diff --git a/ROADMAP.md b/ROADMAP.md index 696285b8..574b4e9c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -145,7 +145,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist - **Geometry and effects:** - Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart. - Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters). -- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). +- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). - **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, French, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, French, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `` and PDF soft masks. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 8ec36b24..b6f70826 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -285,6 +285,8 @@ Fill with Placeholder Text Vyplnit zástupným textem Insert Inline Symbol Vložit symbol do textu Show Hidden Characters Zobrazit skryté znaky + Bold Tučné + Italic Kurzíva Hide Hidden Characters Skrýt skryté znaky Type Orientation Orientace textu Horizontal Vodorovně diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 73163d67..834f0e9b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2446,6 +2446,8 @@ Show Guides Mostrar guías Show handles when multiple anchors are selected Mostrar manejadores al seleccionar varias anclas Show Hidden Characters Mostrar caracteres ocultos + Bold Negrita + Italic Cursiva Show Images in Outline Mode Mostrar imágenes en modo de contorno Show in Folder Mostrar en carpeta Show Indic Options Mostrar opciones índicas @@ -3126,6 +3128,8 @@ axis Both Ambos # stays English for agents and tests. `{_1}`, `{_2}` … stand for the `{}` of the format string, in order # (`complete_languages_translate_every_message` lists any that are missing). Command ids, parameter # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. +@msg select some type first selecciona primero algún texto +@msg {_1} has no {_2} style {_1} no tiene el estilo {_2} @msg a layer couldn't be read no se pudo leer una capa @msg it has more than one artboard tiene más de una mesa de trabajo @msg it has no page no tiene página diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ef600053..cf870a1e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2443,6 +2443,8 @@ Show Guides Afficher les repères Show handles when multiple anchors are selected Afficher les poignées lorsque plusieurs points d’ancrage sont sélectionnés Show Hidden Characters Afficher les caractères masqués + Bold Gras + Italic Italique Show Images in Outline Mode Afficher les images en mode Tracés Show in Folder Afficher dans le dossier Show Indic Options Afficher les options indiennes @@ -3123,6 +3125,8 @@ axis Both Les deux # stays English for agents and tests. `{_1}`, `{_2}` … stand for the `{}` of the format string, in order # (`complete_languages_translate_every_message` lists any that are missing). Command ids, parameter # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. +@msg select some type first sélectionnez d’abord du texte +@msg {_1} has no {_2} style {_1} n’a pas de style {_2} @msg a layer couldn't be read un calque n’a pas pu être lu @msg it has more than one artboard il a plus d'un plan de travail @msg it has no page il n’a pas de page diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 23abffe6..d386fb56 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2446,6 +2446,8 @@ Show Guides Mostra guide Show handles when multiple anchors are selected Mostra le maniglie quando sono selezionati più punti di ancoraggio Show Hidden Characters Mostra caratteri nascosti + Bold Grassetto + Italic Corsivo Show Images in Outline Mode Mostra immagini in modalità Contorno Show in Folder Mostra nella cartella Show Indic Options Mostra opzioni per lingue indiane @@ -3126,6 +3128,8 @@ axis Both Entrambi # stays English for agents and tests. `{_1}`, `{_2}` … stand for the `{}` of the format string, in order # (`complete_languages_translate_every_message` lists any that are missing). Command ids, parameter # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. +@msg select some type first seleziona prima del testo +@msg {_1} has no {_2} style {_1} non ha lo stile {_2} @msg a layer couldn't be read non è stato possibile leggere un livello @msg it has more than one artboard ha più di una tavola da disegno @msg it has no page non ha pagine diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4c7da56e..4fdc46ba 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -326,6 +326,8 @@ Fill with Placeholder Text サンプルテキストの割り付け Insert Inline Symbol インラインシンボルを挿入 Show Hidden Characters 制御文字を表示 + Bold 太字 + Italic 斜体 Type Orientation 組み方向 Horizontal 横書き Vertical 縦書き diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index bf3679f9..b5941b13 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2134,6 +2134,8 @@ Show Grid (⌘') Mostrar Grade (⌘') Show Guides Mostrar Guias Show Hidden Characters Mostrar Caracteres Ocultos + Bold Negrito + Italic Itálico Show Images in Outline Mode Mostrar Imagens no Modo de Contorno Show Indic Options Mostrar Opções do Índico Show Link Info Mostrar Informações do Link diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 705dcff9..af7325bc 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2442,6 +2442,8 @@ Show Guides Показать направляющие Show handles when multiple anchors are selected Показывать маркеры при выделении нескольких опорных точек Show Hidden Characters Показать скрытые символы + Bold Полужирный + Italic Курсив Show Images in Outline Mode Показывать изображения в режиме контуров Show in Folder Показать в папке Show Indic Options Показать параметры индийских языков @@ -3122,6 +3124,8 @@ axis Both Оба # stays English for agents and tests. `{_1}`, `{_2}` … stand for the `{}` of the format string, in order # (`complete_languages_translate_every_message` lists any that are missing). Command ids, parameter # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. +@msg select some type first сначала выделите текст +@msg {_1} has no {_2} style у {_1} нет начертания {_2} @msg a layer couldn't be read не удалось прочитать слой @msg it has more than one artboard в нём несколько монтажных областей @msg it has no page в нём нет страницы diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e831a40a..7b0b5353 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2364,6 +2364,8 @@ Show Guides 显示参考线 Show handles when multiple anchors are selected 选择多个锚点时显示手柄 Show Hidden Characters 显示隐藏字符 + Bold 粗体 + Italic 斜体 Show Images in Outline Mode 以轮廓模式显示图像 Show in Folder 在文件夹中显示 Show Indic Options 显示印度文字选项 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c4e6155e..70f9b792 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2449,6 +2449,8 @@ Show Guides 顯示參考線 Show handles when multiple anchors are selected 選取多個錨點時顯示控制把手 Show Hidden Characters 顯示隱藏字元 + Bold 粗體 + Italic 斜體 Show Images in Outline Mode 在外框模式中顯示影像 Show in Folder 在資料夾中顯示 Show Indic Options 顯示印度文字選項 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 00b76b15..2fa9b9a8 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -11,6 +11,7 @@ use vectorcraft_engine::cmd::fileio::SaveMode; use crate::VectorcraftApp; use crate::io; +use crate::panels::character::Face; use crate::state::{DockTab, next_zoom}; use crate::theme::{self, Brightness, Tokens}; use crate::widgets; @@ -175,6 +176,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("view.textThreads", "Hide Text Threads", "Cmd+Shift+Y", "{} toggle the thread lines between threaded text frames"), ("view.gradientAnnotator", "Hide Gradient Annotator", "Cmd+Alt+G", "{} toggle the Gradient tool's annotator"), ("type.hiddenCharacters", "Show Hidden Characters", "Cmd+Alt+I", "{} toggle markers for spaces, paragraph ends and story ends"), + ( + "type.bold", + "Bold", + "", + "{} the selected type (or the Type tool's selection) in its family's Bold face, or back to the regular face when it is bold; keeps italics. A family without that face is left as it is, with a message. While the Type tool edits text, Cmd+Shift+B", + ), + ( + "type.italic", + "Italic", + "", + "{} the selected type (or the Type tool's selection) in its family's Italic (or Oblique) face, or back upright when it is italic; keeps the weight. A family without that face is left as it is, with a message. While the Type tool edits text, Cmd+Shift+I", + ), ("effect.last", "Last Effect…", "Cmd+Alt+Shift+E", "{} open the dialog of the last effect applied"), ("view.zoomIn", "Zoom In", "Cmd+=", "{}"), ("view.zoomOut", "Zoom Out", "Cmd+-", "{}"), @@ -930,6 +943,8 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.view.snap_to_pixel), "view.textThreads" => flag(&mut app.ui.view.text_threads), "type.hiddenCharacters" => flag(&mut app.ui.view.hidden_chars), + "type.bold" => crate::panels::character::toggle_face(app, Face::Bold), + "type.italic" => crate::panels::character::toggle_face(app, Face::Italic), "view.gradientAnnotator" => flag(&mut app.ui.view.gradient_annotator), "effect.last" => match app.last_effect.clone() { Some((e, params)) => { @@ -1801,6 +1816,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { match id { // Save is off for a clean document that already has its own file. "file.save" => app.session.active().is_some_and(|d| d.path.is_none() || d.converted || d.is_dirty()), + "type.bold" | "type.italic" => crate::panels::character::text_style(app).is_some(), "file.reveal" => app.services.reveal.is_some() && app.session.active().is_some_and(|d| d.path.is_some()), "file.place" | "file.export.svg" @@ -2220,6 +2236,8 @@ pub fn menu_tree() -> Vec<(&'static str, Vec)> { sub("Font", font_items()), sub("Recent Fonts", RECENT_FONT_IDS.iter().map(|id| c("Recent Font", id)).collect()), sub("Size", TYPE_SIZES.iter().map(|(l, n)| cp(l, "text.setStyle", json!({ "size": n }))).collect()), + c("Bold", "type.bold"), + c("Italic", "type.italic"), Sep, panel("Glyphs", "glyphs"), sub("Insert Special Character", insert_items(INSERT_SPECIAL)), diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index e67c9181..9405ab8f 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -111,6 +111,90 @@ fn char_cmd(app: &mut VectorcraftApp, cmd: &str, p: Value) { range_style(app, p); } +/// The faces Type › Bold and Type › Italic switch to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Face { + Bold, + Italic, +} + +/// Words of a style name that set its weight: a style without any is the family's regular weight. +const WEIGHTS: [&str; 16] = [ + "thin", + "hairline", + "extralight", + "ultralight", + "light", + "book", + "medium", + "semibold", + "demibold", + "demi", + "bold", + "extrabold", + "ultrabold", + "heavy", + "black", + "ultra", +]; + +/// Words that name the regular weight, upright: not part of what Bold and Italic keep. +const PLAIN: [&str; 5] = ["regular", "normal", "roman", "plain", "upright"]; + +/// A style name's (bold, regular weight, italic, the other words): `Bold Italic` is (true, false, +/// true, []), `Narrow Italic` (false, true, true, ["narrow"]), `SemiBold` (false, false, false, []). +fn face_of(style: &str) -> (bool, bool, bool, Vec) { + let words: Vec = style.split([' ', '-', '_']).filter(|w| !w.is_empty()).map(str::to_ascii_lowercase).collect(); + let italic = words.iter().any(|w| w == "italic" || w == "oblique"); + let bold = words.iter().any(|w| w == "bold"); + let regular = !words.iter().any(|w| WEIGHTS.contains(&w.as_str())); + let mut rest: Vec = + words.into_iter().filter(|w| !WEIGHTS.contains(&w.as_str()) && !PLAIN.contains(&w.as_str()) && w != "italic" && w != "oblique").collect(); + rest.sort(); + (bold, regular, italic, rest) +} + +/// The style of `styles` that is bold (else of regular weight) and italic (else upright), with the +/// same other words as style `like` (a Narrow face stays Narrow, a plain one plain). +fn pick_face<'a>(styles: &'a [String], bold: bool, italic: bool, like: &str) -> Option<&'a str> { + let (.., keep) = face_of(like); + styles + .iter() + .map(String::as_str) + .filter(|s| { + let (b, r, i, rest) = face_of(s); + i == italic && (if bold { b } else { r }) && rest == keep + }) + // `Regular` before `Regular Text`-like doubles: the plainest name is the family's own face. + .min_by_key(|s| s.len()) +} + +/// Type › Bold and Type › Italic (Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text, as in +/// page layout apps): the family's own Bold or Italic face for the text the panels act on, or back +/// to its regular weight (upright) when it already is bold (italic). No fake bold or slant: a family +/// without that face is left as it is, and the message says so (#724). +pub(crate) fn toggle_face(app: &mut VectorcraftApp, face: Face) -> Result { + let (s, _) = text_style(app).ok_or("select some type first")?; + let styles = vectorcraft_text::FontDb::global().styles(&s.font_family); + let (bold, _, italic, _) = face_of(&s.font_style); + let (want_bold, want_italic) = match face { + Face::Bold => (!bold, italic), + Face::Italic => (bold, !italic), + }; + let Some(name) = pick_face(&styles, want_bold, want_italic, &s.font_style) else { + let wanted = match (want_bold, want_italic) { + (true, true) => "Bold Italic", + (true, false) => "Bold", + (false, true) => "Italic", + (false, false) => "Regular", + }; + return Err(format!("{} has no {} style", s.font_family, wanted)); + }; + let name = name.to_string(); + style(app, json!({ "style": name })); + Ok(json!({ "style": name })) +} + /// `text.setRangeStyle` with `p` on the range the Type tool has selected (the whole text when /// nothing is selected). Does nothing unless the Type tool edits text. pub(crate) fn range_style(app: &mut VectorcraftApp, p: Value) { @@ -213,6 +297,7 @@ enum TextInput { Copy, Cut, Paste(Option), + Face(Face), } /// Route editing keys (with modifiers), clipboard events and Cmd+C/X/V to the Type tool (Cmd+A is @@ -254,6 +339,13 @@ pub(crate) fn route_type_input(app: &mut VectorcraftApp, ctx: &egui::Context) { } return false; } + // Type › Bold and Italic, as page layout apps have them while text is edited. + if m.command && m.shift && !m.alt && matches!(key, Key::B | Key::I) { + if *pressed { + todo.push(TextInput::Face(if *key == Key::B { Face::Bold } else { Face::Italic })); + } + return false; + } if m.command && !m.shift && !m.alt && matches!(key, Key::C | Key::X | Key::V) { if *pressed { todo.push(match key { @@ -281,6 +373,11 @@ pub(crate) fn route_type_input(app: &mut VectorcraftApp, ctx: &egui::Context) { } } TextInput::Paste(s) => text_paste(app, s), + TextInput::Face(f) => { + if let Err(e) = toggle_face(app, f) { + app.status(e); + } + } } } } @@ -549,6 +646,33 @@ mod tests { use super::*; use vectorcraft_engine::Session; + /// Bold and Italic pick the family's own faces by name, and toggle back (#724). + #[test] + fn bold_and_italic_pick_the_familys_own_faces() { + let styles: Vec = + ["Light", "Narrow", "Regular", "Italic", "Narrow Italic", "SemiBold", "Bold", "Bold Condensed", "Narrow Bold", "Bold Italic", "Black"] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!(pick_face(&styles, true, false, "Regular"), Some("Bold"), "not Bold Condensed, Narrow Bold or SemiBold"); + assert_eq!(pick_face(&styles, true, true, "Italic"), Some("Bold Italic")); + assert_eq!(pick_face(&styles, false, true, "Regular"), Some("Italic")); + assert_eq!(pick_face(&styles, false, false, "Italic"), Some("Regular"), "upright again, not Narrow"); + assert_eq!(pick_face(&styles, true, false, "Narrow"), Some("Narrow Bold"), "a Narrow face stays Narrow"); + assert_eq!(pick_face(&styles, false, true, "Narrow"), Some("Narrow Italic")); + let oblique: Vec = ["Book", "Oblique", "Bold-Oblique"].iter().map(|s| s.to_string()).collect(); + assert_eq!(pick_face(&oblique, true, true, "Oblique"), Some("Bold-Oblique")); + assert_eq!(pick_face(&oblique, false, false, "Oblique"), None, "Book has a weight word: no regular face"); + assert_eq!(face_of("Bold Italic"), (true, false, true, vec![])); + assert_eq!(face_of("SemiBold"), (false, false, false, vec![])); + assert_eq!(face_of("Narrow Italic"), (false, true, true, vec!["narrow".to_string()])); + // No type selected: a message, nothing changed. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + assert!(toggle_face(&mut app, Face::Bold).is_err()); + assert!(!crate::menus::enabled(&app, "type.bold")); + } + /// Character Alignment is in the panel menu with the East Asian options only (as Mojikumi Set /// and Top-to-Top Leading are in the Paragraph panel). #[test] diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 87156edb..dbdb941d 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -466,6 +466,31 @@ mod tests { out } + /// Cmd+Shift+B while the Type tool edits text is Type › Bold, not Hide Bounding Box (#724). + #[test] + fn cmd_shift_b_while_typing_is_bold_not_the_bounding_box() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.select_tool("type"); + let view = app.view_info(); + for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { + app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 50.0, 50.0), view).unwrap(); + } + frame(&mut app, vec![egui::Event::Text("Bold".into())]); + assert!(app.session.tool_wants_text()); + let chord = + egui::Event::Key { key: Key::B, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND | Modifiers::SHIFT }; + frame(&mut app, vec![chord.clone()]); + assert!(app.ui.view.bounding_box, "the bounding box stays"); + // The chord reached Bold: the text is in a bold face, or its family has none and says so. + let face = crate::panels::character::text_style(&app).map(|(s, _)| s.font_style).unwrap_or_default(); + assert!(face.contains("Bold") || app.ui.status.contains("has no Bold style"), "{face:?} {:?}", app.ui.status); + // Out of the text, the chord hides the bounding box as before. + app.select_tool("selection"); + frame(&mut app, vec![chord]); + assert!(!app.ui.view.bounding_box); + } + /// Tab shows and hides the panels, and in the Type tool it types a tab, without moving the /// keyboard focus on to a field: the keys after it (a tool letter, the next letter typed) still /// work.