DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
UI: Tabs panel with a ruler over the text column
aiongg2e3d954f5b14
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 34dd61442..28b7af7cc 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1336,7 +1336,7 @@ fn ruler_units_menu(app: &mut DesignApp, ui: &mut egui::Ui, key: &str, cur: desi}}-fn fmt_tick(v: f64) -> String {+pub(crate) fn fmt_tick(v: f64) -> String {let r = v.round();if (v - r).abs() < 1e-6 { format!("{}", r as i64) } else { format!("{v:.1}") }}diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rsindex fdf20e6c4..a9b723fa1 100644--- a/crates/ui-egui/src/dock.rs+++ b/crates/ui-egui/src/dock.rs@@ -48,6 +48,14 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[("dataMerge", "Data Merge", "panel-datamerge"),];+/// Panels that only float (they open from a menu, not from the icon column).+pub const FLOATING_PANELS: &[(&str, &str)] = &[("tabs", "Tabs")];++/// The English name of panel `id`.+pub fn panel_label(id: &str) -> &'static str {+ ICON_PANELS.iter().map(|p| (p.0, p.1)).chain(FLOATING_PANELS.iter().copied()).find(|p| p.0 == id).map_or("Panel", |p| p.1)+}+pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {let t = Tokens::get(ui.ctx());// Expanded panel stack (outermost, 253 pt) — declared first so it sits at the far right.@@ -125,7 +133,7 @@ fn dock_header(ui: &mut egui::Ui, t: &Tokens, chevron: &str) {pub fn flyout(app: &mut DesignApp, ctx: &egui::Context) {let Some(id) = app.ui.open_panel.clone() else { return };let t = Tokens::get(ctx);- let label = crate::i18n::tr(&app.ui.language, ICON_PANELS.iter().find(|p| p.0 == id).map(|p| p.1).unwrap_or("Panel")).to_owned();+ let label = crate::i18n::tr(&app.ui.language, panel_label(&id)).to_owned();let screen = ctx.content_rect();let dock_w = if app.ui.dock_expanded { ctx.memory(|m| m.area_rect(egui::Id::new("dock")).map(|r| r.width())).unwrap_or(280.0) } else { 0.0 };let pos = egui::pos2(screen.max.x - 37.0 - dock_w - 262.0, 120.0);@@ -203,6 +211,7 @@ pub fn panel_body(app: &mut DesignApp, ui: &mut egui::Ui, id: &str) {"scripts" => panels::library::scripts(app, ui),"dataMerge" => panels::datamerge::show(app, ui),"table" => panels::table::show(app, ui),+ "tabs" => panels::tabs::show(app, ui),_ => panels::properties::info_panel(app, ui),}}@@ -225,47 +234,57 @@ pub fn dock_panel(app: &mut DesignApp, id: &str) {pub fn floating(app: &mut DesignApp, ctx: &egui::Context) {let t = Tokens::get(ctx);for (id, at) in app.ui.floating.clone() {- let label = crate::i18n::tr(&app.ui.language, ICON_PANELS.iter().find(|p| p.0 == id).map(|p| p.1).unwrap_or("Panel")).to_owned();+ let label = crate::i18n::tr(&app.ui.language, panel_label(&id)).to_owned();+ let docks = ICON_PANELS.iter().any(|p| p.0 == id);let mut open = true;let mut dock = false;- let r = egui::Window::new(label.clone())+ let mut w = egui::Window::new(label.clone()).id(egui::Id::new(("floating_panel", &id))).title_bar(false).default_pos(egui::pos2(at[0], at[1]))- .default_width(256.0)+ .default_width(if id == "tabs" { 560.0 } else { 256.0 }).resizable(true)- .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(0)))- .show(ctx, |ui| {- // Header strip (drag it to move the panel): name, Dock, close.- let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width().max(200.0), 24.0), Sense::hover());- ui.painter().rect_filled(strip, 0.0, t.panel_darker);- crate::rtl::paint(ui.painter(), strip.min + vec2(10.0, 12.0), egui::Align2::LEFT_CENTER, &label, semibold(12.0), t.text_strong);- let close = egui::Rect::from_min_size(egui::pos2(strip.max.x - 22.0, strip.min.y + 3.0), vec2(18.0, 18.0));- if ui- .interact(close, ui.id().with("fclose"), Sense::click())- .on_hover_ui(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Close"));- })- .clicked()- {- open = false;- }- ui.painter().text(close.center(), egui::Align2::CENTER_CENTER, "×", egui::FontId::proportional(15.0), t.text_dim);- let dock_r = egui::Rect::from_min_size(egui::pos2(strip.max.x - 44.0, strip.min.y + 3.0), vec2(18.0, 18.0));- if ui+ .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(0)));+ // The Tabs panel moves over the text frame it edits, at the column's width.+ if id == "tabs"+ && let Some((pos, width)) = app.ui.tabs_panel.place.take()+ {+ w = w.current_pos(pos).min_width(width).max_width(width);+ }+ let r = w.show(ctx, |ui| {+ // Header strip (drag it to move the panel): name, Dock, close.+ let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width().max(200.0), 24.0), Sense::hover());+ ui.painter().rect_filled(strip, 0.0, t.panel_darker);+ crate::rtl::paint(ui.painter(), strip.min + vec2(10.0, 12.0), egui::Align2::LEFT_CENTER, &label, semibold(12.0), t.text_strong);+ let close = egui::Rect::from_min_size(egui::pos2(strip.max.x - 22.0, strip.min.y + 3.0), vec2(18.0, 18.0));+ if ui+ .interact(close, ui.id().with("fclose"), Sense::click())+ .on_hover_ui(|ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Close"));+ })+ .clicked()+ {+ open = false;+ }+ ui.painter().text(close.center(), egui::Align2::CENTER_CENTER, "×", egui::FontId::proportional(15.0), t.text_dim);+ let dock_r = egui::Rect::from_min_size(egui::pos2(strip.max.x - 44.0, strip.min.y + 3.0), vec2(18.0, 18.0));+ if docks+ && ui.interact(dock_r, ui.id().with("fdock"), Sense::click()).on_hover_ui(|ui| {crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Dock panel"));}).clicked()- {- dock = true;- }+ {+ dock = true;+ }+ if docks {dock_glyph(ui.painter(), dock_r, t.text_dim);- egui::Frame::NONE.inner_margin(egui::Margin::same(10)).show(ui, |ui| {- egui::ScrollArea::vertical().max_height(ctx.content_rect().height() - 160.0).show(ui, |ui| panel_body(app, ui, &id));- });+ }+ egui::Frame::NONE.inner_margin(egui::Margin::same(10)).show(ui, |ui| {+ egui::ScrollArea::vertical().max_height(ctx.content_rect().height() - 160.0).show(ui, |ui| panel_body(app, ui, &id));});+ });// Remember where it was left.if let Some(r) = r&& let Some(f) = app.ui.floating.iter_mut().find(|(p, _)| *p == id)diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rsindex e5e8a8d08..f69c9a20b 100644--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@ -94,6 +94,42 @@ const TABLE: &[(&str, [&str; 5])] = &[("Character", ["Zeichen", "Caractère", "Carácter", "文字", "字符"]),("Paragraph", ["Absatz", "Paragraphe", "Párrafo", "段落", "段落"]),("Tabs", ["Tabulatoren", "Tabulations", "Tabulaciones", "タブ", "制表符"]),+ (+ "Left-aligned tab",+ ["Linksbündiger Tabulator", "Tabulation alignée à gauche", "Tabulación alineada a la izquierda", "左揃えタブ", "左对齐制表符"],+ ),+ ("Centered tab", ["Zentrierter Tabulator", "Tabulation centrée", "Tabulación centrada", "中央揃えタブ", "居中对齐制表符"]),+ (+ "Right-aligned tab",+ ["Rechtsbündiger Tabulator", "Tabulation alignée à droite", "Tabulación alineada a la derecha", "右揃えタブ", "右对齐制表符"],+ ),+ (+ "Tab aligned on a character",+ [+ "Am Zeichen ausgerichteter Tabulator",+ "Tabulation alignée sur un caractère",+ "Tabulación alineada en un carácter",+ "文字揃えタブ",+ "按字符对齐制表符",+ ],+ ),+ ("X:", ["X:", "X :", "X:", "X:", "X:"]),+ ("Leader:", ["Füllzeichen:", "Points de suite :", "Carácter de relleno:", "リーダー:", "前导符:"]),+ ("Align On:", ["Ausrichten an:", "Aligner sur :", "Alinear en:", "揃える文字:", "对齐位置:"]),+ (+ "Position panel above text frame",+ [+ "Bedienfeld über dem Textrahmen platzieren",+ "Placer le panneau au-dessus du bloc de texte",+ "Colocar el panel sobre el marco de texto",+ "パネルをテキストフレームの上に配置",+ "将面板置于文本框上方",+ ],+ ),+ ("Clear All", ["Alle löschen", "Tout effacer", "Borrar todo", "すべてを消去", "全部清除"]),+ ("Delete Tab", ["Tabulator löschen", "Supprimer la tabulation", "Eliminar tabulación", "タブを削除", "删除制表符"]),+ ("Repeat Tab", ["Tabulator wiederholen", "Répéter la tabulation", "Repetir tabulación", "タブを繰り返し", "重复制表符"]),+ ("Reset Indents", ["Einzüge zurücksetzen", "Réinitialiser les retraits", "Restablecer sangrías", "インデントをリセット", "重置缩进"]),("Glyphs", ["Glyphen", "Glyphes", "Glifos", "字形", "字形"]),("Story", ["Textabschnitt", "Article", "Artículo", "ストーリー", "文章"]),("Character Styles", ["Zeichenformate", "Styles de caractère", "Estilos de carácter", "文字スタイル", "字符样式"]),diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rsindex 10e393cd2..3b0ffc9ad 100644--- a/crates/ui-egui/src/i18n/ar.rs+++ b/crates/ui-egui/src/i18n/ar.rs@@ -1469,4 +1469,16 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paragraph Rules…", "خطوط الفقرة…"),("Paragraph Rules", "خطوط الفقرة"),("Rule Below", "خط سفلي"),+ ("Left-aligned tab", "علامة جدولة محاذاة لليسار"),+ ("Centered tab", "علامة جدولة توسيط"),+ ("Right-aligned tab", "علامة جدولة محاذاة لليمين"),+ ("Tab aligned on a character", "علامة جدولة محاذاة على حرف"),+ ("X:", "س:"),+ ("Leader:", "الحرف المكرر:"),+ ("Align On:", "المحاذاة على:"),+ ("Position panel above text frame", "وضع اللوحة فوق إطار النص"),+ ("Clear All", "مسح الكل"),+ ("Delete Tab", "حذف علامة الجدولة"),+ ("Repeat Tab", "تكرار علامة الجدولة"),+ ("Reset Indents", "إعادة تعيين المسافات البادئة"),];diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rsindex c91afd6ba..a6fa60eb9 100644--- a/crates/ui-egui/src/i18n/it.rs+++ b/crates/ui-egui/src/i18n/it.rs@@ -1492,4 +1492,16 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paragraph Rules", "Filetti paragrafo"),("Rule Below", "Filetto sotto"),("Tint:", "Tinta:"),+ ("Left-aligned tab", "Tabulazione allineata a sinistra"),+ ("Centered tab", "Tabulazione centrata"),+ ("Right-aligned tab", "Tabulazione allineata a destra"),+ ("Tab aligned on a character", "Tabulazione allineata a un carattere"),+ ("X:", "X:"),+ ("Leader:", "Carattere di riempimento:"),+ ("Align On:", "Allinea a:"),+ ("Position panel above text frame", "Posiziona il pannello sopra la cornice di testo"),+ ("Clear All", "Cancella tutto"),+ ("Delete Tab", "Elimina tabulazione"),+ ("Repeat Tab", "Ripeti tabulazione"),+ ("Reset Indents", "Ripristina rientri"),];diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rsindex d25717dc6..e3a01425f 100644--- a/crates/ui-egui/src/i18n/pt_br.rs+++ b/crates/ui-egui/src/i18n/pt_br.rs@@ -1073,4 +1073,17 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paragraph Rules…", "Linhas de parágrafo…"),("Paragraph Rules", "Linhas de parágrafo"),("Rule Below", "Linha abaixo"),+ ("Left-aligned tab", "Tabulação alinhada à esquerda"),+ ("Centered tab", "Tabulação centralizada"),+ ("Right-aligned tab", "Tabulação alinhada à direita"),+ ("Tab aligned on a character", "Tabulação alinhada a um caractere"),+ ("X:", "X:"),+ ("Leader:", "Caractere de preenchimento:"),+ ("Align On:", "Alinhar em:"),+ ("Position panel above text frame", "Posicionar o painel acima do quadro de texto"),+ ("Clear All", "Limpar tudo"),+ ("Delete Tab", "Excluir tabulação"),+ ("Repeat Tab", "Repetir tabulação"),+ ("Reset Indents", "Redefinir recuos"),+ ("Tabs", "Tabulações"),];diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rsindex 9a9fb89ba..e5dc4dc31 100644--- a/crates/ui-egui/src/i18n/uk.rs+++ b/crates/ui-egui/src/i18n/uk.rs@@ -1455,6 +1455,18 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Selection", "Виділення"),("All Documents", "Усі документи"),("On", "Увімкнено"),+ ("Left-aligned tab", "Табуляція з вирівнюванням ліворуч"),+ ("Centered tab", "Табуляція з вирівнюванням по центру"),+ ("Right-aligned tab", "Табуляція з вирівнюванням праворуч"),+ ("Tab aligned on a character", "Табуляція з вирівнюванням за символом"),+ ("X:", "X:"),+ ("Leader:", "Заповнювач:"),+ ("Align On:", "Вирівнювати за:"),+ ("Position panel above text frame", "Розмістити панель над текстовим фреймом"),+ ("Clear All", "Очистити все"),+ ("Delete Tab", "Видалити табуляцію"),+ ("Repeat Tab", "Повторити табуляцію"),+ ("Reset Indents", "Скинути відступи"),];/// Contexts whose Ukrainian noun differs from the shared action/text-layout label.diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rsindex 69415e9b3..1359a78b4 100644--- a/crates/ui-egui/src/icons.rs+++ b/crates/ui-egui/src/icons.rs@@ -450,6 +450,36 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {pen.line(&[(x0, y), (x1, y)]);}}+ // Tab stops: a stem standing on a foot that runs the way the text runs from the stop.+ "tab-left" | "tab-center" | "tab-right" | "tab-char" => {+ pen.w = 1.8;+ pen.line(&[(10.0, 4.0), (10.0, 15.0)]);+ let (x0, x1) = match name {+ "tab-left" => (10.0, 16.0),+ "tab-right" => (4.0, 10.0),+ _ => (5.0, 15.0),+ };+ pen.line(&[(x0, 15.0), (x1, 15.0)]);+ if name == "tab-char" {+ pen.fcircle(14.0, 10.0, 1.4);+ }+ }+ // Position the panel above the text frame: a horseshoe magnet.+ "tab-snap" => {+ pen.w = 1.6;+ let arc: Vec<(f32, f32)> = (0..=12)+ .map(|i| {+ let a = i as f32 / 12.0 * std::f32::consts::PI;+ (10.0 + 5.5 * a.cos(), 10.0 + 5.5 * a.sin())+ })+ .collect();+ let mut pts = vec![(15.5, 3.5)];+ pts.extend(arc);+ pts.push((4.5, 3.5));+ pen.line(&pts);+ pen.line(&[(3.0, 5.5), (6.0, 5.5)]);+ pen.line(&[(14.0, 5.5), (17.0, 5.5)]);+ }"ref-point" => {for i in 0..9 {let (x, y) = (4.0 + (i % 3) as f32 * 6.0, 4.0 + (i / 3) as f32 * 6.0);diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex fb81e9c34..31fa1be94 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -266,6 +266,9 @@ pub struct UiState {pub palette: Option<String>,#[serde(skip)]pub flyout: Option<usize>,+ /// Type › Tabs: the selected stop and where the panel sits.+ #[serde(skip)]+ pub tabs_panel: panels::tabs::PanelState,}impl Default for UiState {@@ -336,6 +339,7 @@ impl Default for UiState {dialog: None,palette: None,flyout: None,+ tabs_panel: Default::default(),}}}diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 94e5c0971..325ac0ed8 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -74,6 +74,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[("app.deletePage", "Delete Page", None, "{} — deletes the page in view"),("app.duplicateSpread", "Duplicate Spread", None, "{} — duplicates the spread in view (pages and items)"),("app.tablePanel", "Table Panel", Some("Shift+F9"), "{}"),+ ("app.tabsPanel", "Tabs", Some("Cmd+Shift+T"), "{} — show or hide the Tabs panel (it opens above the selected text frame)"),("app.storyEditor", "Edit in Story Editor", Some("Cmd+Y"), "{story?}"),("view.zoomIn", "Zoom In", Some("Cmd+="), "{}"),("view.zoomOut", "Zoom Out", Some("Cmd+-"), "{}"),@@ -303,6 +304,7 @@ pub const MENUS: &[(&str, &[&str])] = &["cmd:type.pathOptions","cmd:type.pathOptions|Delete Type from Path|{\"delete\": true}","<",+ "ui:app.tabsPanel","ui:window.panel|Glyphs|{\"panel\": \"glyphs\"}","cmd:type.fillWithPlaceholder",">Insert Special Character",@@ -655,6 +657,7 @@ pub const MENUS: &[(&str, &[&str])] = &["ui:window.panel","-",">Type & Tables",+ "ui:app.tabsPanel","ui:window.panel|Conditional Text|{\"panel\": \"conditions\"}","ui:window.panel|Notes|{\"panel\": \"notes\"}","ui:window.panel|Glyphs|{\"panel\": \"glyphs\"}",@@ -705,6 +708,17 @@ pub fn ui_label(id: &str) -> Option<(&'static str, Option<&'static str>)> {UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| (c.1, c.2))}+/// Type › Tabs: float the Tabs panel (placed above the selected text frame) or close it.+fn toggle_tabs_panel(app: &mut DesignApp) {+ if app.ui.floating.iter().any(|(p, _)| p == "tabs") {+ crate::dock::dock_panel(app, "tabs");+ } else {+ let at = app.canvas_rect.map_or(egui::pos2(300.0, 140.0), |r| r.min + egui::vec2(80.0, 60.0));+ crate::dock::float_panel(app, "tabs", at);+ app.ui.tabs_panel.snap_request = 2;+ }+}+/// Run a UI command; `None` if `id` isn't one.pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {let rect = app.canvas_rect;@@ -973,6 +987,10 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,app.ui.open_panel = if app.ui.open_panel.as_deref() == Some("table") { None } else { Some("table".into()) };Ok(Value::Null)}+ "app.tabsPanel" => {+ toggle_tabs_panel(app);+ Ok(Value::Null)+ }"app.exportPdf" => {if p.is_null() || p.as_object().is_none_or(|m| m.is_empty()) {crate::dialogs::open_pdf_export(app);@@ -1204,7 +1222,9 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,}"window.panel" => {let panel = p.get("panel").and_then(Value::as_str).unwrap_or("properties").to_string();- if crate::dock::DOCK_TABS.iter().any(|(id, _, _)| *id == panel) {+ if panel == "tabs" {+ toggle_tabs_panel(app);+ } else if crate::dock::DOCK_TABS.iter().any(|(id, _, _)| *id == panel) {app.ui.dock_tab = panel;app.ui.dock_expanded = true;app.ui.open_panel = None;@@ -1276,7 +1296,7 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,}"window.floatPanel" | "window.dockPanel" => {let panel = p.get("panel").and_then(Value::as_str).unwrap_or("");- if !crate::dock::ICON_PANELS.iter().any(|(id, _, _)| *id == panel) {+ if !crate::dock::ICON_PANELS.iter().any(|(id, _, _)| *id == panel) && !crate::dock::FLOATING_PANELS.iter().any(|(id, _)| *id == panel) {return Some(Err(format!("{id}: unknown panel `{panel}`")));}if id == "window.floatPanel" {diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex 05a73395b..6e03c4eb4 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -12,6 +12,7 @@ pub mod properties;pub mod styles;pub mod swatches;pub mod table;+pub mod tabs;use designcraft_doc::{Content, StrokeAlign, WrapMode};use designcraft_geom::Rect;diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rsnew file mode 100644index 000000000..db5353afe--- /dev/null+++ b/crates/ui-egui/src/panels/tabs.rs@@ -0,0 +1,450 @@+//! Tabs panel (Type › Tabs) and the tab ruler it shares with Paragraph Style Options › Tabs.+//!+//! The ruler measures from the left edge of the text column, like composition. Click the strip+//! above the scale to add a stop, drag a stop to move it, drag it off the ruler to delete it; the+//! triangles on the scale are the first-line (top), left and right (bottom) indents.++use designcraft_doc::{TabAlign, TabStop};+use designcraft_engine::cmd::tabs::MAX_POSITION;+use designcraft_geom::{Point, Unit};+use egui::{Color32, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2};+use serde_json::{Value, json};++use crate::DesignApp;+use crate::theme::Tokens;++/// Ruler height, the tab strip at its top and the inset of position 0 from its left edge.+const H: f32 = 40.0;+const STRIP: f32 = 15.0;+pub(crate) const PAD: f32 = 10.0;+/// The narrowest the panel gets when it moves over a frame (its controls fit on one row).+const MIN_WIDTH: f32 = 560.0;+/// How far off the ruler a dragged stop has to go to be deleted.+const OFF: f32 = 24.0;++/// The Tabs panel's own state (the stops themselves live in the document).+#[derive(Clone, Debug, Default)]+pub struct PanelState {+ pub selected: Option<usize>,+ /// Alignment for stops added with a click.+ pub align: TabAlign,+ /// The panel sits above the text frame: ruler pixels per point (the view zoom then).+ pub snap: Option<f32>,+ /// Place the panel above the text frame over the next frames (the first one learns its height).+ pub snap_request: u8,+ /// Where the floating window has to go (top-left) and how wide it has to be, once.+ pub place: Option<(Pos2, f32)>,+}++/// What a ruler shows.+pub(crate) struct Ruler<'a> {+ pub tabs: &'a [TabStop],+ pub left: f64,+ pub first: f64,+ pub right: f64,+ /// Column width in points.+ pub width: f64,+ pub unit: Unit,+ pub selected: Option<usize>,+ /// Points to pixels; `None` fits the column into the available width.+ pub scale: Option<f32>,+}++/// An edit made on the ruler.+#[derive(Clone, Debug, PartialEq)]+pub(crate) enum RulerEdit {+ Select(usize),+ Add(f64),+ Move(usize, f64),+ Remove(usize),+ /// `leftIndent`, `firstLineIndent` or `rightIndent` and its new value.+ Indent(&'static str, f64),+}++#[derive(Clone, Copy, Debug, PartialEq)]+enum Grab {+ Tab(usize),+ New,+ Indent(&'static str),+}++/// A drag in progress: what, where (points) and whether it is off the ruler.+#[derive(Clone, Copy, Debug)]+struct Drag {+ grab: Grab,+ pos: f64,+ off: bool,+}++pub(crate) fn tab_icon(a: TabAlign) -> &'static str {+ match a {+ TabAlign::Left => "tab-left",+ TabAlign::Center => "tab-center",+ TabAlign::Right => "tab-right",+ TabAlign::Char => "tab-char",+ }+}++/// Tooltip names of the alignments, in button order.+pub(crate) const ALIGNS: [(TabAlign, &str); 4] = [+ (TabAlign::Left, "Left-aligned tab"),+ (TabAlign::Center, "Centered tab"),+ (TabAlign::Right, "Right-aligned tab"),+ (TabAlign::Char, "Tab aligned on a character"),+];++/// Draw the ruler and report the edit the pointer made.+pub(crate) fn ruler(ui: &mut Ui, salt: &str, r: &Ruler) -> Option<RulerEdit> {+ let t = Tokens::get(ui.ctx());+ let width_pt = if r.width.is_finite() && r.width > 1.0 { r.width.min(MAX_POSITION) } else { 468.0 };+ let w = ui.available_width().max(120.0);+ let (rect, resp) = ui.allocate_exact_size(vec2(w, H), Sense::click_and_drag());+ let scale = r.scale.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(((w - 2.0 * PAD) / width_pt as f32).max(0.01));+ let x0 = rect.min.x + PAD;+ let to_x = |pt: f64| x0 + pt as f32 * scale;+ let to_pt = |x: f32| (((x - x0) / scale) as f64 * 2.0).round() / 2.0;+ let strip = Rect::from_min_max(rect.min, pos2(rect.max.x, rect.min.y + STRIP));+ let bar = Rect::from_min_max(pos2(rect.min.x, strip.max.y), rect.max);++ let hit = |p: Pos2| -> Option<Grab> {+ if bar.contains(p) {+ let near = |pt: f64| (p.x - to_x(pt)).abs() <= 6.0;+ if p.y <= bar.min.y + 10.0 && near(r.left + r.first) {+ return Some(Grab::Indent("firstLineIndent"));+ }+ if p.y >= bar.max.y - 10.0 {+ if near(r.left) {+ return Some(Grab::Indent("leftIndent"));+ }+ if near(width_pt - r.right) {+ return Some(Grab::Indent("rightIndent"));+ }+ }+ return None;+ }+ if !strip.expand2(vec2(0.0, 2.0)).contains(p) {+ return None;+ }+ let nearest =+ r.tabs.iter().enumerate().map(|(i, s)| (i, (to_x(s.position) - p.x).abs())).filter(|(_, d)| *d <= 6.0).min_by(|a, b| a.1.total_cmp(&b.1));+ Some(nearest.map_or(Grab::New, |(i, _)| Grab::Tab(i)))+ };++ let key = ui.id().with(("tab_ruler", salt));+ let mut drag: Option<Drag> = ui.data(|d| d.get_temp(key));+ let mut edit = None;+ if resp.drag_started()+ && let Some(p) = ui.input(|i| i.pointer.press_origin())+ && let Some(grab) = hit(p)+ {+ drag = Some(Drag { grab, pos: to_pt(p.x).clamp(0.0, MAX_POSITION), off: false });+ if let Grab::Tab(i) = grab {+ edit = Some(RulerEdit::Select(i));+ }+ }+ if resp.dragged()+ && let (Some(d), Some(p)) = (drag.as_mut(), resp.interact_pointer_pos())+ {+ d.pos = to_pt(p.x).clamp(0.0, width_pt.max(0.0));+ d.off = matches!(d.grab, Grab::Tab(_)) && (p.y < rect.min.y - OFF || p.y > rect.max.y + OFF);+ }+ if resp.drag_stopped()+ && let Some(d) = drag.take()+ {+ edit = Some(match d.grab {+ Grab::Tab(i) if d.off => RulerEdit::Remove(i),+ Grab::Tab(i) => RulerEdit::Move(i, d.pos),+ Grab::New => RulerEdit::Add(d.pos),+ Grab::Indent("firstLineIndent") => RulerEdit::Indent("firstLineIndent", d.pos - r.left),+ Grab::Indent("rightIndent") => RulerEdit::Indent("rightIndent", (width_pt - d.pos).max(0.0)),+ Grab::Indent(k) => RulerEdit::Indent(k, d.pos),+ });+ }+ if resp.clicked()+ && let Some(p) = resp.interact_pointer_pos()+ {+ match hit(p) {+ Some(Grab::Tab(i)) => edit = Some(RulerEdit::Select(i)),+ Some(Grab::New) => edit = Some(RulerEdit::Add(to_pt(p.x).clamp(0.0, width_pt.max(0.0)))),+ _ => {}+ }+ }+ ui.data_mut(|d| match drag {+ Some(v) => {+ d.insert_temp(key, v);+ }+ None => d.remove::<Drag>(key),+ });++ // Paint: the strip, the scale with ticks in document units, the area past the column.+ let p = ui.painter_at(rect.expand(1.0));+ p.rect_filled(strip, 0.0, t.panel_darker);+ p.rect_filled(bar, 0.0, t.ruler);+ let end = to_x(width_pt);+ if end < rect.max.x {+ p.rect_filled(Rect::from_min_max(pos2(end, rect.min.y), rect.max), 0.0, t.input.gamma_multiply(0.7));+ }+ p.line_segment([pos2(x0, strip.min.y), pos2(x0, rect.max.y)], Stroke::new(1.0, t.ruler_tick));+ p.line_segment([pos2(end, strip.min.y), pos2(end, rect.max.y)], Stroke::new(1.0, t.ruler_tick));+ let (major, sub) = r.unit.ruler_ticks(scale as f64);+ let font = egui::FontId::proportional(9.0);+ let tick = Stroke::new(1.0, t.ruler_tick);+ let mut k = 0u32;+ while major > 0.0 && k < 2000 {+ let m = k as f64 * major;+ if to_x(m) > rect.max.x {+ break;+ }+ for s in 0..sub.max(1) {+ let x = to_x(m + major * s as f64 / sub.max(1) as f64);+ if x > rect.max.x {+ break;+ }+ let len = if s == 0 {+ bar.height() - 4.0+ } else if sub % 2 == 0 && s == sub / 2 {+ 7.0+ } else {+ 4.0+ };+ p.line_segment([pos2(x, bar.max.y - len), pos2(x, bar.max.y)], tick);+ }+ p.text(pos2(to_x(m) + 2.0, bar.min.y + 1.0), egui::Align2::LEFT_TOP, crate::canvas::fmt_tick(r.unit.from_pt(m)), font.clone(), t.ruler_text);+ k += 1;+ }+ // Indent markers (a dragged one follows the pointer; the first line follows the left indent).+ let (mut left, mut first_abs, mut right_x) = (r.left, r.left + r.first, width_pt - r.right);+ if let Some(Drag { grab: Grab::Indent(which), pos, .. }) = drag {+ match which {+ "leftIndent" => {+ first_abs = pos + r.first;+ left = pos;+ }+ "firstLineIndent" => first_abs = pos,+ _ => right_x = pos,+ }+ }+ let ink = t.text_strong;+ let tri = |x: f32, down: bool, c: Color32| {+ let (y0, y1) = if down { (bar.min.y, bar.min.y + 7.0) } else { (bar.max.y, bar.max.y - 7.0) };+ p.add(egui::Shape::convex_polygon(vec![pos2(x - 5.0, y0), pos2(x + 5.0, y0), pos2(x, y1)], c, Stroke::new(1.0, t.panel_darker)));+ };+ tri(to_x(first_abs), true, ink);+ tri(to_x(left), false, ink);+ tri(to_x(right_x), false, ink);+ // Tab stops.+ for (i, s) in r.tabs.iter().enumerate() {+ let dragging = drag.filter(|d| d.grab == Grab::Tab(i));+ if dragging.is_some_and(|d| d.off) {+ continue;+ }+ let x = to_x(dragging.map_or(s.position, |d| d.pos));+ let mark = Rect::from_center_size(pos2(x, strip.max.y - 6.0), vec2(14.0, 14.0));+ if r.selected == Some(i) {+ p.rect_filled(mark.expand(1.0), 2.0, t.accent);+ }+ crate::icons::paint(&p, mark, tab_icon(s.align), ink);+ }+ if let Some(d) = drag.filter(|d| matches!(d.grab, Grab::New)) {+ crate::icons::paint(&p, Rect::from_center_size(pos2(to_x(d.pos), strip.max.y - 6.0), vec2(16.0, 16.0)), "tab-left", t.accent_strong);+ }+ if let Some(d) = drag.filter(|d| !d.off) {+ p.line_segment([pos2(to_x(d.pos), strip.min.y), pos2(to_x(d.pos), rect.max.y)], Stroke::new(1.0, t.accent));+ }+ edit+}++/// The four alignment buttons; returns the one clicked.+pub(crate) fn align_buttons(ui: &mut Ui, lang: &str, current: TabAlign) -> Option<TabAlign> {+ let mut out = None;+ for (a, tip) in ALIGNS {+ if crate::icons::button(ui, tab_icon(a), 22.0, a == current, crate::i18n::tr(lang, tip)).clicked() {+ out = Some(a);+ }+ }+ out+}++/// A one-line text field that commits on Enter or when it loses focus.+pub(crate) fn text_commit(ui: &mut Ui, id: &str, current: &str, width: f32, enabled: bool) -> Option<String> {+ let tid = ui.id().with(("tabs_text", id));+ let focused = ui.memory(|m| m.has_focus(tid));+ let mut buf: String = if focused { ui.data(|d| d.get_temp(tid)).unwrap_or_else(|| current.to_string()) } else { current.to_string() };+ let r = ui.add_enabled(enabled, egui::TextEdit::singleline(&mut buf).id(tid).desired_width(width));+ ui.data_mut(|d| d.insert_temp(tid, buf.clone()));+ (r.lost_focus() && buf != current).then_some(buf)+}++/// The text column of the selection on screen: (top-left, top-right, top), when the+/// frame's text runs left to right unrotated in the view.+fn column_on_screen(app: &DesignApp, frame: u64, col: [f64; 4]) -> Option<(Pos2, Pos2, f32)> {+ let st = app.session.active()?;+ let v = app.view()?;+ let rect = app.canvas_rect?;+ let xf = crate::canvas::Xf::new(rect, v);+ let id = designcraft_doc::ItemId(frame);+ let loc = st.doc.find(id)?;+ let it = st.doc.item_at(&loc)?;+ let story = it.text_frame().and_then(|tf| st.doc.story(tf.story))?;+ if story.vertical {+ return None;+ }+ let layout = designcraft_tools::CanvasLayout::new(&st.doc, st.editing_parents);+ let m = layout.xf(loc.spread) * st.doc.parent_xf(&loc) * st.doc.text_xf(it);+ let a = xf.to_screen(m * Point::new(col[0], col[1]));+ let b = xf.to_screen(m * Point::new(col[2], col[1]));+ let c = xf.to_screen(m * Point::new(col[0], col[3]));+ // Only when the column runs straight across the screen.+ if (a.y - b.y).abs() > 0.5 || b.x <= a.x || (c.x - a.x).abs() > 0.5 {+ return None;+ }+ Some((a, b, a.y))+}++/// The Tabs panel.+pub fn show(app: &mut DesignApp, ui: &mut Ui) {+ let lang = app.ui.language.clone();+ let tr = |s: &'static str| crate::i18n::tr(&lang, s);+ let Ok(v) = app.session.execute("type.tabs.get", &json!({})) else {+ crate::rtl::label(ui, tr("Select text or a text frame."));+ return;+ };+ let tabs: Vec<TabStop> = serde_json::from_value(v["tabs"].clone()).unwrap_or_default();+ let num = |k: &str| v[k].as_f64().filter(|x| x.is_finite()).unwrap_or(0.0);+ let (left, first, right, width) = (num("leftIndent"), num("firstLineIndent"), num("rightIndent"), num("width"));+ let unit = app.session.active().map(|d| d.doc.settings.horizontal_units).unwrap_or(Unit::Picas);+ let column = v["frame"].as_u64().zip(v["column"].as_array().and_then(|a| {+ let f = |i: usize| a.get(i).and_then(Value::as_f64);+ Some([f(0)?, f(1)?, f(2)?, f(3)?])+ }));+ let screen = column.and_then(|(f, c)| column_on_screen(app, f, c));+ let zoom = app.view().map(|v| v.zoom as f32);++ // Panel position above the frame: on request (the magnet, or opening the panel).+ let win = ui.ctx().memory(|m| m.area_rect(egui::Id::new(("floating_panel", "tabs"))));+ let state = &mut app.ui.tabs_panel;+ if state.selected.is_some_and(|i| i >= tabs.len()) {+ state.selected = None;+ }+ if state.snap_request > 0 {+ state.snap_request -= 1;+ if let (Some((a, b, top)), Some(z)) = (screen, zoom) {+ let h = win.map_or(90.0, |r| r.height());+ // The window's inner margin (10) plus the ruler's inset put position 0 over the column+ // edge; the panel spans at least the column.+ let width = (b.x - a.x + 2.0 * PAD + 20.0).max(MIN_WIDTH);+ state.place = Some((pos2(a.x - 10.0 - PAD, (top - h - 8.0).max(30.0)), width));+ state.snap = Some(z);+ ui.ctx().request_repaint();+ }+ }+ if state.snap.is_some() && state.snap != zoom {+ state.snap = None;+ }+ let selected = state.selected;+ let sel = selected.and_then(|i| tabs.get(i));+ let current_align = sel.map_or(state.align, |s| s.align);+ let mut cmds: Vec<(&'static str, Value)> = Vec::new();+ let mut snap_now = false;++ ui.horizontal_wrapped(|ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ if let Some(a) = align_buttons(ui, &lang, current_align) {+ app.ui.tabs_panel.align = a;+ if let Some(i) = selected {+ cmds.push(("type.tabs.change", json!({"index": i, "align": a})));+ }+ }+ ui.add_space(6.0);+ crate::rtl::label(ui, tr("X:"));+ if let Some(x) = crate::widgets::measure(ui, "tabs_x", sel.map(|s| s.position), unit, 72.0) {+ match selected {+ Some(i) => cmds.push(("type.tabs.move", json!({"index": i, "position": x}))),+ None => cmds.push(("type.tabs.add", json!({"position": x, "align": current_align}))),+ }+ }+ crate::rtl::label(ui, tr("Leader:"));+ if let (Some(l), Some(i)) = (text_commit(ui, "leader", sel.map_or("", |s| s.leader.as_str()), 36.0, sel.is_some()), selected) {+ cmds.push(("type.tabs.change", json!({"index": i, "leader": l})));+ }+ crate::rtl::label(ui, tr("Align On:"));+ let char_tab = sel.is_some_and(|s| s.align == TabAlign::Char);+ if let (Some(c), Some(i)) = (text_commit(ui, "alignOn", sel.map_or("", |s| s.align_on.as_str()), 18.0, char_tab), selected) {+ cmds.push(("type.tabs.change", json!({"index": i, "alignOn": c})));+ }+ ui.add_space(6.0);+ let snap_tip = tr("Position panel above text frame");+ if ui.add_enabled_ui(screen.is_some(), |ui| crate::icons::button(ui, "tab-snap", 22.0, false, snap_tip)).inner.clicked() {+ snap_now = true;+ }+ crate::menus::menu_button(ui, "☰", |ui| {+ for (label, id, needs_stop) in+ [("Clear All", "type.tabs.clear", false), ("Delete Tab", "type.tabs.remove", true), ("Repeat Tab", "type.tabs.repeat", true)]+ {+ if ui.add_enabled(!needs_stop || selected.is_some(), egui::Button::new(crate::rtl::widget(ui, tr(label)))).clicked() {+ cmds.push((id, selected.map_or(json!({}), |i| json!({"index": i}))));+ ui.close();+ }+ }+ if ui.button(crate::rtl::widget(ui, tr("Reset Indents"))).clicked() {+ cmds.push(("type.para", json!({"attrs": {"leftIndent": 0, "firstLineIndent": 0, "rightIndent": 0}})));+ ui.close();+ }+ });+ });+ ui.add_space(4.0);+ let r = Ruler { tabs: &tabs, left, first, right, width, unit, selected, scale: app.ui.tabs_panel.snap };+ match ruler(ui, "panel", &r) {+ Some(RulerEdit::Select(i)) => app.ui.tabs_panel.selected = Some(i),+ Some(RulerEdit::Add(x)) => cmds.push(("type.tabs.add", json!({"position": x, "align": app.ui.tabs_panel.align}))),+ Some(RulerEdit::Move(i, x)) => cmds.push(("type.tabs.move", json!({"index": i, "position": x}))),+ Some(RulerEdit::Remove(i)) => cmds.push(("type.tabs.remove", json!({"index": i}))),+ Some(RulerEdit::Indent(k, x)) => cmds.push(("type.para", json!({"attrs": {k: x}}))),+ None => {}+ }+ if snap_now {+ app.ui.tabs_panel.snap_request = 2;+ ui.ctx().request_repaint();+ }+ for (id, p) in cmds {+ match app.run(id, p) {+ Ok(r) if id.starts_with("type.tabs.") => app.ui.tabs_panel.selected = r["index"].as_u64().map(|i| i as usize),+ _ => {}+ }+ }+}++#[cfg(test)]+mod tests {+ use egui_kittest::kittest::Queryable;+ use serde_json::json;++ use crate::test_window;++ fn stops(app: &mut crate::DesignApp) -> Vec<f64> {+ let v = app.session.execute("type.tabs.get", &json!({})).unwrap();+ v["tabs"].as_array().unwrap().iter().map(|t| t["position"].as_f64().unwrap()).collect()+ }++ #[test]+ fn shortcut_opens_the_panel_and_a_click_on_the_ruler_adds_a_stop() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 372, 300], "content": "text", "text": "Name\tPrice"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ let mut h = test_window::open(app, egui::vec2(1400.0, 900.0));+ h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::T);+ h.run_steps(6);+ assert!(h.state().app.ui.floating.iter().any(|(p, _)| p == "tabs"), "Cmd+Shift+T floats the Tabs panel");+ // The ruler's strip lies just below the row of alignment buttons.+ let b = h.get_by_label("Left-aligned tab").rect();+ test_window::click_at(&mut h, egui::pos2(b.min.x + super::PAD + 60.0, b.max.y + 14.0));+ let got = stops(&mut h.state_mut().app);+ assert_eq!(got.len(), 1, "one stop added");+ assert!(got[0] > 0.0);+ assert_eq!(h.state().app.ui.tabs_panel.selected, Some(0));+ // The menu item (Type › Tabs) closes it again.+ h.state_mut().app.run("app.tabsPanel", json!({})).unwrap();+ assert!(!h.state().app.ui.floating.iter().any(|(p, _)| p == "tabs"));+ }+}