Command search popup on the UI kit; the bottom command line is gone

This commit is contained in:
Nathan Dane
2026-10-20 14:48:48 +02:00
parent a3e2fe25bb
commit d45fcce72c
20 changed files with 876 additions and 356 deletions
+13
View File
@@ -1007,6 +1007,19 @@
"sample.plate.name": "Sample Plate",
"sample.vents.about": "Slots in a rectangular pattern: rows, columns and pitch are parameters",
"sample.vents.name": "Vent Plate",
"search.command_keys": "Enter run Shift+Enter run and keep open Esc close",
"search.commands": "Commands",
"search.design": "In this design",
"search.feature": "Feature",
"search.invalid": "Not valid",
"search.keys": "↑ ↓ choose Enter run Tab fill name Esc close",
"search.no_match": "No command matches '{query}'",
"search.parameter": "Parameter",
"search.recent": "Recent",
"search.run": "Run command",
"search.suggest": "Did you mean {label}?",
"search.try": "Type a command name, a feature in this design, or a parameter. To run a command with values, type its id and a JSON object: {example}",
"search.valid": "Valid",
"settings.display_quality_note": "Finer levels draw curved faces and edges smoother and take longer to mesh. Only the viewport changes, never the design or exports.",
"settings.frame_rate_note": "Shows frames per second in the view's bottom-right corner. While it is on, the view redraws continuously.",
"settings.measure_axis_distances": "Show X/Y/Z distances",
+13
View File
@@ -1007,6 +1007,19 @@
"sample.plate.name": "サンプル プレート",
"sample.vents.about": "矩形パターンに並んだスロット: 行数、列数、ピッチはパラメータ",
"sample.vents.name": "通気プレート",
"search.command_keys": "Enter 実行 Shift+Enter 実行して開いたままにする Esc 閉じる",
"search.commands": "コマンド",
"search.design": "このデザイン内",
"search.feature": "フィーチャー",
"search.invalid": "無効",
"search.keys": "↑ ↓ 選択 Enter 実行 Tab 名前を補完 Esc 閉じる",
"search.no_match": "「{query}」に一致するコマンドはありません",
"search.parameter": "パラメーター",
"search.recent": "最近使った項目",
"search.run": "コマンドを実行",
"search.suggest": "{label} ですか?",
"search.try": "コマンド名、このデザインのフィーチャー、またはパラメーターを入力します。値を指定して実行するには、IDとJSONオブジェクトを入力します:{example}",
"search.valid": "有効",
"settings.display_quality_note": "細かいほど曲面とエッジが滑らかに表示されますが、メッシュの生成に時間がかかります。変わるのはビューポートだけで、設計やエクスポートは変わりません。",
"settings.frame_rate_note": "ビューの右下に 1 秒あたりのフレーム数を表示します。オンの間、ビューは常に再描画されます。",
"settings.measure_axis_distances": "計測のX・Y・Z距離を表示",
+13
View File
@@ -1007,6 +1007,19 @@
"sample.plate.name": "示例板",
"sample.vents.about": "按矩形阵列排列的槽:行数、列数和间距均为参数",
"sample.vents.name": "通风板",
"search.command_keys": "Enter 运行 Shift+Enter 运行并保持打开 Esc 关闭",
"search.commands": "命令",
"search.design": "此设计中",
"search.feature": "特征",
"search.invalid": "无效",
"search.keys": "↑ ↓ 选择 Enter 运行 Tab 补全名称 Esc 关闭",
"search.no_match": "没有与“{query}”匹配的命令",
"search.parameter": "参数",
"search.recent": "最近使用",
"search.run": "运行命令",
"search.suggest": "您是否想找 {label}?",
"search.try": "输入命令名称、此设计中的特征或参数。要带值运行命令,请输入其ID和JSON对象:{example}",
"search.valid": "有效",
"settings.display_quality_note": "级别越精细,曲面和边显示越平滑,但网格生成耗时更长。只影响视口,不影响设计或导出。",
"settings.frame_rate_note": "在视图右下角显示每秒帧数。开启时视图会持续重绘。",
"settings.measure_axis_distances": "显示 X/Y/Z 距离",
+10
View File
@@ -44,6 +44,8 @@ impl Tokens {
form_primary: Color32::from_rgb(35, 110, 173),
form_error: Color32::from_rgb(161, 52, 44),
form_error_fill: Color32::from_rgb(252, 239, 237),
form_success: Color32::from_rgb(39, 107, 44),
form_success_fill: Color32::from_rgb(229, 242, 230),
control_radius: 6,
form_label_width: 70.0,
form_gap_y: 5.0,
@@ -346,6 +348,8 @@ impl Tokens {
t.form_primary = t.accent;
t.form_error = t.error;
t.form_error_fill = t.timeline_item_error;
t.form_success = Color32::from_rgb(143, 219, 154);
t.form_success_fill = Color32::from_rgb(44, 74, 51);
t
}
@@ -363,6 +367,12 @@ impl Tokens {
t.analysis.draft = [positive, [0.95, 0.90, 0.60], negative];
t.analysis.access = [positive, negative];
t.analysis.hatch = true;
// Keep validation badges separate from red errors under both red-green
// simulations, while retaining their explicit Valid / Not valid labels.
t.form_success_fill = if dark { Color32::from_rgb(44, 57, 67) } else { Color32::from_rgb(227, 227, 246) };
if !dark {
t.form_success = Color32::from_rgb(39, 88, 78);
}
// The icons that show the same meanings follow; on the dark toolbar the blue is a little
// stronger, to stay clear of the icon fill.
let good = if dark { Color32::from_rgb(35, 115, 245) } else { Color32::from_rgb(51, 115, 230) };
+38 -2
View File
@@ -281,7 +281,15 @@ fn groups(t: &Tokens) -> Vec<Group> {
group("card text", &[("form_ink", t.form_ink), ("form_error", t.form_error)], &[("dialog_body", t.dialog_body)]),
group("card hints", &[("form_dim", t.form_dim)], &[("dialog_body", t.dialog_body)]),
group("card primary", &[("form_primary", t.form_primary)], &[("dialog_body", t.dialog_body)]),
group("card validation", &[("form_error", t.form_error)], &[("form_error_fill", t.form_error_fill)]),
// Validation is identified by its words as well as colour. Measure both the
// ink and badge surfaces against the corresponding failure states.
group(
"card validation",
&[("form_success", t.form_success), ("form_error", t.form_error)],
&[("form_success_fill", t.form_success_fill), ("form_error_fill", t.form_error_fill)],
),
group("validation status", &[("form_success", t.form_success), ("error", t.error)], &[("panel", t.panel)]),
group("validation surfaces", &[("form_success_fill", t.form_success_fill), ("form_error_fill", t.form_error_fill)], &[]),
group("UI text", &[("error", t.error), ("warning", t.warning), ("text", t.text)], &[("panel", t.panel)]),
group("origin axes", &[("axis_x", t.axis_x), ("axis_y", t.axis_y), ("axis_z", t.axis_z)], &[("viewport_top", t.viewport_top)]),
group("view triad", &[("triad[0]", t.triad[0]), ("triad[1]", t.triad[1]), ("triad[2]", t.triad[2])], &[("viewport_top", t.viewport_top)]),
@@ -738,10 +746,11 @@ fn each_mode_changes_only_its_table() {
"form_accent",
"sketch_accent",
"preview_sketch",
"form_success_fill",
];
let mut red_green_light =
red_green_both.into_iter().filter(|name| !["surface_accent", "mesh_accent", "form_accent"].contains(name)).collect::<Vec<_>>();
red_green_light.extend(["sketch_projected", "sketch_locked", "timeline_item_error", "construction_geom", "glyph_text"]);
red_green_light.extend(["sketch_projected", "sketch_locked", "timeline_item_error", "construction_geom", "glyph_text", "form_success"]);
for (dark, mode, want) in [
(false, ColorVision::Protan, set(&red_green_light)),
(true, ColorVision::Protan, set(&red_green_both)),
@@ -821,6 +830,33 @@ fn every_mode_keeps_colours_apart_for_its_eye() {
}
}
/// Badge meaning must survive each simulation even for subtle default tints (which
/// the general groups check may otherwise skip when they are close for normal vision).
#[test]
fn validation_badges_are_distinct_and_readable_in_every_mode() {
let mut failures = Vec::new();
for dark in [false, true] {
for mode in std::iter::once(ColorVision::Off).chain(MODES) {
let t = Tokens::themed(dark, mode);
for (name, other) in [("form_error", t.form_error), ("error", t.error)] {
let distance = worst(mode, rgb(t.form_success), rgb(other));
if distance < FLOOR {
failures.push(format!("{mode:?} dark={dark} form_success vs {name}: {distance:.2}"));
}
}
let distance = worst(mode, rgb(t.form_success_fill), rgb(t.form_error_fill));
if distance < FLOOR {
failures.push(format!("{mode:?} dark={dark} validation fills: {distance:.2}"));
}
let contrast = crate::theme::contrast_ratio(t.form_success, t.form_success_fill);
if contrast < 4.5 {
failures.push(format!("{mode:?} dark={dark} success contrast: {contrast:.2}"));
}
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
#[test]
fn the_shader_gets_the_modes_colours_and_its_stripes() {
for dark in [false, true] {
+12
View File
@@ -408,6 +408,18 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
ok(json!(app.cam))
}
"ui.camera" => wrap(camera(app, p)),
"ui.palette" => {
if p.get("open").and_then(Value::as_bool) == Some(false) {
app.ui.palette_open = false;
app.sbox.text.clear();
} else {
app.start("ui.palette");
if let Some(query) = s("text") {
app.sbox.text = query.chars().take(crate::shortcut_box::MAX_QUERY).collect();
}
}
ok(json!({"open": app.ui.palette_open, "text": app.sbox.text}))
}
"ui.start" => {
let Some(id) = s("command") else { return err("missing `command`") };
// `params`: what the dialog opens on. Refused: nothing starts, or the dialog closes.
+4
View File
@@ -813,6 +813,10 @@ impl SolveApp {
/// Start a command the way a toolbar click does: interactive tools and dialogs for commands
/// that have them, otherwise run it with defaults.
pub fn start(&mut self, id: &str) {
if id == "ui.palette" {
shortcut_box::open(self, None);
return;
}
// A file is loading: the design waits for it.
if self.file_load.busy() || self.file_picker.is_some() {
return;
-160
View File
@@ -1,160 +0,0 @@
//! The command line / palette: type a command id with JSON parameters
//! (`Extrude {"distance": 20}`), or part of a command name to search (press S anywhere).
use egui::{RichText, vec2};
use serde_json::Value;
use solidcraft_engine::command_specs;
use crate::SolveApp;
use crate::theme::Tokens;
#[derive(Default)]
pub struct Palette {
pub text: String,
pub history: Vec<String>,
focus: bool,
}
/// Commands whose id or label matches the query: (id, label in the current language, icon).
/// The label matches in the current language and in English, so a name typed in either finds
/// the command.
pub fn matches(q: &str) -> Vec<(&'static str, &'static str, &'static str)> {
let q = q.trim().to_lowercase();
let mut v: Vec<(bool, bool, &'static str, &'static str, &'static str)> = command_specs()
.into_iter()
.filter_map(|c| {
let label = crate::i18n::tr_label(c.label);
let (shown, english, id) = (label.to_lowercase(), c.label.to_lowercase(), c.id.to_lowercase());
let found = q.is_empty() || shown.contains(&q) || english.contains(&q) || id.contains(&q);
found.then(|| (!(shown.starts_with(&q) || english.starts_with(&q)), !id.starts_with(&q), label, c.id, c.icon))
})
.collect();
v.sort();
v.into_iter().map(|(_, _, label, id, icon)| (id, label, icon)).collect()
}
/// Execute a line of palette input.
pub fn submit(app: &mut SolveApp, line: &str) {
let line = line.trim();
if line.is_empty() {
return;
}
app.palette.history.push(line.to_string());
let (id, rest) = match line.find(|c: char| c.is_whitespace() || c == '{') {
Some(i) => (&line[..i], line[i..].trim()),
None => (line, ""),
};
if solidcraft_engine::find_command(id).is_some() {
if rest.is_empty() {
app.start(id);
} else {
match serde_json::from_str::<Value>(rest) {
Ok(p) => {
let _ = app.run(id, p);
}
Err(e) => app.set_status(format!("parameters must be JSON: {e}"), true),
}
}
return;
}
if let Some((id, _, _)) = matches(line).first() {
app.start(id);
} else {
app.set_status(format!("no command matches `{line}`"), true);
}
}
pub fn palette_bar(app: &mut SolveApp, ui: &mut egui::Ui) {
let t = Tokens::get();
egui::Panel::bottom("sc_palette").exact_size(28.0).frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(8, 3))).show(
ui,
|ui| {
ui.horizontal_centered(|ui| {
ui.label(RichText::new(">").strong().color(t.accent));
let r = ui.add(
egui::TextEdit::singleline(&mut app.palette.text)
// The JSON example keeps its braces here rather than in the catalog, so the
// placeholder parser never has to treat JSON punctuation as a name.
.hint_text(crate::i18n::format("ui.command_palette_hint", &[("example", "Extrude {\"distance\": 20}")]))
.desired_width(520.0),
);
if app.palette.focus {
r.request_focus();
app.palette.focus = false;
}
if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
let line = std::mem::take(&mut app.palette.text);
submit(app, &line);
}
if let Some(last) = app.session.log.last() {
ui.label(RichText::new(last).size(t.font_caption).color(t.text_dim));
}
});
},
);
}
/// The search popup (S).
pub fn popup(app: &mut SolveApp, ctx: &egui::Context) {
if !app.ui.palette_open {
return;
}
let mut open = true;
let mut picked: Option<&'static str> = None;
let t = Tokens::get();
let center = ctx.content_rect().center();
crate::frame::window(ctx, crate::i18n::tr_label("Search commands"), crate::frame::Width::Normal)
.id(egui::Id::new("sc_search"))
.pivot(egui::Align2::LEFT_TOP)
.fixed_pos(egui::pos2(center.x - 200.0, 150.0))
.fixed_size(vec2(400.0, 340.0))
.collapsible(false)
.open(&mut open)
.show(ctx, |ui| {
let r = ui.add(egui::TextEdit::singleline(&mut app.palette.text).hint_text(crate::i18n::tr_label("command name")).desired_width(380.0));
// Read Enter before taking the focus back (lost_focus reads the focus as it is now).
let entered = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
r.request_focus();
let list = matches(&app.palette.text);
if entered {
picked = list.first().map(|x| x.0);
}
egui::ScrollArea::vertical().max_height(280.0).show(ui, |ui| {
for (id, label, icon) in list.iter().take(60) {
let enabled = solidcraft_engine::find_command(id).is_some_and(|c| c.info(&app.session).enabled);
ui.horizontal(|ui| {
let (ir, _) = ui.allocate_exact_size(vec2(18.0, 18.0), egui::Sense::hover());
crate::icons::paint(ui.painter(), ir, icon, t.icon, t.icon_fill, t.accent);
if ui.add_enabled(enabled, egui::Button::new(*label).frame(false)).clicked() {
picked = Some(id);
}
ui.label(RichText::new(*id).size(t.font_panel).color(t.text_dim));
});
}
});
});
if let Some(id) = picked {
app.palette.text.clear();
app.ui.palette_open = false;
app.start(id);
} else if !open || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
app.ui.palette_open = false;
app.palette.text.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The command line finds a name typed in the current language or in English (#2544).
#[test]
fn matches_finds_a_name_in_the_current_language_and_in_english() {
let _ja = crate::i18n::scope("ja");
let name = crate::i18n::Locale::for_language("ja").text("cmd.sketch_rectangle_center");
for query in [name, "Center Rectangle", "sketch.rectangle.center"] {
let found = matches(query);
assert_eq!(found.first().map(|m| (m.0, m.1)), Some(("sketch.rectangle.center", name)), "{query:?}");
}
}
}
+453 -180
View File
@@ -1,23 +1,21 @@
//! The S box: a command search that opens at the cursor (the S key). It searches every command by
//! name, id, toolbar tab and panel with a forgiving (fuzzy) match. With nothing typed it lists
//! the recent commands first. Pinned commands sit in a row of icons on top, a small toolbar of
//! favourites. Up/Down choose, Enter runs, Esc closes. Recent and pinned commands are kept
//! between runs.
//! Ribbon-anchored command search. Ranking comes from the registry; document results use
//! existing feature-edit and parameter commands. JSON mode never starts an interactive tool.
use egui::{Align2, FontId, Pos2, Rect, Sense, Stroke, pos2, vec2};
use egui::{Pos2, Rect, pos2, vec2};
use serde_json::{Value, json};
use solidcraft_engine::command_specs;
use crate::theme::Tokens;
use crate::{SolveApp, icons, ui_kit};
use crate::{SolveApp, ui_kit};
/// How many recent commands are kept.
const RECENT: usize = 12;
const W: f32 = 340.0;
pub(crate) const MAX_QUERY: usize = 4096;
const MAX_RESULTS: usize = 80;
#[derive(Default)]
pub struct ShortcutBox {
/// Where it opened (the cursor), while open.
/// Fallback anchor when there is no ribbon (headless tests).
at: Option<Pos2>,
/// The highlighted row.
index: usize,
@@ -30,6 +28,7 @@ pub struct ShortcutBox {
/// Most recent first.
pub recent: Vec<String>,
pub pinned: Vec<String>,
design: Option<(u64, Vec<DesignRow>)>,
}
impl ShortcutBox {
@@ -38,13 +37,19 @@ impl ShortcutBox {
}
pub fn load(&mut self, v: &Value) {
let list = |k: &str| -> Vec<String> {
v.get(k).and_then(Value::as_array).map(|a| a.iter().take(64).filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
v.get(k)
.and_then(Value::as_array)
.map(|a| a.iter().take(64).filter_map(|x| x.as_str().filter(|s| s.len() <= 256).map(str::to_string)).collect())
.unwrap_or_default()
};
self.recent = list("recent");
self.pinned = list("pinned");
}
/// A command was run from the box: it goes to the front of the recent list.
pub fn used(&mut self, id: &str) {
if solidcraft_engine::find_command(id).is_none() {
return;
}
self.recent.retain(|r| r != id);
self.recent.insert(0, id.to_string());
self.recent.truncate(RECENT);
@@ -120,7 +125,7 @@ pub fn search(app: &SolveApp, q: &str) -> Vec<Row> {
.max(score(&q, c.id) * 9 / 10)
.max(score(&q, tab).max(score(&q, home_tab)) / 3)
.max(score(&q, panel).max(score(&q, home_panel)) / 3);
let recent = app.sbox.recent.iter().position(|r| r == c.id).map_or(0, |i| 2000 - i as u32);
let recent = app.sbox.recent.iter().position(|r| r == c.id).map_or(0, |i| 2000u32.saturating_sub(i.min(2000) as u32));
// Commands that can run now come before those that can't.
let usable = if c.info(&app.session).enabled { 150 } else { 0 };
(s > 0).then_some((s + usable + if q.is_empty() { recent } else { recent / 20 }, (c.id, label, c.icon, place)))
@@ -130,32 +135,113 @@ pub fn search(app: &SolveApp, q: &str) -> Vec<Row> {
v.into_iter().map(|(_, row)| row).collect()
}
/// A row's right-hand side, ending at `at`: the shortcut, then where the command lives
/// ("Sketch › Create"). The separator is drawn, centred on the ink of the panel's name: a
/// font's "›", or one centred on the row, sits low beside Japanese or Chinese words.
fn paint_key_and_place(painter: &egui::Painter, at: Pos2, key: &str, place: Option<(&str, &str)>, color: egui::Color32) {
let font = FontId::proportional(crate::theme::Tokens::get().font_panel);
// One piece of text ending at `x`, centred on the row: its left edge and the middle of its ink.
let piece = |x: f32, text: &str| -> (f32, f32) {
let galley = painter.layout_no_wrap(text.to_string(), font.clone(), color);
let pos = pos2(x - galley.size().x, at.y - galley.size().y / 2.0);
let ink = galley
.rows
.first()
.filter(|r| r.row.visuals.mesh_bounds.is_positive())
.map_or(galley.size().y / 2.0, |r| r.pos.y + r.row.visuals.mesh_bounds.center().y);
painter.galley(pos, galley, color);
(pos.x, pos.y + ink)
#[derive(Clone, Debug)]
enum DesignTarget {
Feature(u64),
Parameter(String),
}
#[derive(Clone, Debug)]
struct DesignRow {
label: String,
detail: String,
icon: &'static str,
target: DesignTarget,
}
fn bounded(text: &str) -> String {
text.chars().take(MAX_QUERY).collect()
}
fn design_rows(app: &mut SolveApp, query: &str) -> Vec<DesignRow> {
if app.sbox.design.as_ref().is_none_or(|(revision, _)| *revision != app.session.revision) {
let doc = &app.session.doc;
let params = doc.param_rows();
let values: std::collections::BTreeMap<_, _> = params.iter().take(20_000).map(|p| (p.name.as_str(), p)).collect();
let mut rows = Vec::new();
for feature in doc.features.iter().take(10_000) {
let value = feature
.param_names
.iter()
.take(64)
.find_map(|name| values.get(name.as_str()))
.map(|p| p.value.filter(|v| v.is_finite()).map_or_else(|| bounded(&p.expression), |v| format!("{v} {}", p.unit)))
.unwrap_or_default();
rows.push(DesignRow {
label: bounded(&feature.name),
detail: format!("{} · {value}", crate::i18n::tr("search.feature")),
icon: crate::timeline::icon_of(&feature.kind),
target: DesignTarget::Feature(feature.id),
});
}
let icon = solidcraft_engine::find_command("parameters.change").map_or("", |c| c.icon);
for p in params.iter().filter(|p| p.source == "user").take(10_000) {
let value = p.value.filter(|v| v.is_finite()).map_or_else(|| bounded(&p.expression), |v| format!("{v} {}", p.unit));
rows.push(DesignRow {
label: bounded(&p.name),
detail: format!("{} · {value}", crate::i18n::tr("search.parameter")),
icon,
target: DesignTarget::Parameter(p.name.clone()),
});
}
app.sbox.design = Some((app.session.revision, rows));
}
let q = query.trim().to_lowercase();
let mut rows: Vec<_> = app
.sbox
.design
.as_ref()
.into_iter()
.flat_map(|(_, rows)| rows)
.filter_map(|row| {
let rank = score(&q, &row.label);
(rank > 0).then_some((rank, row.clone()))
})
.collect();
rows.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.label.cmp(&b.1.label)));
rows.into_iter().take(24).map(|(_, row)| row).collect()
}
/// Same split, serde parser and error messages as the original command line.
fn typed(line: &str) -> Option<(&str, Result<Value, String>)> {
let line = line.trim();
if !line.contains('{') {
return None;
}
let split = line.find(|c: char| c.is_whitespace() || c == '{').unwrap_or(line.len());
let id = line.get(..split).unwrap_or_default();
let rest = line.get(split..).unwrap_or_default().trim();
let result = if solidcraft_engine::find_command(id).is_none() {
Err(crate::i18n::format("shortcut.no_command", &[("id", id)]))
} else {
serde_json::from_str::<Value>(rest).map_err(|e| crate::i18n::format("shortcut.json_error", &[("error", &e.to_string())]))
};
let mut x = at.x;
if let Some((tab, panel)) = place {
let (left, ink) = piece(x, panel);
icons::glyphs::breadcrumb(painter, pos2(left - 5.0, ink), color);
x = piece(left - 10.0, tab).0 - 14.0;
}
if !key.is_empty() {
piece(x, key);
}
Some((id, result))
}
/// Bounded Levenshtein distance also handles transposed/missing letters in a no-match query.
fn closest(query: &str) -> Option<&'static str> {
let q: Vec<_> = query.trim().to_lowercase().chars().take(128).collect();
command_specs()
.into_iter()
.map(|c| {
let label = crate::i18n::tr_label(c.label);
let mut prev: Vec<_> = (0..=q.len()).collect();
for (j, ch) in label.to_lowercase().chars().take(128).enumerate() {
let mut next = vec![j + 1];
for (i, qc) in q.iter().enumerate() {
next.push(
(prev.get(i).copied().unwrap_or(128) + usize::from(ch != *qc))
.min(prev.get(i + 1).copied().unwrap_or(128) + 1)
.min(next.last().copied().unwrap_or(128) + 1),
);
}
prev = next;
}
(prev.last().copied().unwrap_or(128), label)
})
.min()
.map(|(_, label)| label)
}
/// Open the box at a point (the cursor), or at the middle of the window.
@@ -165,36 +251,28 @@ pub fn open(app: &mut SolveApp, at: Option<Pos2>) {
app.sbox.index = 0;
app.sbox.text.clear();
app.sbox.focus = true;
app.sbox.design = None;
}
/// A line typed as `command.id {"param": value}`: the command runs at once with those parameters
/// (the same entry the bottom command line used to take).
fn run_typed(app: &mut SolveApp, line: &str) {
let line = line.trim();
app.ui.palette_open = false;
app.sbox.at = None;
app.sbox.text.clear();
let split = line.find(|c: char| c.is_whitespace() || c == '{').unwrap_or(line.len());
let (id, rest) = (line.get(..split).unwrap_or_default(), line.get(split..).unwrap_or_default().trim());
let Some(command) = solidcraft_engine::find_command(id) else {
app.set_status(crate::i18n::format("shortcut.no_command", &[("id", id)]), true);
return;
};
match serde_json::from_str::<Value>(rest) {
Ok(params) => {
app.sbox.used(command.id);
let _ = app.run(command.id, params);
if let Some((id, result)) = typed(line) {
match result {
Ok(params) => {
app.sbox.used(id);
let _ = app.run(id, params);
}
Err(error) => app.set_status(error, true),
}
Err(e) => app.set_status(crate::i18n::format("shortcut.json_error", &[("error", &e.to_string())]), true),
}
close(app);
}
fn run(app: &mut SolveApp, id: &str) {
app.sbox.used(id);
fn close(app: &mut SolveApp) {
app.ui.palette_open = false;
app.sbox.at = None;
app.sbox.text.clear();
app.start(id);
}
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
@@ -205,152 +283,238 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
let t = Tokens::get();
let screen = ctx.content_rect();
// Opened without `open` (a feature edit that falls through to the box): focus once.
if app.sbox.at.is_none() {
app.sbox.focus = true;
}
let at = *app.sbox.at.get_or_insert_with(|| ctx.input(|i| i.pointer.latest_pos()).unwrap_or(screen.center()));
let list = search(app, &app.sbox.text);
let (up, down, enter, esc) = ctx.input(|i| {
(i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape))
});
if down {
app.sbox.index = (app.sbox.index + 1).min(list.len().saturating_sub(1));
}
if up {
app.sbox.index = app.sbox.index.saturating_sub(1);
}
let mut picked: Option<&'static str> = None;
let mut pin: Option<&'static str> = None;
let mut menu: Option<(Pos2, &'static str)> = None;
let w = W.min((screen.width() - 8.0).max(32.0));
let h = 380.0_f32.min((screen.height() - 8.0).max(120.0));
let fallback = *app.sbox.at.get_or_insert(screen.center());
let anchor =
ctx.data(|d| d.get_temp::<Rect>(egui::Id::new("sc_ribbon_search"))).map(|r| r.left_bottom() + vec2(0.0, t.space_6)).unwrap_or(fallback);
let anchor = if anchor.x.is_finite() && anchor.y.is_finite() { anchor } else { screen.center() };
app.sbox.text = bounded(&app.sbox.text);
let width = ui_kit::CommandSearch::width().min((screen.width() - t.space_8).max(t.space_24));
let height = (screen.height() - anchor.y - t.space_8).max(t.space_24 * 4.0);
let pos = pos2(
at.x.clamp(screen.left() + 4.0, (screen.right() - w - 4.0).max(screen.left() + 4.0)),
at.y.clamp(screen.top() + 4.0, (screen.bottom() - h).max(screen.top() + 4.0)),
anchor.x.clamp(screen.left() + t.space_4, (screen.right() - width - t.space_4).max(screen.left() + t.space_4)),
anchor.y.max(screen.top() + t.space_4),
);
let resp = crate::frame::area(egui::Id::new("sc_sbox")).fixed_pos(pos).order(egui::Order::Foreground).show(ctx, |ui| {
crate::context_menu::menu_frame(ui, |ui| {
ui_kit::scope(ui, |ui| {
ui.set_width(w - 10.0);
// Pinned commands: a mini toolbar.
if !app.sbox.pinned.is_empty() {
ui.horizontal_wrapped(|ui| {
for id in app.sbox.pinned.clone() {
let Some(c) = solidcraft_engine::find_command(&id) else { continue };
let (r, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click());
if resp.hovered() {
ui.painter().rect_filled(r, 4.0, t.hover);
}
icons::paint(ui.painter(), r.shrink(5.0), c.icon, t.icon, t.icon_fill, t.accent);
if resp.on_hover_text(crate::i18n::tr_label(c.label)).clicked() {
picked = Some(c.id);
}
}
});
ui.separator();
let (up, down, enter, esc, tab, keep) = ctx.input(|i| {
(
i.key_pressed(egui::Key::ArrowUp),
i.key_pressed(egui::Key::ArrowDown),
i.key_pressed(egui::Key::Enter),
i.key_pressed(egui::Key::Escape),
i.key_pressed(egui::Key::Tab),
i.modifiers.shift,
)
});
let mut picked = None;
let mut menu = None;
let mut rows = Vec::new();
let mut design = Vec::new();
let mut mode = None;
let response = crate::frame::area(egui::Id::new("sc_sbox")).fixed_pos(pos).order(egui::Order::Foreground).fade_in(false).show(ctx, |ui| {
ui.set_width(width);
ui.spacing_mut().item_spacing.y = t.space_6;
ui_kit::scope(ui, |ui| {
ui.spacing_mut().item_spacing.y = t.space_6;
let invalid = typed(&app.sbox.text).is_some_and(|(_, result)| result.is_err());
let field = ui_kit::CommandSearch::field(ui, &mut app.sbox.text, invalid, std::mem::take(&mut app.sbox.focus), MAX_QUERY);
if field.changed() {
app.sbox.index = 0;
}
mode = typed(&app.sbox.text).map(|(id, result)| (id.to_owned(), result));
if mode.is_none() {
rows = search(app, &app.sbox.text)
.into_iter()
.filter(|r| {
!app.sbox.text.trim().is_empty()
|| (app.sbox.recent.is_empty() && app.sbox.pinned.is_empty())
|| app.sbox.recent.iter().chain(&app.sbox.pinned).any(|id| id == r.0)
})
.take(if app.sbox.text.trim().is_empty() {
if app.sbox.recent.is_empty() && app.sbox.pinned.is_empty() { 8 } else { MAX_RESULTS }
} else {
56
})
.collect();
design = if app.sbox.text.trim().is_empty() { Vec::new() } else { design_rows(app, &app.sbox.text.clone()) };
}
let enabled: Vec<_> = rows
.iter()
.map(|r| solidcraft_engine::find_command(r.0).is_some_and(|c| c.info(&app.session).enabled))
.chain(design.iter().map(|_| true))
.take(MAX_RESULTS)
.collect();
if down || up {
let step = if down { 1 } else { enabled.len().saturating_sub(1) };
for _ in 0..enabled.len() {
app.sbox.index = (app.sbox.index + step) % enabled.len().max(1);
if enabled.get(app.sbox.index).copied().unwrap_or(false) {
break;
}
}
let te = ui_kit::search_field(ui, egui::Id::new("sc_sbox_text"), &mut app.sbox.text, crate::i18n::tr_label("Search commands"));
crate::scenario::publish_rect("shortcut:search", te.rect);
if std::mem::take(&mut app.sbox.focus) {
te.request_focus();
}
if te.changed() {
app.sbox.index = 0;
}
ui.add_space(4.0);
if app.sbox.text.trim().is_empty() && !app.sbox.recent.is_empty() {
ui.label(egui::RichText::new(crate::i18n::tr_label("RECENT")).size(crate::theme::Tokens::get().font_micro).color(t.text_dim));
}
egui::ScrollArea::vertical().max_height(h - 90.0).show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
for (i, (id, label, icon, place)) in list.iter().enumerate().take(80) {
let enabled = solidcraft_engine::find_command(id).is_some_and(|c| c.info(&app.session).enabled);
let (r, resp) = ui.allocate_exact_size(vec2(w - 20.0, 26.0), Sense::click());
let lit = i == app.sbox.index || resp.hovered();
if lit {
ui.painter().rect_filled(r, 4.0, t.hover);
if i == app.sbox.index && (up || down) {
ui.scroll_to_rect(r, None);
}
}
let ink = if enabled { t.icon } else { t.border };
icons::paint(
ui.painter(),
Rect::from_center_size(pos2(r.left() + 14.0, r.center().y), vec2(16.0, 16.0)),
icon,
ink,
t.icon_fill,
t.accent,
}
app.sbox.index = app.sbox.index.min(enabled.len().saturating_sub(1));
if !enabled.get(app.sbox.index).copied().unwrap_or(false) {
app.sbox.index = enabled.iter().position(|v| *v).unwrap_or(0);
}
ui_kit::Menu::show(ui, width, |ui| {
egui::ScrollArea::vertical().max_height((height - t.control_height * 4.0).max(t.control_height)).show(ui, |ui| {
if let Some((id, result)) = &mode {
let mut row = ui_kit::MenuItem::new(
"search:run",
crate::i18n::tr("search.run"),
solidcraft_engine::find_command(id).map_or("", |c| c.icon),
);
let col = if enabled { t.text } else { t.text_dim };
ui.painter().text(
pos2(r.left() + 30.0, r.center().y),
Align2::LEFT_CENTER,
label,
FontId::proportional(crate::theme::Tokens::get().font_button),
col,
);
let key = crate::keymap::effective(app, id).unwrap_or_default();
paint_key_and_place(ui.painter(), pos2(r.right() - 26.0, r.center().y), &key, *place, t.text_dim);
// The pin.
let pinned = app.sbox.pinned.iter().any(|p| p == id);
let pr = Rect::from_center_size(pos2(r.right() - 11.0, r.center().y), vec2(16.0, 16.0));
let presp = ui.interact(pr, ui.id().with(("pin", *id)), Sense::click());
if pinned || lit {
let c = pr.center();
let pts: Vec<Pos2> = (0..10)
.map(|k| {
let a = std::f32::consts::PI * (k as f32 / 5.0) - std::f32::consts::FRAC_PI_2;
let rr = if k % 2 == 0 { 6.0 } else { 2.6 };
c + vec2(a.cos() * rr, a.sin() * rr)
})
.collect();
if pinned {
ui.painter().add(egui::Shape::convex_polygon(pts.clone(), t.warning, Stroke::NONE));
row.enabled = result.is_ok();
row.highlighted = true;
let badge = crate::i18n::tr(if result.is_ok() { "search.valid" } else { "search.invalid" });
row.shortcut = badge;
if row
.search_row(ui, "", id, Some(if result.is_ok() { ui_kit::SearchBadge::Valid } else { ui_kit::SearchBadge::Invalid }))
.clicked()
{
picked = Some(0);
}
match result {
Ok(params) => {
ui_kit::CommandSearch::detail(ui, &format!("{id}\n{}", serde_json::to_string_pretty(params).unwrap_or_default()))
}
Err(error) => {
ui_kit::text(ui, error, ui_kit::Text::Error("command_parameters"));
}
ui.painter().add(egui::Shape::closed_line(pts, Stroke::new(1.0, if pinned { t.warning } else { t.text_dim })));
}
if presp.on_hover_text(crate::i18n::tr(if pinned { "shortcut.unpin" } else { "shortcut.pin" })).clicked() {
pin = Some(id);
} else if resp.clicked() && enabled {
picked = Some(id);
} else {
let empty = app.sbox.text.trim().is_empty();
let mut last_recent = None;
for (index, (id, label, icon, place)) in rows.iter().enumerate() {
let recent = empty && app.sbox.recent.iter().any(|r| r == id);
if last_recent != Some(recent) {
let count = rows.iter().filter(|r| (empty && app.sbox.recent.iter().any(|id| id == r.0)) == recent).count();
ui_kit::CommandSearch::heading(ui, if recent { "search.recent" } else { "search.commands" }, count);
last_recent = Some(recent);
}
let mut item = ui_kit::MenuItem::new(id, label, icon);
item.enabled = enabled.get(index).copied().unwrap_or(false);
item.highlighted = index == app.sbox.index;
let shortcut = crate::keymap::effective(app, id).unwrap_or_default();
item.shortcut = &shortcut;
let path = place.map_or_else(|| id.to_string(), |(tab, panel)| format!("{tab} › {panel}"));
let response = item.search_row(ui, &app.sbox.text, &path, None);
if item.highlighted && (up || down) {
ui.scroll_to_rect(response.rect, None);
}
if response.clicked() {
picked = Some(index);
}
if response.secondary_clicked() {
menu = Some((response.rect.left_bottom(), (*id).to_owned()));
}
}
if resp.secondary_clicked() {
menu = Some((resp.interact_pointer_pos().unwrap_or(r.left_bottom()), id));
if !design.is_empty() {
ui_kit::CommandSearch::heading(ui, "search.design", design.len());
}
for (index, row) in design.iter().enumerate() {
let handle = format!("search:design:{index}");
let mut item = ui_kit::MenuItem::new(&handle, &row.label, row.icon);
item.highlighted = app.sbox.index == rows.len() + index;
let badge = crate::i18n::tr(match row.target {
DesignTarget::Feature(_) => "search.feature",
DesignTarget::Parameter(_) => "search.parameter",
});
item.shortcut = badge;
let response = item.search_row(ui, &app.sbox.text, &row.detail, Some(ui_kit::SearchBadge::Kind));
if item.highlighted && (up || down) {
ui.scroll_to_rect(response.rect, None);
}
if response.clicked() {
picked = Some(rows.len() + index);
}
}
if rows.is_empty() && design.is_empty() {
ui.add_space(t.space_16);
ui.with_layout(egui::Layout::top_down(egui::Align::Center), |ui| {
ui_kit::text(
ui,
&crate::i18n::format("search.no_match", &[("query", &app.sbox.text)]),
ui_kit::Text::Heading("search_no_match"),
);
if let Some(label) = closest(&app.sbox.text) {
ui_kit::text(
ui,
&crate::i18n::format("search.suggest", &[("label", label)]),
ui_kit::Text::Report("search_suggest", false),
);
}
});
ui.add_space(t.space_8);
}
if empty {
ui_kit::text(
ui,
&crate::i18n::format("search.try", &[("example", r#"solid.extrude {"distance": 20}"#)]),
ui_kit::Text::Note("search_try"),
);
}
}
});
})
ui_kit::CommandSearch::footer(ui, mode.is_some());
});
});
});
crate::scenario::publish_rect("ribbon:search_popup", resp.response.rect);
if let Some(id) = pin {
app.sbox.toggle_pin(id);
}
// A row's menu: pin to the toolbar or the shortcuts.
crate::scenario::publish_target("ribbon:search_popup", response.response.rect);
crate::scenario::publish_target("palette:outer", response.response.rect);
if let Some((at, id)) = menu {
crate::context_menu::open_for(app, at, crate::context_menu::Target::ToolbarCommand { id: id.to_string() });
crate::context_menu::open_for(app, at, crate::context_menu::Target::ToolbarCommand { id });
return;
}
if enter && picked.is_none() && app.sbox.text.contains('{') {
let line = app.sbox.text.clone();
run_typed(app, &line);
return;
if tab && mode.is_none() {
if let Some(row) = rows.get(app.sbox.index) {
app.sbox.text = row.0.to_owned();
} else if let Some(row) = design.get(app.sbox.index.saturating_sub(rows.len())) {
app.sbox.text = row.label.clone();
}
app.sbox.focus = true;
}
if enter
&& picked.is_none()
&& let Some((id, ..)) = list.get(app.sbox.index)
{
picked = Some(id);
if enter || picked.is_some() {
if mode.is_some() {
let line = app.sbox.text.clone();
// Invalid submissions retain the old error, while the field remains editable.
if let Some((_, Err(error))) = &mode {
app.set_status(error.clone(), true);
} else {
run_typed(app, &line);
if keep {
app.ui.palette_open = true;
app.sbox.at = Some(pos);
app.sbox.text = line;
app.sbox.focus = true;
}
}
} else {
let index = picked.unwrap_or(app.sbox.index);
if let Some((id, ..)) = rows.get(index).filter(|r| solidcraft_engine::find_command(r.0).is_some_and(|c| c.info(&app.session).enabled)) {
app.sbox.used(id);
close(app);
app.start(id);
} else if let Some(row) = design.get(index.saturating_sub(rows.len())).filter(|_| index >= rows.len()) {
let target = row.target.clone();
close(app);
match target {
DesignTarget::Feature(id) => app.edit_feature(id),
DesignTarget::Parameter(name) => {
app.start("parameters.change");
if let Some(dialog) = &mut app.params {
dialog.filter = name;
}
}
}
}
}
}
let outside = ctx.input(|i| i.pointer.any_pressed()) && !resp.response.contains_pointer();
if let Some(id) = picked {
run(app, id);
} else if esc || outside {
app.ui.palette_open = false;
app.sbox.at = None;
app.sbox.text.clear();
let outside = ctx.input(|i| i.pointer.any_pressed()) && !response.response.contains_pointer();
if esc || outside {
close(app);
}
}
@@ -478,4 +642,113 @@ mod tests {
assert_eq!(h.app.session.doc.features.len(), before + 1, "{:?}", h.app.status);
assert!(!h.app.ui.palette_open);
}
#[test]
fn command_mode_preserves_parser_and_keeps_invalid_input_editable() {
assert!(typed("solid.box").is_none());
assert_eq!(typed(r#"solid.box {"length":10}"#).unwrap().1.unwrap(), json!({"length":10}));
assert!(typed("solid.box {}").unwrap().1.is_ok());
assert!(typed("not.a.command {}").unwrap().1.unwrap_err().contains("no command"));
let expected = serde_json::from_str::<Value>(r#"{"length": }"#).unwrap_err();
assert_eq!(
typed(r#"solid.box {"length": }"#).unwrap().1.unwrap_err(),
crate::i18n::format("shortcut.json_error", &[("error", &expected.to_string())])
);
let mut h = crate::scenario::Harness::new();
h.app.home.open = false;
h.call("ui.palette", json!({"text": r#"solid.box {"length": }"#}));
h.frames(3);
h.step(&json!({"key":"Enter"})).unwrap();
assert!(h.app.ui.palette_open);
assert!(h.app.sbox.text.contains("length"));
assert!(h.app.status.as_ref().is_some_and(|(s, _, error)| *error && s.contains("JSON")));
assert!(h.app.session.doc.features.is_empty());
}
#[test]
fn shift_enter_runs_json_and_retains_the_query_and_focus() {
let mut h = crate::scenario::Harness::new();
h.app.home.open = false;
let query = r#"solid.box {"length":10,"width":10,"height":10}"#;
h.call("ui.palette", json!({"text":query}));
h.frames(3);
h.step(&json!({"key":"Enter", "shift":true})).unwrap();
h.frames(2);
assert_eq!(h.app.session.doc.features.len(), 1, "{:?}", h.app.status);
assert!(h.app.ui.palette_open);
assert_eq!(h.app.sbox.text, query);
assert!(h.ctx.memory(|m| m.has_focus(egui::Id::new("sc_sbox_text"))));
h.step(&json!({"key":"Enter"})).unwrap();
h.frames(2);
assert_eq!(h.app.session.doc.features.len(), 2);
assert!(!h.app.ui.palette_open);
}
#[test]
fn document_results_open_existing_feature_and_parameter_editors() {
let mut h = crate::scenario::Harness::new();
h.app.home.open = false;
h.app.run("solid.box", json!({"length":6,"width":6,"height":6})).unwrap();
h.app.run("parameters.add", json!({"name":"box_width", "expression":"6 mm"})).unwrap();
let rows = design_rows(&mut h.app, "box");
assert_eq!(rows.len(), 2, "{rows:?}");
assert!(rows.iter().any(|r| matches!(r.target, DesignTarget::Feature(_)) && r.detail.contains("6 mm")));
assert!(rows.iter().any(|r| matches!(r.target, DesignTarget::Parameter(_)) && r.detail.contains("6 mm")));
h.call("ui.palette", json!({"text":"box_width"}));
h.frames(3);
h.step(&json!({"key":"Enter"})).unwrap();
assert!(!h.app.ui.palette_open);
assert_eq!(h.app.params.as_ref().unwrap().filter, "box_width");
h.app.params = None;
h.call("ui.palette", json!({"text":"box"}));
h.frames(3);
h.step(&json!({"click":{"handle":"menu:search:design:0"}})).unwrap();
assert!(!h.app.ui.palette_open);
assert!(h.app.dialog.is_some(), "a feature opens its existing edit dialog");
}
#[test]
fn tab_fills_selected_registry_id_arrows_choose_and_escape_closes() {
let mut h = crate::scenario::Harness::new();
h.app.home.open = false;
h.call("ui.start", json!({"command":"ui.palette"}));
h.frames(3);
h.step(&json!({"text":"solid."})).unwrap();
let first = h.app.sbox.index;
h.step(&json!({"key":"ArrowDown"})).unwrap();
assert_ne!(h.app.sbox.index, first);
h.step(&json!({"key":"ArrowUp"})).unwrap();
assert_eq!(h.app.sbox.index, first);
h.step(&json!({"key":"Tab"})).unwrap();
assert_eq!(h.app.sbox.text, "solid.box");
assert_eq!(crate::scenario::rect_of("palette:outer"), crate::scenario::rect_of("ribbon:search_popup"));
assert_eq!(crate::scenario::rect_of("palette:search"), crate::scenario::rect_of("shortcut:search"));
h.step(&json!({"key":"Escape"})).unwrap();
assert!(!h.app.ui.palette_open && h.app.sbox.text.is_empty());
}
#[test]
fn hostile_queries_and_non_finite_anchors_are_bounded() {
let mut h = crate::scenario::Harness::new();
h.app.home.open = false;
open(&mut h.app, Some(pos2(f32::NAN, f32::INFINITY)));
h.app.sbox.text = "界".repeat(MAX_QUERY * 2);
h.frames(3);
assert_eq!(h.app.sbox.text.chars().count(), MAX_QUERY);
assert!(crate::scenario::rect_of("ribbon:search_popup").unwrap().is_finite());
assert!(crate::scenario::handles("menu:").len() <= MAX_RESULTS);
assert_eq!(closest("fliet"), Some("Fillet"));
h.call("ui.palette", json!({"open":false}));
assert!(!h.app.ui.palette_open);
}
#[test]
fn saved_pins_remain_visible_without_a_query_or_recent_commands() {
let mut h = crate::scenario::Harness::new();
h.app.home.open = false;
h.app.sbox.load(&json!({"pinned":["solid.extrude"]}));
h.call("ui.palette", json!({}));
h.frames(3);
assert!(h.app.sbox.recent.is_empty());
assert!(crate::scenario::rect_of("menu:solid.extrude").is_some());
assert_eq!(crate::scenario::handles("menu:").len(), 1);
}
}
+3
View File
@@ -283,6 +283,9 @@ pub struct Tokens {
pub form_primary: Color32,
pub form_error: Color32,
pub form_error_fill: Color32,
/// Successful validation text and its badge surface.
pub form_success: Color32,
pub form_success_fill: Color32,
/// Corner radius of dense form controls and actions.
pub control_radius: u8,
/// Width of the dense form label column.
+1 -1
View File
@@ -111,7 +111,7 @@ theme_keys! {
sketch_ink, sketch_soft, surface_fill, surface_ink, surface_soft, mesh_fill, mesh_ink, mesh_soft, form_fill, form_tab_ink, form_soft, sheet_fill, sheet_ink, sheet_soft, render_fill, render_ink, render_soft, tab_on_fill_dark,
app_bar_separator, surface_accent, mesh_accent, form_accent, render_accent, on_accent, agent_ok, agent_busy, app_bar_hover_subtle,
app_bar_hover_button, app_bar_hover_strong, app_bar_tab_active,
form_ink, form_dim, form_primary, form_error, form_error_fill, dialog_body, dialog_footer, dialog_rule, control_fill, control_border, dialog_label, selected_ink, selected_bg,
form_ink, form_dim, form_primary, form_error, form_error_fill, form_success, form_success_fill, dialog_body, dialog_footer, dialog_rule, control_fill, control_border, dialog_label, selected_ink, selected_bg,
],
many: [triad, gizmo, continuity, app_bar_icon, logo],
icons_one: [
+2 -8
View File
@@ -771,11 +771,6 @@ fn ribbon_text(ui: &egui::Ui, at: egui::Pos2, text: &str, size: f32, color: Colo
ui.painter().galley(origin, galley, color);
}
/// The ribbon and S shortcut share one popup anchor, including after resizing.
fn search_anchor(ctx: &egui::Context) -> Option<egui::Pos2> {
ctx.data(|d| d.get_temp::<Rect>(egui::Id::new("sc_ribbon_search"))).map(|r| r.left_bottom() + vec2(0.0, 3.0))
}
fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) {
let t = Tokens::get();
let tabs = crate::workspace::visible_tabs(app);
@@ -820,7 +815,7 @@ fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) {
}
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));
if resp.on_hover_text(label).clicked() {
crate::shortcut_box::open(app, search_anchor(ui.ctx()));
app.start("ui.palette");
}
let changed = ui.ctx().data_mut(|d| {
let id = egui::Id::new("sc_ribbon_visible_tab");
@@ -1870,8 +1865,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
// is what leaves it, so a second Escape after putting a tool down is harmless.
}
Key::S if !mods.shift && !mods.alt => {
let at = search_anchor(ctx).or_else(|| ctx.input(|i| i.pointer.latest_pos()));
crate::shortcut_box::open(app, at);
app.start("ui.palette");
}
Key::V => crate::context_menu::toggle_visibility(app),
Key::F2 => {
+82 -1
View File
@@ -28,6 +28,20 @@ macro_rules! element {
// One entry per element/variant: names, rendering and geometry expectations stay together.
const ELEMENTS: &[Element] = &[
element!("command_search", |ui, _| {
let mut query = "fillet".to_owned();
CommandSearch::field(ui, &mut query, false, true, 4096);
Menu::show(ui, ui.available_width(), |ui| {
CommandSearch::heading(ui, "search.commands", 1);
let c = solidcraft_engine::find_command("solid.fillet").unwrap();
let mut row = MenuItem::new(c.id, c.label, c.icon);
row.highlighted = true;
row.shortcut = "F";
row.search_row(ui, &query, "MODEL › MODIFY", None);
CommandSearch::detail(ui, "radius 6 mm");
CommandSearch::footer(ui, false);
});
}),
element!("menu", |ui, _| {
Menu::show(ui, 268.0, |ui| {
Menu::heading(ui, "Body");
@@ -682,7 +696,7 @@ const ELEMENTS: &[Element] = &[
fn example(ui: &mut Ui, element: &Element) -> (&'static str, Option<&'static str>) {
let mut sample = Sample { value: "12 mm".into(), second: "25 mm".into(), selected: 0, checked: true };
let rect = ui.scope(|ui| (element.draw)(ui, &mut sample)).response.rect;
if matches!(element.name, "menu" | "menu_submenu" | "rename_menu" | "workspace_menu") {
if matches!(element.name, "menu" | "menu_submenu" | "rename_menu" | "workspace_menu" | "command_search") {
// A popup's elevation is painted outside its layout rectangle. Reserve those
// actual shadow bounds as part of the gallery sample, keeping the paint guard strict.
ui.expand_to_include_rect(rect + Menu::frame().shadow.margin());
@@ -1081,3 +1095,70 @@ fn menu_board_in_both_themes() {
}
crate::theme::set_dark(previous);
}
/// CPU raster of the actual popup in all five board states. No display or GPU required.
#[test]
fn command_search_board_in_both_themes() {
use super::checks::tests::{raster, textures_update};
use std::collections::HashMap;
let previous = crate::theme::is_dark();
for dark in [false, true] {
crate::theme::set_dark(dark);
let t = Tokens::get();
assert!(crate::theme::contrast_ratio(t.form_success, t.form_success_fill) >= 4.5);
assert!(crate::theme::contrast_ratio(t.selected_ink, t.accent_soft) >= 4.5);
for (state, query) in [
("empty", ""),
("matches", "fillet"),
("command", r#"solid.extrude {"distance":20}"#),
("invalid", r#"solid.extrude {"distance":}"#),
("no-match", "filletttt"),
] {
let ctx = crate::fonts::test_context();
ctx.set_visuals(if dark { egui::Visuals::dark() } else { egui::Visuals::light() });
let mut app = crate::test_support::sample_app();
app.run("parameters.add", serde_json::json!({"name":"fillet_radius","expression":"6 mm"})).unwrap();
app.sbox.used("solid.extrude");
app.sbox.used("solid.fillet");
app.sbox.used("sketch.create");
crate::shortcut_box::open(&mut app, Some(egui::pos2(20.0, 20.0)));
app.sbox.text = query.to_owned();
let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(570.0, 650.0));
let mut textures = HashMap::new();
let mut image = None;
for _ in 0..3 {
scenario::clear_handles();
let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(bounds), focused: true, ..Default::default() }, |ui| {
ui.painter().rect_filled(bounds, 0.0, Tokens::get().panel);
crate::shortcut_box::show(&mut app, ui.ctx());
});
textures_update(&mut textures, &output.textures_delta);
output.textures_delta.clear();
image = Some(raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures));
}
let popup = scenario::rect_of("ribbon:search_popup").unwrap();
let field = scenario::rect_of("shortcut:search").unwrap();
assert_eq!(field.height(), 40.0);
assert_eq!(popup.width(), 520.0);
assert!(bounds.contains_rect(popup), "{state}: {popup:?}");
match state {
"matches" => {
assert!(scenario::handle_at("menu:solid.fillet").is_some());
assert_eq!(scenario::rect_of("menu:solid.fillet").unwrap().height(), 38.0);
assert!(scenario::handle_at("menu:search:design:0").is_some());
}
"command" => assert!(scenario::rect_of("dialog:note:command_parameters").is_some()),
"invalid" => assert!(scenario::rect_of("dialog:report:command_parameters").is_some()),
"no-match" => assert!(scenario::rect_of("dialog:report:search_no_match").is_some()),
_ => {}
}
let image = image.unwrap();
assert!(image.pixels().any(|p| p.0[3] != 0));
if let Ok(dir) = std::env::var("SOLIDCRAFT_SEARCH_EVIDENCE") {
std::fs::create_dir_all(&dir).unwrap();
image.save(std::path::Path::new(&dir).join(format!("search-{state}-{}.png", if dark { "dark" } else { "light" }))).unwrap();
}
}
}
crate::theme::set_dark(previous);
}
+2
View File
@@ -14,6 +14,7 @@ mod metrics;
pub(crate) mod panel;
mod radial;
mod reports;
mod search;
mod status;
mod table;
mod text;
@@ -33,6 +34,7 @@ pub(crate) use panel::{ComputeStatus, FeatureOptions, Panel, Part, Window, Windo
pub(crate) use panel::{collapsible_header, header};
pub(crate) use radial::{RADIAL_RADIUS, radial_menu};
pub(crate) use reports::*;
pub(crate) use search::{CommandSearch, SearchBadge};
pub(crate) use status::*;
pub(crate) use table::*;
+203
View File
@@ -0,0 +1,203 @@
//! Command-search composition: a taller editor and two-line MenuItem variant.
//! Domain ranking and command dispatch stay with the caller.
use crate::{icons, theme::Tokens};
use egui::{FontId, Rect, Response, Sense, Stroke, Ui, pos2, vec2};
#[derive(Clone, Copy)]
pub(crate) enum SearchBadge {
Kind,
Valid,
Invalid,
}
pub(crate) struct CommandSearch;
impl CommandSearch {
pub(crate) fn width() -> f32 {
let t = Tokens::get();
t.form_card_width * 2.0 - t.space_8
}
pub(crate) fn field(ui: &mut Ui, value: &mut String, invalid: bool, focus: bool, limit: usize) -> Response {
let t = Tokens::get();
let height = t.control_height + t.space_12;
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover());
let focused = focus || ui.memory(|m| m.has_focus(egui::Id::new("sc_sbox_text")));
let ink = if invalid {
t.form_error
} else if focused {
t.form_primary
} else {
t.control_border
};
if focused {
ui.painter().rect_filled(r.expand(t.space_3), t.radius_xl, if invalid { t.form_error_fill } else { t.accent_soft });
}
ui.painter().rect(r, t.radius_xl, t.control_fill, Stroke::new(1.0, ink), egui::StrokeKind::Inside);
icons::paint_icon(
ui.painter(),
Rect::from_center_size(r.left_center() + vec2(t.space_12 + t.space_8, 0.0), vec2(t.space_16, t.space_16)),
"zoom",
1.0,
);
let cap = if value.is_empty() { "S" } else { "Esc" };
Self::key(ui, r.right_center() - vec2(t.space_10, 0.0), cap);
let editor = Rect::from_min_max(r.min + vec2(t.space_24 + t.space_16, 0.0), r.max - vec2(t.space_24 * 2.0, 0.0));
let mono = value.contains('{');
let response = ui
.scope_builder(egui::UiBuilder::new().max_rect(editor), |ui| {
ui.add_sized(
editor.size(),
super::fields::text_input(egui::TextEdit::singleline(value))
.id(egui::Id::new("sc_sbox_text"))
.char_limit(limit)
.frame(egui::Frame::NONE)
.hint_text(crate::i18n::tr_label("Search commands"))
.font(if mono { FontId::monospace(t.font_label) } else { FontId::proportional(t.font_button) }),
)
})
.inner;
if focus {
response.request_focus();
}
crate::scenario::publish_target("shortcut:search", r);
crate::scenario::publish_target("palette:search", r);
response
}
fn key(ui: &Ui, right: egui::Pos2, label: &str) -> f32 {
let t = Tokens::get();
let galley = ui.painter().layout_no_wrap(label.to_owned(), FontId::monospace(t.font_small), t.form_dim);
let size = galley.size() + vec2(t.space_10, t.space_4);
let r = Rect::from_min_size(pos2(right.x - size.x, right.y - size.y / 2.0), size);
ui.painter().rect(r, t.radius_sm, t.dialog_footer, Stroke::new(1.0, t.dialog_rule), egui::StrokeKind::Inside);
ui.painter().galley(r.min + vec2(t.space_10 / 2.0, t.space_2), galley, t.form_dim);
size.x
}
pub(crate) fn heading(ui: &mut Ui, label: &str, count: usize) {
super::Menu::heading(ui, &format!("{} {count}", crate::i18n::tr(label)));
}
pub(crate) fn detail(ui: &mut Ui, text: &str) {
let t = Tokens::get();
egui::Frame::NONE.fill(t.control_fill).stroke(Stroke::new(1.0, t.dialog_rule)).corner_radius(t.control_radius).inner_margin(t.space_8).show(
ui,
|ui| {
super::text(ui, text, super::Text::MonoNote("command_parameters"));
},
);
}
pub(crate) fn footer(ui: &mut Ui, command: bool) {
let t = Tokens::get();
ui.add_space(t.space_6);
ui.painter().hline(ui.available_rect_before_wrap().x_range(), ui.cursor().top(), Stroke::new(1.0, t.dialog_rule));
egui::Frame::NONE.fill(t.dialog_footer).inner_margin(t.space_6).show(ui, |ui| {
ui.set_min_width((ui.available_width() - t.space_12).max(0.0));
super::text(ui, crate::i18n::tr(if command { "search.command_keys" } else { "search.keys" }), super::Text::Note("search_keys"));
});
}
}
impl super::MenuItem<'_> {
/// 38 pt search row: shared menu states, 26 pt tile, highlighted match, path and keycap.
pub(crate) fn search_row(&self, ui: &mut Ui, query: &str, path: &str, badge: Option<SearchBadge>) -> Response {
let t = Tokens::get();
let (r, response) = ui.allocate_exact_size(
vec2(ui.available_width(), t.control_height + t.space_10),
if self.enabled { Sense::click() } else { Sense::hover() },
);
let hot = self.enabled && (self.highlighted || response.hovered());
let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(r));
if hot {
painter.rect_filled(r, t.control_radius, t.accent_soft);
}
let tile = Rect::from_center_size(
pos2(r.left() + t.space_8 + (t.space_24 + t.space_2) / 2.0, r.center().y),
vec2(t.space_24 + t.space_2, t.space_24 + t.space_2),
);
painter.rect_filled(tile, t.control_radius, if hot { t.accent_soft } else { t.dialog_footer });
icons::paint_icon(&painter, tile.shrink(t.space_6), self.icon, if self.enabled { 1.0 } else { 0.4 });
let right = r.right() - t.space_8;
let key_width = if self.shortcut.is_empty() {
0.0
} else if let Some(badge) = badge {
let ink = match badge {
SearchBadge::Kind => t.form_dim,
SearchBadge::Valid => t.form_success,
SearchBadge::Invalid => t.form_error,
};
let galley = painter.layout_no_wrap(self.shortcut.to_owned(), crate::fonts::semibold(t.font_small), ink);
let size = galley.size() + vec2(t.space_16, t.space_4);
let rect = Rect::from_min_size(pos2(right - size.x, r.center().y - size.y / 2.0), size);
painter.rect_filled(
rect,
t.radius_xl,
match badge {
SearchBadge::Invalid => t.form_error_fill,
SearchBadge::Valid => t.form_success_fill,
SearchBadge::Kind => t.dialog_footer,
},
);
painter.galley(rect.min + vec2(t.space_8, t.space_2), galley, ink);
size.x + t.space_10
} else {
CommandSearch::key(ui, pos2(right, r.center().y), self.shortcut) + t.space_10
};
let left = tile.right() + t.space_10;
let label = self.label;
let normal = egui::TextFormat::simple(FontId::proportional(t.font_label), if self.enabled { t.form_ink } else { t.form_dim });
let mut job = egui::text::LayoutJob::default();
// Match by character boundaries, including case mappings that change UTF-8 byte lengths.
let q = query.trim().to_lowercase();
let hit = (!q.is_empty())
.then(|| {
label.char_indices().find_map(|(start, _)| {
let mut lowered = String::new();
for (offset, c) in label.get(start..)?.char_indices() {
lowered.extend(c.to_lowercase());
if lowered == q {
return Some((start, start + offset + c.len_utf8()));
}
if !q.starts_with(&lowered) {
break;
}
}
None
})
})
.flatten();
if let Some((start, end)) = hit {
job.append(label.get(..start).unwrap_or_default(), 0.0, normal.clone());
job.append(label.get(start..end).unwrap_or_default(), 0.0, egui::TextFormat::simple(crate::fonts::bold(t.font_label), t.selected_ink));
job.append(label.get(end..).unwrap_or_default(), 0.0, normal);
} else {
job.append(label, 0.0, normal);
}
job.wrap.max_width = (right - key_width - left).max(0.0);
job.wrap.max_rows = 1;
let galley = painter.layout_job(job);
painter.galley(pos2(left, r.top() + t.space_3), galley, t.form_ink);
let path_rect = Rect::from_min_max(pos2(left, r.center().y), pos2((right - key_width).max(left), r.bottom() - t.space_2));
if let Some((tab, group)) = path.split_once('›') {
let tab = painter.layout_no_wrap(tab.trim().to_owned(), FontId::proportional(t.font_small), t.form_dim);
let x = (left + tab.size().x + t.space_6).min(path_rect.right());
painter.with_clip_rect(path_rect).galley(pos2(left, path_rect.center().y - tab.size().y / 2.0), tab, t.form_dim);
icons::glyphs::breadcrumb(&painter.with_clip_rect(path_rect), pos2(x, path_rect.center().y), t.form_dim);
super::text::paint_text(
ui,
Rect::from_min_max(pos2((x + t.space_6).min(path_rect.right()), path_rect.top()), path_rect.max),
group.trim(),
FontId::proportional(t.font_small),
t.form_dim,
false,
);
} else {
super::text::paint_text(ui, path_rect, path, FontId::proportional(t.font_small), t.form_dim, false);
}
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, self.enabled, label));
crate::scenario::publish_target(&format!("menu:{}", self.id), r);
response
}
}
+1 -1
View File
@@ -218,7 +218,7 @@ fn floating_window_helper_has_only_its_live_consumers() {
}
}
callers.sort();
assert_eq!(callers, ["bom_panel.rs", "messages.rs", "palette.rs", "space_mouse_calibration.rs"]);
assert_eq!(callers, ["bom_panel.rs", "messages.rs", "space_mouse_calibration.rs"]);
}
#[test]
+1 -1
View File
@@ -20,7 +20,7 @@ Keys handled by the window itself:
| Key | Action |
|---|---|
| S | the S box: search every command at the cursor |
| S | command search under the ribbon search field |
| V | show or hide the selected bodies, sketches and planes |
| F2 | rename the selected browser or timeline item |
| F6 | fit the view to the model |
+9 -2
View File
@@ -67,8 +67,15 @@
value box in the viewport.
- **Timeline** (bottom). Every feature in order. Double-click to edit, drag the marker to roll
back, and drag features to reorder them.
- **S box.** Press S anywhere for a command search at the cursor. Pin the commands you use most
to its top.
- **Command search (S).** Click the ribbon search field or press S to open the search popup
below it. Results group commands by their ribbon path and show matching features and user
parameters from this design. With an empty query, recent commands appear first, followed by
pinned commands in the Commands group. Up/Down
choose, Enter runs, Tab fills the selected name, and Esc closes. A feature opens its existing
editor; a parameter opens Change Parameters filtered to its name. To run with explicit values,
enter an id and JSON object, for example `solid.extrude {"distance": 20}`. The popup validates
JSON as you type and shows parser errors. Shift+Enter runs it and keeps the popup open.
Right-click a command for its existing pin and toolbar actions.
Preferences (File › Preferences) hold the theme, the units of new designs, the mouse preset, the
visual style and autosave. Graphics › Colour vision gives the colours that carry a meaning (sketch
+15
View File
@@ -227,3 +227,18 @@ UI callers apply the camera with their animation preference, without editing the
Shift-orbit snapping includes 45-degree edge views and isometric corner views, with a
lightly damped spring transition and a small boundary margin to prevent flicker.
### Command search
`ui.palette {text?, open?}` opens command search under the ribbon search field; `open: false`
closes it. `ui.start {command: "ui.palette"}`, clicking `ribbon:search`, and S open the same
popup. This is UI routing: `engine.execute` continues to run commands without opening dialogs.
The query is limited to 4096 Unicode characters, with at most 80 visible results.
`shortcut:search` and `palette:search` identify the editor; `ribbon:search_popup` and
`palette:outer` identify the popup. Command rows retain `menu:<command id>`; design rows use
`menu:search:design:<index>`. Up/Down choose an enabled row, Enter runs it, Tab fills its id or
name, and Esc closes. Typing `command.id {"parameter": value}` validates JSON live and runs
through the same engine entry as `engine.execute`. Shift+Enter runs JSON and keeps the query
open. Invalid JSON stays editable and reports the parser's error. Feature results open their
existing edit tools; parameter results open Change Parameters filtered to that name.
+1
View File
@@ -55,6 +55,7 @@ table. Panel/Window/Confirm compositions also have dedicated geometry and intera
| Module / element | Use and options | Main tokens |
| --- | --- | --- |
| search: `CommandSearch`, `MenuItem::search_row` | Ribbon search composition: 40 pt bounded field, magnifier and S/Esc keycap, 38 pt two-line menu row with 26 pt icon tile, accent bold substring, path, shortcut/kind keycap, counts, JSON detail box and footer. The ordinary 30 pt menu row cannot fit a second line; this variant keeps its enabled/selected states and scenario IDs. Ranking and dispatch stay with the caller. | `form_card_width × 2 − space_8` (520 pt), `control_height`, `space_2/3/4/6/8/10/12/16/24`, `radius_xl/control_radius`, `control_fill`, `dialog_body/footer/rule/border`, `form_ink/dim/primary/error/error_fill/success/success_fill`, `selected_ink`, `accent_soft`, typography |
| menu: `Menu`, `MenuItem` | Shared popup, 30 pt rows, 28 pt icon column, clipped labels, right-aligned mono shortcuts, submenu chevrons, checked/unchecked and document swatches, inert 40% disabled rows and danger ink; headings and separators; ribbon drag/pin targets retained | `dialog_body/border/rule`, `radius_xl`, `control_height/radius`, `form_ink/dim/primary/error`, `accent_soft`, typography and spacing |
| radial: `radial_menu` | Eight rounded annular sectors, parallel 4 pt gaps, 9 pt circular corner joins, accent hover, centre label/key; existing hold/flick/release dispatch | `dialog_body/border`, `form_ink/dim/primary`, `accent_soft`, font/spacing tokens |
| panel: `Window`, `WindowPage` | Shared card frame, header, optional page list, bounded content and footer with a left action | `form_header/footer_height`, `form_card_width`, `form_label_width`, `control_height`, `dialog_footer/rule`, `selected_bg/ink`, spacing |