diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ecbdf780fb..25158eacca 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -182,7 +182,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?} save the current set's tools and menu commands with their shortcuts as a UTF-8 text file (Keyboard Shortcuts › Export Text…): the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none; without `path`, pick a file", + "{path?, format?: \"text\"|\"sheet\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. A `path` is written as given. Without it, pick a file: the desktop save dialog offers both formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3f89789d5d..5ed91270ad 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -71,6 +71,7 @@ pub mod script_runs; pub mod scripts_menu; mod scrub; pub mod shortcut_editor; +pub mod shortcut_sheet; pub mod shortcuts; pub mod state; pub mod stylus; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c099422957..31abcabb3d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -183,7 +183,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?} save the current set's tools and menu commands with their shortcuts as a UTF-8 text file (Keyboard Shortcuts › Export Text…): the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none; without `path`, pick a file", + "{path?, format?: \"text\"|\"sheet\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. A `path` is written as given. Without it, pick a file: the desktop save dialog offers both formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 88a97206c7..5a50525657 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1184,7 +1184,7 @@ pub fn export_text(set: &str, overrides: &Overrides) -> String { let snapshot = snapshot(); let km = crate::keymap::keymap_in(&snapshot, overrides); let backtick = backtick_text(); - let shown_set = if PRESETS.contains(&set) || set == CUSTOM { tl!(set) } else { set }; + let shown_set = shown_set_name(set); let mut out = format!("{}\n{} {shown_set}\n", tl!("Keyboard Shortcuts"), tl!("Set:")); for (tools, heading) in [(true, "Tools"), (false, "Menu Commands")] { out += &format!("\n{}\n", tl!(heading)); @@ -1197,6 +1197,133 @@ pub fn export_text(set: &str, overrides: &Overrides) -> String { out } +/// A set's name as the dialog shows it: the presets and Custom in the UI language. +fn shown_set_name(set: &str) -> &str { + if PRESETS.contains(&set) || set == CUSTOM { tl!(set) } else { set } +} + +/// Export Text's file formats. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextFormat { + /// [`export_text`]'s text file. + Text, + /// The printable shortcut sheet as a PDF ([`crate::shortcut_sheet::sheet_pdf`]). + Sheet, +} + +impl TextFormat { + pub const ALL: [Self; 2] = [Self::Text, Self::Sheet]; + + /// The `format` param's value. + pub fn name(self) -> &'static str { + match self { + Self::Text => "text", + Self::Sheet => "sheet", + } + } + + fn extension(self) -> &'static str { + match self { + Self::Text => "txt", + Self::Sheet => "pdf", + } + } + + /// The save dialog's file type. + fn filter(self) -> crate::FileFilter { + let label = match self { + Self::Text => "Text", + Self::Sheet => "Shortcut sheet", + }; + crate::FilePick::filter(label, &[self.extension()]) + } + + fn file_name(self) -> String { + format!("VectorCraft Shortcuts.{}", self.extension()) + } + + /// `path` with `format`'s extension: kept when it has it in any letter case, the extension of + /// another of these formats replaced, and the extension added to any other path. + fn with_extension(path: &str, format: Self) -> String { + let ext = vectorcraft_engine::cmd::fileio::extension(path); + if ext.eq_ignore_ascii_case(format.extension()) { + path.to_string() + } else if Self::ALL.iter().any(|f| f.extension().eq_ignore_ascii_case(&ext)) { + std::path::Path::new(path).with_extension(format.extension()).to_string_lossy().into_owned() + } else { + format!("{path}.{}", format.extension()) + } + } + + /// The format a save dialog's answer picked: the file type it reports, else the extension of + /// `path`; text for any other. + fn picked(path: &str, file_type: Option<&str>) -> Self { + let ext = file_type.map_or_else(|| vectorcraft_engine::cmd::fileio::extension(path), str::to_string); + Self::ALL.into_iter().find(|f| f.extension().eq_ignore_ascii_case(ext.trim_start_matches('.'))).unwrap_or(Self::Text) + } +} + +/// The section name for menu commands no menu holds, as Export Text's heading has it. +const MENU_COMMANDS: &str = "Menu Commands"; + +/// Export Text's rows in sections, for the shortcut sheet: Tools, then one section per top-level +/// menu in the order the dialog first lists a command of it, with the names and shortcuts as the +/// dialog shows them, each name without its top-level menu. Every row the dialog lists is there, +/// with an empty shortcut when it has none. +pub fn export_sections(overrides: &Overrides) -> Vec { + use crate::shortcut_sheet::{Row, Section}; + let snapshot = snapshot(); + let km = crate::keymap::keymap_in(&snapshot, overrides); + let backtick = backtick_text(); + let mut tools = Section { title: tl!("Tools").to_string(), rows: vec![] }; + let mut menus: Vec
= vec![]; + for e in snapshot.entries.iter().filter(|e| listed(km.overrides(), e)) { + let shortcut = dialog_shortcuts_with(&km, &e.key, backtick.as_deref()).unwrap_or_default(); + if e.is_tool { + tools.rows.push(Row { name: shown_name(e), shortcut }); + continue; + } + let group = shown_group(&e.group); + let (top, rest) = group.split_once(" › ").unwrap_or((group.as_str(), "")); + let top = if top.is_empty() { tl!(MENU_COMMANDS) } else { top }; + let label = shown_label(e); + let inner = if rest.is_empty() { label.to_string() } else { format!("{rest} › {label}") }; + let name = if e.shows_key { format!("{inner} ({})", e.key) } else { inner }; + match menus.iter_mut().find(|s| s.title == top) { + Some(s) => s.rows.push(Row { name, shortcut }), + None => menus.push(Section { title: top.to_string(), rows: vec![Row { name, shortcut }] }), + } + } + std::iter::once(tools).chain(menus).collect() +} + +/// The file `format` writes for `set` with `overrides`: the sheet on `page`. +fn export_text_file(format: TextFormat, set: &str, overrides: &Overrides, page: crate::shortcut_sheet::PageSize) -> Result, String> { + match format { + TextFormat::Text => Ok(export_text(set, overrides).into_bytes()), + TextFormat::Sheet => { + let title = format!("{} · {}", tl!("Keyboard Shortcuts"), shown_set_name(set)); + crate::shortcut_sheet::sheet_pdf(&title, &export_sections(overrides), page) + } + } +} + +/// The sheet's paper when `pageSize` is left out: A4 when the current document prints on A4 (its +/// print settings, or, with none saved, a first artboard of A4 size either way up), else Letter. +fn default_sheet_page(app: &VectorcraftApp) -> crate::shortcut_sheet::PageSize { + use crate::shortcut_sheet::PageSize; + let Some(st) = app.session.active() else { return PageSize::Letter }; + let a4 = match st.doc.print_setup.clone().and_then(|v| serde_json::from_value::(v).ok()) { + Some(settings) => settings.media == vectorcraft_pdf::Media::A4, + None => st.doc.artboards.first().is_some_and(|a| { + let (w, h) = PageSize::A4.landscape(); + let (long, short) = (a.rect.width().max(a.rect.height()), a.rect.width().min(a.rect.height())); + (long - w).abs() < 1.0 && (short - h).abs() < 1.0 + }), + }; + if a4 { PageSize::A4 } else { PageSize::Letter } +} + // ---------- UI commands ---------- pub fn open(app: &mut VectorcraftApp) { @@ -1329,19 +1456,75 @@ pub fn run_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option None, + Ok(Some(f)) => match TextFormat::ALL.into_iter().find(|t| t.name() == f) { + Some(t) => Some(t), + None => { + let key = "format"; + return Some(Err(format!("`{key}` must be one of {}", TextFormat::ALL.map(TextFormat::name).join(", ")))); + } + }, + Err(e) => return Some(Err(e)), + }; + let page = match s("pageSize") { + Ok(None) => default_sheet_page(app), + Ok(Some(n)) => match crate::shortcut_sheet::PageSize::parse(&n) { + Some(page) => page, + None => { + let key = "pageSize"; + return Some(Err(format!( + "`{key}` must be one of {}", + crate::shortcut_sheet::PageSize::ALL.map(crate::shortcut_sheet::PageSize::name).join(", ") + ))); + } + }, + Err(e) => return Some(Err(e)), + }; + // A given path is written as text unless `format` says otherwise; a save dialog offers + // every format (text first) unless `format` names one, and its answer picks the format. + let (path, format) = match path { + Some(path) => (Some(path), format.unwrap_or(TextFormat::Text)), + None => { + let shown = format.unwrap_or(TextFormat::Text); + let filters = format.map_or_else(|| TextFormat::ALL.map(TextFormat::filter).to_vec(), |f| vec![f.filter()]); + let pick = crate::FilePick { filters, ..crate::FilePick::named(&shown.file_name()) }; + match crate::picks::save_with_type(app, &pick) { + Some((answer, file_type)) => { + let picked = format.unwrap_or_else(|| TextFormat::picked(&answer, file_type.as_deref())); + // The format that `format` names, or that a dialog reports as the type + // picked, gives the name its extension. A file already at a path + // changed that way, which the dialog did not check, is replaced only + // after asking. + let typed = format.is_some() || file_type.is_some(); + let path = if typed { TextFormat::with_extension(&answer, picked) } else { answer.clone() }; + let request = crate::picks::PickRequest::Save(pick.clone()); + if path != answer && crate::picks::ask_to_replace(app, request, &answer, file_type.as_deref(), &path) { + return Some(Err("cancelled".into())); + } + (Some(path), picked) + } + None => (None, shown), + } + } + }; + // Its save dialog is open: the file is made and written when it answers. + if path.is_none() && app.file_dialog_open() { + return Some(Err("cancelled".into())); + } + let bytes = match export_text_file(format, &app.ui.shortcut_set, &app.ui.shortcut_overrides, page) { + Ok(bytes) => bytes, + Err(e) => return Some(Err(e)), + }; + match path { Some(path) => match app.services.write.as_mut() { - Some(w) => w(&path, text.as_bytes()).map(|_| json!({"path": path})), + Some(w) => w(&path, &bytes).map(|_| json!({"path": path})), None => Err("no file writer".into()), }, - // Its save dialog is open: the file is written when it answers. - None if app.file_dialog_open() => Err("cancelled".into()), None => match app.services.download.as_mut() { - Some(dl) => dl("VectorCraft Shortcuts.txt", text.as_bytes()).map(|()| Value::Null), - None => Ok(json!({"text": text})), + Some(dl) => dl(&format.file_name(), &bytes).map(|()| Value::Null), + None if format == TextFormat::Sheet => Ok(json!({"pdf": vectorcraft_svg::base64_encode(&bytes)})), + None => Ok(json!({"text": String::from_utf8_lossy(&bytes)})), }, } } @@ -2171,6 +2354,133 @@ mod tests { assert_eq!(*text, expected); } + /// The sheet's sections: Tools first, then each top-level menu once, in the + /// order the dialog first lists a command of it, holding every row the dialog lists with its + /// shortcut, the command named without its top-level menu. + #[test] + fn export_sections_hold_every_listed_row_once_by_top_level_menu() { + let mut ov = Overrides::new(); + crate::keymap::set_override(&mut ov, "edit.preferences", "Ctrl+Alt+Shift+9"); + let (sections, listed_rows, tops) = with_steady_plugins(|| { + let km = keymap_with(&ov); + let listed: Vec = entries().iter().filter(|e| listed(km.overrides(), e)).cloned().collect(); + let mut tops: Vec = vec![]; + for e in listed.iter().filter(|e| !e.is_tool) { + let top = e.group.split(" › ").next().filter(|t| !t.is_empty()).unwrap_or(MENU_COMMANDS).to_string(); + if !tops.contains(&top) { + tops.push(top); + } + } + (export_sections(&ov), listed.len(), tops) + }); + let titles: Vec<&str> = sections.iter().map(|s| s.title.as_str()).collect(); + assert_eq!(titles[0], "Tools"); + assert_eq!(titles[1..], tops.iter().map(String::as_str).collect::>()[..], "one section per top-level menu"); + for menu in ["File", "Edit", "Object", "Type", "Select", "Effect", "View", "Window", "Help"] { + assert!(titles.contains(&menu), "no {menu} section: {titles:?}"); + } + assert_eq!(sections.iter().map(|s| s.rows.len()).sum::(), listed_rows, "every listed row once"); + let prefs = entry("edit.preferences").expect("the Preferences row"); + let top = prefs.group.split(" › ").next().unwrap_or_default().to_string(); + let name = shown_name(&prefs).strip_prefix(&format!("{top} › ")).map(str::to_string).expect("Preferences is in a menu"); + let section = sections.iter().find(|s| s.title == top).expect("its menu's section"); + assert!(section.rows.iter().any(|r| r.name == name && r.shortcut.ends_with('9')), "{name} in {:?}", section.rows); + let pen = sections[0].rows.iter().find(|r| r.shortcut == menus::pretty_shortcut(default_of("tool:pen").unwrap_or_default())); + assert!(pen.is_some(), "the Pen tool's row"); + } + + /// `format` picks the file: text (the default, the same bytes as before) or the PDF sheet. A + /// given path is written as text whatever its extension, and a bad `format` or `pageSize` is an + /// error that writes nothing. + #[test] + fn export_text_command_writes_text_or_a_sheet() { + type Files = std::rc::Rc)>>>; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let written: Files = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, b: &[u8]| { + w.borrow_mut().push((path.to_string(), b.to_vec())); + Ok(()) + })); + let (files, text) = with_steady_plugins(|| { + written.borrow_mut().clear(); + app.run("shortcuts.exportText", json!({"path": "/a/plain.txt"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/named.txt", "format": "text"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/as-text.pdf"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/sheet.pdf", "format": "sheet", "pageSize": "a4"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/sheet.txt", "format": "sheet"})).unwrap(); + (written.borrow().clone(), export_text(&app.ui.shortcut_set, &app.ui.shortcut_overrides)) + }); + let [plain, named, as_text, sheet, sheet_as_named] = files.as_slice() else { panic!("{} files", files.len()) }; + for f in [plain, named, as_text] { + assert_eq!(f.1, text.as_bytes(), "{}", f.0); + } + assert!(sheet.1.starts_with(b"%PDF-"), "{}", sheet.0); + assert_eq!(sheet_as_named.0, "/a/sheet.txt", "a path is written as given"); + assert!(sheet_as_named.1.starts_with(b"%PDF-")); + written.borrow_mut().clear(); + let mut err = |p: Value| app.run("shortcuts.exportText", p); + assert_eq!(err(json!({"path": "/a/x", "format": "xlsx"})), Err("`format` must be one of text, sheet".to_string())); + assert_eq!(err(json!({"path": "/a/x", "format": "Sheet"})), Err("`format` must be one of text, sheet".to_string())); + assert_eq!(err(json!({"path": "/a/x", "format": 3})), Err("`format` must be a string".to_string())); + assert_eq!(err(json!({"path": "/a/x", "pageSize": "legal"})), Err("`pageSize` must be one of letter, a4".to_string())); + assert_eq!(err(json!({"path": "/a/x", "pageSize": "A4"})), Err("`pageSize` must be one of letter, a4".to_string())); + assert!(written.borrow().is_empty()); + } + + /// With no `pageSize` the sheet is on A4 when the current document prints on A4: its print + /// settings say so, or, with none saved, its first artboard is A4 either way up; else Letter. + #[test] + fn the_sheet_is_on_a4_when_the_document_prints_on_a4() { + use crate::shortcut_sheet::PageSize; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert_eq!(default_sheet_page(&app), PageSize::Letter, "no document"); + app.session.add_document(vectorcraft_doc::Document::new(612.0, 792.0), None); + assert_eq!(default_sheet_page(&app), PageSize::Letter, "a Letter artboard"); + app.session.add_document(vectorcraft_doc::Document::new(595.28, 841.89), None); + assert_eq!(default_sheet_page(&app), PageSize::A4, "an A4 artboard"); + let printing = |w, h, media| { + let mut doc = vectorcraft_doc::Document::new(w, h); + doc.print_setup = serde_json::to_value(vectorcraft_pdf::PrintSettings { media, ..Default::default() }).ok(); + doc + }; + app.session.add_document(printing(595.28, 841.89, vectorcraft_pdf::Media::Letter), None); + assert_eq!(default_sheet_page(&app), PageSize::Letter, "an A4 artboard printing on Letter"); + app.session.add_document(printing(612.0, 792.0, vectorcraft_pdf::Media::A4), None); + assert_eq!(default_sheet_page(&app), PageSize::A4, "printing on A4"); + } + + /// Without a path, a file writer or a download, `shortcuts.exportText` returns the file: the + /// text file under `text` and the sheet as base64 under `pdf`. + #[test] + fn export_text_without_a_file_returns_it() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let (text, sheet) = + with_steady_plugins(|| (app.run("shortcuts.exportText", json!({})), app.run("shortcuts.exportText", json!({"format": "sheet"})))); + let text = text.unwrap(); + assert!(text["text"].as_str().unwrap_or_default().starts_with("Keyboard Shortcuts\n"), "{text}"); + let sheet = sheet.unwrap(); + // "%PDF-" in base64. + assert!(sheet["pdf"].as_str().unwrap_or_default().starts_with("JVBERi0"), "{}", sheet.to_string().len()); + } + + /// The save dialog's answer picks the format: the file type it reports, else the extension + /// typed; text for any other. + #[test] + fn the_save_dialogs_answer_picks_the_export_text_format() { + assert_eq!(TextFormat::picked("/a/sheet.PDF", None), TextFormat::Sheet); + assert_eq!(TextFormat::picked("/a/list", Some("pdf")), TextFormat::Sheet); + assert_eq!(TextFormat::picked("/a/list.pdf", Some("txt")), TextFormat::Text); + assert_eq!(TextFormat::picked("/a/list.txt", None), TextFormat::Text); + assert_eq!(TextFormat::picked("/a/list", None), TextFormat::Text); + assert_eq!(TextFormat::picked("/a/list.json", None), TextFormat::Text); + assert_eq!(TextFormat::with_extension("/a/list", TextFormat::Sheet), "/a/list.pdf"); + assert_eq!(TextFormat::with_extension("/a/list.txt", TextFormat::Sheet), "/a/list.pdf"); + assert_eq!(TextFormat::with_extension("/a/list", TextFormat::Text), "/a/list.txt"); + assert_eq!(TextFormat::with_extension("/a/list.PDF", TextFormat::Sheet), "/a/list.PDF"); + assert_eq!(TextFormat::with_extension("/a/v1.2", TextFormat::Sheet), "/a/v1.2.pdf"); + } + /// The dialog's Import… leaves an action its function key when the imported set gives the key /// to a command, through both Cancel and OK. #[test] diff --git a/crates/ui-egui/src/shortcut_sheet.rs b/crates/ui-egui/src/shortcut_sheet.rs new file mode 100644 index 0000000000..6f99802830 --- /dev/null +++ b/crates/ui-egui/src/shortcut_sheet.rs @@ -0,0 +1,462 @@ +//! Keyboard Shortcuts › Export Text…'s printable shortcut sheet. +//! +//! The rows come from [`crate::shortcut_editor::export_sections`]: a Tools section and one section +//! per top-level menu. The sheet lists the rows that have a shortcut, each section under a colored +//! band with the shortcut on the left and the name on the right, flowed down columns of landscape +//! pages, and is written as a PDF by laying it out as a document. + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; + +/// One section of the list: Tools or a top-level menu, with its rows in the dialog's order. +#[derive(Clone, Debug, PartialEq)] +pub struct Section { + pub title: String, + pub rows: Vec, +} + +/// A row: the command's name within its section and its shortcuts as the dialog shows them (empty +/// when it has none). +#[derive(Clone, Debug, PartialEq)] +pub struct Row { + pub name: String, + pub shortcut: String, +} + +/// The sheet's paper, used in landscape. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PageSize { + Letter, + A4, +} + +impl PageSize { + pub const ALL: [Self; 2] = [Self::Letter, Self::A4]; + + /// The `pageSize` param's value. + pub fn name(self) -> &'static str { + match self { + Self::Letter => "letter", + Self::A4 => "a4", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|p| p.name() == s) + } + + /// Width and height of a landscape page in points. + pub fn landscape(self) -> (f64, f64) { + match self { + Self::Letter => (792.0, 612.0), + Self::A4 => (841.89, 595.28), + } + } +} + +/// Section band colors, in turn. +const BANDS: [(u8, u8, u8); 9] = [ + (0x2f, 0x6d, 0xb5), + (0xc0, 0x39, 0x2b), + (0x27, 0x86, 0x5f), + (0x8e, 0x44, 0xad), + (0xd3, 0x54, 0x00), + (0x16, 0x87, 0x9a), + (0x9a, 0x7d, 0x0a), + (0x5d, 0x6d, 0x7e), + (0xc2, 0x18, 0x5b), +]; + +const MARGIN: f64 = 30.0; +const TITLE_SIZE: f64 = 15.0; +/// From the top margin to the top of the first column. +const TITLE_SPACE: f64 = 28.0; +const COLUMNS: usize = 4; +const GUTTER: f64 = 12.0; +const BAND_HEIGHT: f64 = 13.0; +const BAND_SIZE: f64 = 8.0; +const ROW_HEIGHT: f64 = 9.5; +const ROW_SIZE: f64 = 7.0; +/// Space above a section that does not start a column. +const SECTION_SPACE: f64 = 6.0; +/// The least and the most of a column's width the shortcuts take. +const SHORTCUT_SHARE: f64 = 0.3; +const MAX_SHORTCUT_SHARE: f64 = 0.5; +/// Space between pages in the document. +const PAGE_GAP: f64 = 36.0; +const FONT: &str = "Source Sans 3"; + +/// The sheet's text style. +fn style(size: f64, bold: bool, fill: Color) -> CharStyle { + CharStyle { + font_family: FONT.into(), + font_style: if bold { "Bold" } else { "Regular" }.into(), + size, + fill: Paint::solid(fill), + ..CharStyle::default() + } +} + +/// The width `text` takes in `style`. +fn width(text: &str, style: &CharStyle) -> f64 { + let t = TextObject::point(Point::ZERO, text, style.clone()); + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds.width() +} + +/// The most characters of a name or title the sheet measures; no line on a page holds more. +const MAX_FIT_CHARS: usize = 400; + +/// `text`, shortened with an ellipsis to fit in `room`: the longest start of it that fits with the +/// ellipsis, found with a binary search, so a long imported name takes a few layouts. +fn fitted(text: &str, style: &CharStyle, room: f64) -> String { + let chars: Vec = text.chars().take(MAX_FIT_CHARS + 1).collect(); + if chars.len() <= MAX_FIT_CHARS && width(text, style) <= room { + return text.to_string(); + } + let cut = |n: usize| chars.iter().take(n).collect::().trim_end().to_string() + "…"; + let (mut lo, mut hi) = (0, chars.len().min(MAX_FIT_CHARS)); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + if width(&cut(mid), style) <= room { lo = mid } else { hi = mid - 1 } + } + if lo == 0 && width("…", style) > room { String::new() } else { cut(lo) } +} + +/// Builds the sheet's document: one artboard per page. +struct Sheet { + doc: Document, + page: (f64, f64), + /// Pages so far. + pages: usize, + /// The column being filled, 0-based, and the top of its free space. + column: usize, + y: f64, + /// The shortcut column's width; the names start there. + split: f64, +} + +impl Sheet { + fn origin(&self) -> f64 { + (self.pages - 1) as f64 * (self.page.0 + PAGE_GAP) + } + + fn column_width(&self) -> f64 { + (self.page.0 - 2.0 * MARGIN - GUTTER * (COLUMNS - 1) as f64) / COLUMNS as f64 + } + + fn column_left(&self) -> f64 { + self.origin() + MARGIN + self.column as f64 * (self.column_width() + GUTTER) + } + + fn top(&self) -> f64 { + MARGIN + TITLE_SPACE + } + + fn bottom(&self) -> f64 { + self.page.1 - MARGIN + } + + fn add(&mut self, mut n: Node) { + n.id = self.doc.alloc_id(); + let Some(layer) = self.doc.default_layer() else { return }; + let len = self.doc.children(Some(layer)).map_or(0, |c| c.len()); + // Insertion into the document's own layer only fails for a node id already used, and + // every node gets a new id above. + let _ = self.doc.insert(Some(layer), len, n); + } + + fn rect(&mut self, r: Rect, fill: Color) { + self.add(Node::path(NodeId(0), shapes::rectangle(r), Appearance::basic(Paint::solid(fill), Paint::None, 0.0))); + } + + fn text(&mut self, at: Point, text: &str, style: CharStyle) { + if !text.is_empty() { + self.add(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(at, text, style))))); + } + } + + /// Starts a page with `title` at its top. + fn new_page(&mut self, title: &str) { + self.pages += 1; + let rect = Rect::new(self.origin(), 0.0, self.origin() + self.page.0, self.page.1); + if self.pages == 1 { + if let Some(a) = self.doc.artboards.first_mut() { + a.rect = rect; + } + } else if let Some(mut a) = self.doc.artboards.first().cloned() { + a.id = self.pages as u32; + a.name = format!("Artboard {}", self.pages); + a.rect = rect; + self.doc.artboards.push(a); + } + let style = style(TITLE_SIZE, true, Color::BLACK); + let room = self.page.0 - 2.0 * MARGIN; + let shown = fitted(title, &style, room); + self.text(Point::new(self.origin() + MARGIN, MARGIN + TITLE_SIZE), &shown, style); + self.column = 0; + self.y = self.top(); + } + + /// Room for `height` more in the column, else the next column or page. + fn make_room(&mut self, height: f64, title: &str) -> bool { + if self.y + height <= self.bottom() { + return false; + } + if self.column + 1 < COLUMNS { + self.column += 1; + self.y = self.top(); + } else { + self.new_page(title); + } + true + } + + fn band(&mut self, title: &str, color: Color) { + let (x, w) = (self.column_left(), self.column_width()); + self.rect(Rect::new(x, self.y, x + w, self.y + BAND_HEIGHT), color); + let style = style(BAND_SIZE, true, Color::WHITE); + let shown = fitted(title, &style, w - 8.0); + self.text(Point::new(x + 4.0, self.y + BAND_HEIGHT - 3.6), &shown, style); + self.y += BAND_HEIGHT; + } + + /// Draws one line of a row: `key` on the left and, on the row's first line, `name` on the right. + fn line(&mut self, key: &str, name: Option<&str>, shaded: bool) { + let (x, w) = (self.column_left(), self.column_width()); + if shaded { + self.rect(Rect::new(x, self.y, x + w, self.y + ROW_HEIGHT), Color::rgb8(0xee, 0xf0, 0xf2)); + } + let baseline = self.y + ROW_HEIGHT - 2.6; + self.text(Point::new(x + 3.0, baseline), key, shortcut_style(key, self.split - 6.0)); + if let Some(name) = name { + let plain = style(ROW_SIZE, false, Color::BLACK); + let name = fitted(name, &plain, w - self.split - 3.0); + self.text(Point::new(x + self.split, baseline), &name, plain); + } + self.y += ROW_HEIGHT; + } +} + +/// The style of shortcut `key` in `room`: a shortcut is never cut short, and one too wide for +/// `room` is set smaller. +fn shortcut_style(key: &str, room: f64) -> CharStyle { + let bold = style(ROW_SIZE, true, Color::BLACK); + let wide = width(key, &bold); + if wide > room && wide > 0.0 && room > 0.0 { style(ROW_SIZE * room / wide, true, Color::BLACK) } else { bold } +} + +/// The separate shortcuts of a row's shortcut text, which the dialog joins with ` · `; a row has at +/// least one line. +fn shortcuts(text: &str) -> Vec<&str> { + let keys: Vec<&str> = text.split(" · ").filter(|s| !s.is_empty()).collect(); + if keys.is_empty() { vec![""] } else { keys } +} + +/// The sheet as a document on `page`-sized landscape artboards: `title` at the top of each page, +/// then each section that has a row with a shortcut under a colored band, its rows with a shortcut +/// below it (shortcut on the left, name on the right), flowed down the columns and onto further +/// pages. A section that continues in the next column repeats its band there. A row with several +/// shortcuts has a line for each, kept in one column unless the row is taller than a column, and a +/// shortcut is never shortened; a name too long for its column ends in an ellipsis. +pub fn sheet_document(title: &str, sections: &[Section], page: PageSize) -> Document { + let page = page.landscape(); + let mut s = Sheet { doc: Document::new(page.0, page.1), page, pages: 0, column: 0, y: 0.0, split: 0.0 }; + // The shortcut column is as wide as the widest shortcut, within limits. + let bold = style(ROW_SIZE, true, Color::BLACK); + let widest = sections.iter().flat_map(|sec| &sec.rows).flat_map(|r| shortcuts(&r.shortcut)).map(|k| width(k, &bold)).fold(0.0, f64::max); + let w = s.column_width(); + s.split = (widest + 6.0).clamp(w * SHORTCUT_SHARE, w * MAX_SHORTCUT_SHARE); + s.doc.title = title.to_string(); + s.new_page(title); + // The most a row takes in one piece: a column below its band. + let column = s.bottom() - s.top() - BAND_HEIGHT; + let whole = |row: &Row| shortcuts(&row.shortcut).len() as f64 * ROW_HEIGHT <= column; + let piece = |row: &Row| if whole(row) { shortcuts(&row.shortcut).len() as f64 * ROW_HEIGHT } else { ROW_HEIGHT }; + let listed = sections.iter().filter(|sec| sec.rows.iter().any(|r| !r.shortcut.is_empty())); + for (i, sec) in listed.enumerate() { + let (r, g, b) = BANDS[i % BANDS.len()]; + let color = Color::rgb8(r, g, b); + let space = if s.y > s.top() { SECTION_SPACE } else { 0.0 }; + let mut rows = sec.rows.iter().filter(|r| !r.shortcut.is_empty()).peekable(); + let first = rows.peek().map_or(ROW_HEIGHT, |r| piece(r)); + if !s.make_room(space + BAND_HEIGHT + first, title) { + s.y += space; + } + s.band(&sec.title, color); + for (n, row) in rows.enumerate() { + if s.make_room(piece(row), title) { + s.band(&sec.title, color); + } + let split = !whole(row); + for (k, key) in shortcuts(&row.shortcut).into_iter().enumerate() { + // A row taller than a column goes on in the next one, line by line. + if k > 0 && split && s.make_room(ROW_HEIGHT, title) { + s.band(&sec.title, color); + } + s.line(key, (k == 0).then_some(row.name.as_str()), n % 2 == 1); + } + } + } + s.doc +} + +/// The sheet as a PDF, one page per artboard of [`sheet_document`]. +pub fn sheet_pdf(title: &str, sections: &[Section], page: PageSize) -> Result, String> { + let doc = sheet_document(title, sections, page); + let opts = vectorcraft_pdf::PdfOptions { title: Some(title.to_string()), ..Default::default() }; + vectorcraft_pdf::export(&doc, &opts).map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(name: &str, shortcut: &str) -> Row { + Row { name: name.into(), shortcut: shortcut.into() } + } + + /// Every type object in `doc`, in stacking order: its text, its style and its left edge. + fn text_objects(doc: &Document) -> Vec<(String, CharStyle, f64)> { + let mut out = vec![]; + let Some(layer) = doc.default_layer() else { return out }; + for n in doc.children(Some(layer)).into_iter().flatten() { + if let NodeKind::Text(t) = &n.kind { + out.push((t.plain_text(), t.first_style(), t.xf.translation().x)); + } + } + out + } + + /// The text of every type object in `doc`, in stacking order. + fn texts(doc: &Document) -> Vec { + text_objects(doc).into_iter().map(|(t, ..)| t).collect() + } + + /// Every node of `doc` lies on one of its pages. + fn assert_on_pages(doc: &Document) { + let l = doc.default_layer().unwrap_or(NodeId(0)); + for n in doc.children(Some(l)).into_iter().flatten() { + let Some(b) = n.geometric_bounds() else { continue }; + let on = |a: &vectorcraft_doc::Artboard| { + let r = a.rect.inflate(0.5, 0.5); + r.union(b) == r + }; + assert!(doc.artboards.iter().any(on), "{b:?} is off the pages"); + } + } + + /// The sheet lists the rows that have a shortcut and leaves out the others, and a section with + /// no shortcut at all has no band. + #[test] + fn sheet_leaves_out_rows_and_sections_without_a_shortcut() { + let sections = [ + Section { title: "Tools".into(), rows: vec![row("Pen", "P"), row("Unbound Tool", "")] }, + Section { title: "Empty Menu".into(), rows: vec![row("Nothing", "")] }, + Section { title: "Edit".into(), rows: vec![row("Copy", "Ctrl+C")] }, + ]; + let doc = sheet_document("Keyboard Shortcuts · Custom", §ions, PageSize::Letter); + let t = texts(&doc); + assert_eq!(t, ["Keyboard Shortcuts · Custom", "Tools", "P", "Pen", "Edit", "Ctrl+C", "Copy"]); + } + + /// Each page is a landscape artboard of the paper picked, and rows that do not fit on one page + /// go on to more pages of the same size, each with the title. + #[test] + fn sheet_pages_are_landscape_pages_of_the_paper_picked() { + let rows: Vec = (0..600).map(|i| row(&format!("Command {i}"), &format!("Ctrl+{i}"))).collect(); + let sections = [Section { title: "Edit".into(), rows }]; + for (page, (w, h)) in [(PageSize::Letter, (792.0, 612.0)), (PageSize::A4, (841.89, 595.28))] { + let doc = sheet_document("Sheet", §ions, page); + assert!(doc.artboards.len() >= 2, "{page:?}: {} pages", doc.artboards.len()); + for a in &doc.artboards { + assert!((a.rect.width() - w).abs() < 1e-9 && (a.rect.height() - h).abs() < 1e-9, "{page:?}: {:?}", a.rect); + } + let t = texts(&doc); + assert_eq!(t.iter().filter(|s| *s == "Sheet").count(), doc.artboards.len(), "a title on every page"); + assert_eq!(t.iter().filter(|s| s.starts_with("Command ")).count(), 600, "every row once"); + assert_on_pages(&doc); + // Each column the section takes starts with its band. + let mut columns: Vec = vec![]; + for (_, _, x) in text_objects(&doc).iter().filter(|(t, ..)| t.starts_with("Command ")) { + if !columns.iter().any(|c| (c - x).abs() < 1e-6) { + columns.push(*x); + } + } + assert!(columns.len() > COLUMNS, "{page:?}: {} columns", columns.len()); + assert_eq!(t.iter().filter(|s| *s == "Edit").count(), columns.len(), "{page:?}: a band in every column"); + } + let pdf = sheet_pdf("Sheet", &[Section { title: "Edit".into(), rows: vec![row("Copy", "Ctrl+C")] }], PageSize::A4).unwrap(); + assert!(pdf.starts_with(b"%PDF-")); + assert_eq!(PageSize::parse("a4"), Some(PageSize::A4)); + assert_eq!(PageSize::parse("A4"), None); + assert_eq!(PageSize::parse("legal"), None); + } + + /// A row with more shortcuts than a column holds goes on in the next column, under its band + /// again, and stays on the pages. + #[test] + fn a_row_taller_than_a_column_goes_on_in_the_next() { + let keys: Vec = (0..150).map(|i| format!("Ctrl+F{i}")).collect(); + let sections = [Section { title: "Edit".into(), rows: vec![row("Many", &keys.join(" · ")), row("After", "Ctrl+A")] }]; + let doc = sheet_document("Sheet", §ions, PageSize::Letter); + assert_on_pages(&doc); + let t = texts(&doc); + for k in &keys { + assert_eq!(t.iter().filter(|s| *s == k).count(), 1, "{k}"); + } + assert_eq!(t.iter().filter(|s| *s == "Many").count(), 1); + assert!(t.iter().filter(|s| *s == "Edit").count() >= 3, "{t:?}"); + assert!(t.contains(&"After".to_string())); + } + + /// The sheet's font has the macOS modifier symbols the key names use, and the ellipsis. + #[test] + fn the_sheets_font_has_the_key_name_characters() { + let db = vectorcraft_text::FontDb::global(); + for face in ["Regular", "Bold"] { + let f = db.face(FONT, face).expect("the bundled face"); + for c in "⌃⌥⇧⌘…".chars() { + assert!(f.covers(c), "{face} lacks {c} (U+{:04X})", c as u32); + } + } + } + + /// A row with several shortcuts lists each on a line of its own, and a shortcut too wide for + /// its column is kept whole and set smaller to fit. + #[test] + fn sheet_keeps_every_shortcut_of_a_row_whole() { + let long = "Ctrl+Alt+Shift+".repeat(6) + "PageDown"; + let sections = [Section { title: "Edit".into(), rows: vec![row("Copy", "Ctrl+C · Ctrl+Insert"), row("Long", &long)] }]; + let objects = text_objects(&sheet_document("Sheet", §ions, PageSize::Letter)); + let t: Vec<&str> = objects.iter().map(|(t, ..)| t.as_str()).collect(); + assert_eq!(t, ["Sheet", "Edit", "Ctrl+C", "Copy", "Ctrl+Insert", long.as_str(), "Long"]); + let (_, short, _) = &objects[2]; + assert_eq!(short.size, ROW_SIZE); + let (_, set, _) = &objects[5]; + let (w, _) = PageSize::Letter.landscape(); + let column = (w - 2.0 * MARGIN - GUTTER * (COLUMNS - 1) as f64) / COLUMNS as f64; + assert!(set.size < ROW_SIZE, "{}", set.size); + assert!(width(&long, set) <= column * MAX_SHORTCUT_SHARE - 6.0 + 0.01, "{} wide", width(&long, set)); + } + + /// A name too long for its column is cut short with an ellipsis. + #[test] + fn a_long_name_is_cut_short_to_fit_its_column() { + let long = "Command ".repeat(20); + let doc = sheet_document("Sheet", &[Section { title: "Edit".into(), rows: vec![row(&long, "Ctrl+L")] }], PageSize::Letter); + let shown = texts(&doc).into_iter().find(|t| t.starts_with("Command")).unwrap_or_default(); + assert!(shown.ends_with('…') && shown.len() < long.len(), "{shown}"); + let plain = style(ROW_SIZE, false, Color::BLACK); + let room = 100.0; + assert!(width(&shown, &plain) > 0.0); + let fit = fitted(&long, &plain, room); + assert!(width(&fit, &plain) <= room, "{fit}"); + let one_more = long.chars().take(fit.chars().count()).collect::().trim_end().to_string() + "…"; + assert!(width(&one_more, &plain) > room || one_more == fit, "{fit} is the longest start that fits"); + // A name far longer than any line is measured only in part. + let huge = "x".repeat(1_000_000); + let title = fitted(&huge, &style(TITLE_SIZE, true, Color::BLACK), 700.0); + assert!(title.ends_with('…') && title.chars().count() <= MAX_FIT_CHARS + 1, "{} chars", title.chars().count()); + } +} diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index d6a06960bb..df9662e570 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -456,7 +456,9 @@ fn keyboard_shortcuts_export_text_writes_the_working_set_as_text() { d.fields.insert("set".into(), json!("Custom")); click(&mut app, "Export Text…", dialogs); match shown.requests().as_slice() { - [PickRequest::Save(pick)] => assert_eq!(pick.filters, FilePick::filters([("Text", &["txt"][..])])), + [PickRequest::Save(pick)] => { + assert_eq!(pick.filters, FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..])])) + } other => panic!("{other:?}"), } shown.answer(&["/keys/list.txt"]); @@ -474,6 +476,74 @@ fn keyboard_shortcuts_export_text_writes_the_working_set_as_text() { assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "the dialog stays open"); } +/// The file type picked in Export Text…'s save dialog picks the file: the PDF sheet for a name +/// typed with `.pdf`, and for a type the dialog reports with a name typed without an extension, +/// that type's file under the name with its extension. +#[test] +fn keyboard_shortcuts_export_text_writes_the_format_picked_in_its_save_dialog() { + for (answer, path, start) in [ + (&["/keys/list.pdf"][..], "/keys/list.pdf", &b"%PDF-"[..]), + (&["/keys/sheet", "pdf"][..], "/keys/sheet.pdf", &b"%PDF-"[..]), + (&["/keys/plain", "txt"][..], "/keys/plain.txt", &b"Keyboard Shortcuts\n"[..]), + ] { + let (mut app, shown, _) = app(); + type Files = Rc)>>>; + let files: Files = Default::default(); + let f = files.clone(); + app.services.write = Some(Box::new(move |path: &str, b: &[u8]| { + f.borrow_mut().push((path.to_string(), b.to_vec())); + Ok(()) + })); + app.run("edit.keyboardShortcuts", json!({})).unwrap(); + click(&mut app, "Export Text…", dialogs); + shown.answer(answer); + poll(&mut app); + let files = files.borrow(); + let [(written, bytes)] = files.as_slice() else { panic!("{files:?}") }; + assert_eq!(written, path); + assert!(bytes.starts_with(start), "{path}: {:?}", String::from_utf8_lossy(&bytes[..bytes.len().min(40)])); + } +} + +/// `shortcuts.exportText` with a `format` and no `path` gives the name its save dialog answers +/// that format's extension, though the dialog reports no file type. +#[test] +fn export_text_with_a_format_gives_the_answered_name_its_extension() { + let (mut app, shown, _) = app(); + let written: Rc>> = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, _: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })); + let _ = app.run("shortcuts.exportText", json!({"format": "sheet"})); + shown.answer(&["/keys/sheet"]); + poll(&mut app); + assert_eq!(*written.borrow(), ["/keys/sheet.pdf"]); +} + +/// A name that Export Text… gives the picked type's extension names a file the save dialog did +/// not check: when one is there, a question asks before replacing it and nothing is written +/// meanwhile. +#[test] +fn keyboard_shortcuts_export_text_asks_before_replacing_a_file_its_extension_names() { + let (mut app, shown, _) = app(); + let written: Rc>> = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, _: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })); + app.services.exists = Some(std::sync::Arc::new(|p: &str| p == "/keys/list.pdf")); + app.run("edit.keyboardShortcuts", json!({})).unwrap(); + click(&mut app, "Export Text…", dialogs); + shown.answer(&["/keys/list.txt", "pdf"]); + poll(&mut app); + assert!(written.borrow().is_empty(), "{:?}", written.borrow()); + let d = app.ui.dialog.as_ref().expect("a question"); + assert_eq!(d.str("path"), "/keys/list.pdf"); +} + /// Keyboard Shortcuts' Import… opens a shortcut set another app saved as text (`.kys`) in Import /// Shortcut Set over the dialog when its file dialog answers, and the dialog's working set stays in /// Keyboard Shortcuts, which Cancel shows again. diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index df003ddb01..b8bd53586e 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -89,7 +89,13 @@ fn save_panels_show_the_file_type_they_write() { app.run("shortcuts.export", json!({})).unwrap(); assert_eq!(last_shown(&shown), FilePick::filters([("Shortcut sets", &["json"][..])]), "Keyboard Shortcuts › Export…"); app.run("shortcuts.exportText", json!({})).unwrap(); - assert_eq!(last_shown(&shown), FilePick::filters([("Text", &["txt"][..])]), "Keyboard Shortcuts › Export Text…"); + assert_eq!( + last_shown(&shown), + FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..])]), + "Keyboard Shortcuts › Export Text…" + ); + app.run("shortcuts.exportText", json!({"format": "sheet"})).unwrap(); + assert_eq!(last_shown(&shown), FilePick::filters([("Shortcut sheet", &["pdf"][..])]), "shortcuts.exportText with a format"); let presets = [ ("pdf.preset.save", json!({"name": "Mine"}), "pdf.preset.export", "PDF presets", pdfcmds::PRESET_EXTS), ("print.presets.save", json!({"name": "Mine"}), "print.presets.export", "Print presets", printpresets::PRESET_EXTS), diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..510380a174 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6300,18 +6300,42 @@ path and label, with its id when the row shows it, and the key runs what a click {id}`. A removed plug-in's row goes away and its key runs nothing; its shortcut stays saved and applies again when a plug-in with the same id is installed. -`shortcuts.exportText {path?}` saves the current set's shortcut list as a UTF-8 text file, as Edit › Keyboard -Shortcuts › Export Text… does with the dialog's set as edited so far. The file starts with a "Keyboard Shortcuts" line -and a "Set:" line with the set's name, followed by a Tools section and a Menu Commands section. Each section lists the -rows Edit › Keyboard Shortcuts lists, in its order and with names as it shows them: one line per row, with the name, a -tab and the shortcuts as the dialog shows them on the current platform. A row with no shortcut ends after the tab. -Without `path` a save dialog asks for the file. A `path` that is not a string, or a file that cannot be written, -returns an error, and nothing is written. The layout is VectorCraft's own. The reference app's [Export keyboard -shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) +`shortcuts.exportText {path?, format?, pageSize?}` saves the current set's shortcut list as a UTF-8 text file, as +Edit › Keyboard Shortcuts › Export Text… does with the dialog's set as edited so far. The file starts with a "Keyboard +Shortcuts" line and a "Set:" line with the set's name, followed by a Tools section and a Menu Commands section. Each +section lists the rows Edit › Keyboard Shortcuts lists, in its order and with names as it shows them: one line per +row, with the name, a tab and the shortcuts as the dialog shows them on the current platform. A row with no shortcut +ends after the tab. Without `path` a save dialog asks for the file. A `path` that is not a string, or a file that +cannot be written, returns an error, and nothing is written. The layout is VectorCraft's own. The reference app's +[Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes saving the list from the Keyboard Shortcuts dialog as a text file, and does not describe its layout. +`format` picks the file: `"text"` (the default) writes the text file above and `"sheet"` a printable shortcut sheet +as a PDF. A `path` is written as given, in the format `format` names, or as text without `format`. In the desktop +app, without `path`, the save dialog offers both formats (Text and Shortcut sheet, Text first) unless `format` names +one, and the file type picked in it decides. When `format` names a format, or the dialog reports the type picked, the +name the dialog returns gets that format's extension (`.txt` or `.pdf`): one of these extensions is replaced, and the +extension is added to any other name. When that names a file that is already there, a question asks before replacing +it. The web app downloads the format `format` names, text without it. With no file dialog, file writer or download, +the command returns the file: the text file as `text`, the sheet in base64 as `pdf`. A `format` other than `"text"` +or `"sheet"`, or a `pageSize` other than `"letter"` or `"a4"` (lowercase), returns an error, and nothing is written. + +The shortcut sheet lists the rows that have a shortcut in groups: the Tools rows under the Tools group, then each +top-level menu as a group, in the order the dialog first lists a command of it, with the command named without its +top-level menu. The group names, command names and shortcuts are in the UI language, as the dialog shows them. Each +group has a colored band with its name, and below it the rows, the shortcut on the left and the name on the right. The +groups flow down four columns of landscape pages and onto more pages when they do not fit. `pageSize` is `"letter"` +(792 × 612 pt) or `"a4"` (841.89 × 595.28 pt). Without it the sheet is on A4 when the current document prints on A4 +(its print settings, or, with none saved, a first artboard of A4 size), and on Letter otherwise. Each page is titled +with "Keyboard Shortcuts" and the set's name. A group that continues in the next column repeats its band there. A row +with several shortcuts has a line for each, kept in one column unless the row is taller than a column. A shortcut is +never shortened: one too wide for its column is set smaller. A name too long for its column ends in "…". The type is +Source Sans 3, which VectorCraft bundles and which has the macOS modifier symbols (⌃ ⌥ ⇧ ⌘). Characters it does not +have are drawn in another font the app has loaded, when one has them. The layout is VectorCraft's own. + ```json {"name":"run_command","arguments":{"command":"shortcuts.exportText","params":{"path":"/Users/me/Shortcuts.txt"}}} +{"name":"run_command","arguments":{"command":"shortcuts.exportText","params":{"path":"/Users/me/Shortcuts.pdf","format":"sheet","pageSize":"a4"}}} ``` The desktop app adds its active artboard, the one the Artboards panel highlights, to the `object.align`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..f621ba0de4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1096,7 +1096,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+F6 (`window.nextDocument`) and Cmd/Ctrl+Shift+F6 (`window.previousDocument`) make the next and the previous open document the current one, in tab order and as a click on its tab does, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for navigating to the next and the previous document. After the last document comes the first, and before the first document comes the last. From the Home screen the keys go to the first and the last document. Keyboard Shortcuts lists both under Window. - Cmd/Ctrl+Alt+Shift+U (`document.switchUnits`) switches the document to the next unit of measurement, in one undo step, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for switching units of measurement. The page does not give an order. VectorCraft steps through the units in the order a right-click on a ruler lists them (Points, Picas, Inches, Millimeters, Centimeters, Pixels, Feet & Inches, Meters, Yards, Feet) and goes from Feet back to Points. - Shortcut sets other apps save as text (`.kys`) open in Import Shortcut Set from File › Open, from Edit › Keyboard Shortcuts › Import… in the desktop app, or from a drop on the window. It matches each entry to a tool, command or panel by name and decodes the file's key and modifier codes where VectorCraft's default shortcuts agree on them; the user answers the rest, and Apply fills the Keyboard Shortcuts dialog's working set. The answers are kept with the preferences for the next import (`shortcutSet.read`, `importMatches.*`). - - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. Tests `shortcut_editor::tests::export_text_*` and `tests::picks::keyboard_shortcuts_export_text_writes_the_working_set_as_text`. + - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?, format?, pageSize?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. In the desktop app its save dialog also offers a printable shortcut sheet as a PDF, which `format: "sheet"` also picks (`pageSize: "letter" | "a4"`, A4 when the current document prints on A4): the rows with a shortcut under a colored band per group, in columns on landscape pages, a layout of VectorCraft's own. Tests `shortcut_editor::tests::export_text_*`, `shortcut_editor::tests::export_sections_*`, `shortcut_editor::tests::the_save_dialogs_answer_picks_the_export_text_format`, `shortcut_editor::tests::the_sheet_is_on_a4_when_the_document_prints_on_a4`, `shortcut_sheet::tests::*`, `tests::picks::keyboard_shortcuts_export_text_*` and `tests::picks::export_text_with_a_format_gives_the_answered_name_its_extension`. - On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one. - On Linux and the BSDs, when the desktop leaves the window's frame to the app (a Wayland session without server-side decorations, such as GNOME) and the window is not opened through XWayland, the app bar's window buttons follow the `button-layout` key of `org.gnome.desktop.wm.preferences` ([schema](https://gitlab.gnome.org/GNOME/gsettings-desktop-schemas/-/blob/master/schemas/org.gnome.desktop.wm.preferences.gschema.xml.in)): Close alone at the right, all three at the left, or split between the ends, in the listed order with the first one leftmost. When the key cannot be read or names no window button, and for an app frame turned on by `VECTORCRAFT_TITLEBAR=app` or VectorCraft Title Bar on Every Desktop, all three stay at the right. Tests `titlebar::tests::caption_buttons_follow_the_caption_layout`, `tests::the_caption_buttons_follow_the_frame_layout` and `tests::the_start_frame_applies_the_app_title_bar_preference`. - On Linux and the BSDs, Preferences › User Interface › VectorCraft Title Bar on Every Desktop (off by default) uses the app bar as the title bar from the next start in the sessions where the desktop would draw the window's frame (X11, Wayland compositors with server-side decorations such as KDE Plasma, a window opened through XWayland). System Title Bar and `VECTORCRAFT_TITLEBAR` take precedence over it, and `VECTORCRAFT_TITLEBAR` also takes precedence over System Title Bar for the run it is set in. Only the values `app`, `system` and `desktop` take precedence (case-sensitive, surrounding spaces ignored); any other value, such as `unknown`, is ignored and does not override System Title Bar.