DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
refactor(ui): reduce cognitive complexity in swatches, properties, canvas, lib (Sonar S3776) (#1727)
Dylan M. Taylorcf45e3354585
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 331b83838..e2b066fb1 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2451,6 +2451,26 @@ fn scrollbar_rects(outer: Rect, screen: Rect, content: Rect, vertical: bool) ->}}+/// How far a scrollbar interaction pans the view along its axis: a thumb drag follows the pointer,+/// a click on the track beside the thumb pages by one view.+fn scrollbar_move(resp: &egui::Response, grabbed: bool, vertical: bool, thumb: Rect, page: f32, k: f32) -> f32 {+ if grabbed {+ let d = resp.drag_delta();+ return -(if vertical { d.y } else { d.x }) * k;+ }+ if resp.clicked()+ && let Some(p) = resp.interact_pointer_pos()+ {+ let (p, a, b) = if vertical { (p.y, thumb.min.y, thumb.max.y) } else { (p.x, thumb.min.x, thumb.max.x) };+ if p < a {+ return page;+ } else if p > b {+ return -page;+ }+ }+ 0.0+}+/// The view's scrollbars, on the right and bottom edges of `outer`: they span the pasteboard;/// dragging a thumb pans, clicking the track pages by one view.fn scrollbars(app: &mut DesignApp, ui: &mut egui::Ui, outer: Rect, screen: Rect, rect: Rect, t: &Tokens) {@@ -2476,21 +2496,8 @@ fn scrollbars(app: &mut DesignApp, ui: &mut egui::Ui, outer: Rect, screen: Rect,if !resp.dragged() {ui.data_mut(|d| d.remove::<bool>(grab_id));}- let along = |p: egui::Vec2| if vertical { p.y } else { p.x };- let page = along(screen.size());- let mut moved = 0.0;- if grabbed {- moved = -along(resp.drag_delta()) * k;- } else if resp.clicked()- && let Some(p) = resp.interact_pointer_pos()- {- let (p, a, b) = if vertical { (p.y, thumb.min.y, thumb.max.y) } else { (p.x, thumb.min.x, thumb.max.x) };- if p < a {- moved = page;- } else if p > b {- moved = -page;- }- }+ let page = if vertical { screen.size().y } else { screen.size().x };+ let moved = scrollbar_move(&resp, grabbed, vertical, thumb, page, k);if moved != 0.0 && moved.is_finite() {pan(app, &xf, if vertical { vec2(0.0, moved) } else { vec2(moved, 0.0) });}@@ -3686,6 +3693,37 @@ fn guide_at(app: &DesignApp, xf: &Xf, p: Pos2) -> Option<(designcraft_doc::SpreaNone}+/// A primary press at `o` on a ruler starts a new guide; on a guide it selects and grabs it.+fn begin_guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect, xf: &Xf, o: Pos2) -> Option<GuideDrag> {+ let full = resp.rect;+ if full.contains(o) && !rect.contains(o) {+ // In a ruler (not the corner).+ let orientation = if o.y < rect.min.y && o.x >= rect.min.x {+ Some(designcraft_doc::Orientation::Horizontal)+ } else if o.x < rect.min.x && o.y >= rect.min.y {+ Some(designcraft_doc::Orientation::Vertical)+ } else {+ None+ };+ if let Some(orientation) = orientation {+ return Some(GuideDrag { orientation, from: None, at: Some(o), mods: egui::Modifiers::NONE });+ }+ } else if rect.contains(o)+ && matches!(app.session.tool_id(), "selection" | "directSelection")+ && let Some((r, pi, gi, orientation)) = guide_at(app, xf, o)+ {+ let shift = ui.input(|i| i.modifiers.shift);+ // A press on a guide selects it (Shift: on release, as a click adds or removes it).+ let selected = app.session.active().is_some_and(|st| st.selection.guides.contains(&GuideSel { spread: r, page: pi, index: gi }));+ if !shift && !selected {+ let _ = app.run("guide.select", json!({"spread": r, "page": pi, "index": gi}));+ }+ ui.data_mut(|d| d.insert_temp(egui::Id::unique(GUIDE_PRESS), GuidePress { origin: o, shift }));+ return Some(GuideDrag { orientation, from: Some((r, pi, gi)), at: Some(o), mods: egui::Modifiers::NONE });+ }+ None+}+/// Ruler guides: drag one out of a ruler, drag an existing one (Selection tools) to move it, drop/// it back on a ruler to delete it. A press near an unlocked guide takes it even over an object:/// the guide is selected and the object is not. Returns true from the press to the release, so@@ -3697,32 +3735,7 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, reclet mut drag: Option<GuideDrag> = ui.data(|d| d.get_temp(id));if drag.is_none() && pressed && resp.hovered() && app.ui.guides && !app.ui.guides_locked {let Some(o) = origin else { return false };- let full = resp.rect;- if full.contains(o) && !rect.contains(o) {- // In a ruler (not the corner).- let orientation = if o.y < rect.min.y && o.x >= rect.min.x {- Some(designcraft_doc::Orientation::Horizontal)- } else if o.x < rect.min.x && o.y >= rect.min.y {- Some(designcraft_doc::Orientation::Vertical)- } else {- None- };- if let Some(orientation) = orientation {- drag = Some(GuideDrag { orientation, from: None, at: Some(o), mods: egui::Modifiers::NONE });- }- } else if rect.contains(o)- && matches!(app.session.tool_id(), "selection" | "directSelection")- && let Some((r, pi, gi, orientation)) = guide_at(app, xf, o)- {- let shift = ui.input(|i| i.modifiers.shift);- // A press on a guide selects it (Shift: on release, as a click adds or removes it).- let selected = app.session.active().is_some_and(|st| st.selection.guides.contains(&GuideSel { spread: r, page: pi, index: gi }));- if !shift && !selected {- let _ = app.run("guide.select", json!({"spread": r, "page": pi, "index": gi}));- }- ui.data_mut(|d| d.insert_temp(egui::Id::unique(GUIDE_PRESS), GuidePress { origin: o, shift }));- drag = Some(GuideDrag { orientation, from: Some((r, pi, gi)), at: Some(o), mods: egui::Modifiers::NONE });- }+ drag = begin_guide_drag(app, ui, resp, rect, xf, o);}let Some(mut g) = drag else { return false };if let Some(p) = latest {diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex f3571d38b..0117a67b4 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1368,6 +1368,50 @@ impl DesignApp {self.ui.flyout = None;}+ /// First frame only: load the saved colour profiles and make the saved Color Settings active.+ fn apply_saved_color_settings(&mut self) {+ if self.color_applied {+ return;+ }+ self.color_applied = true;+ for path in self.ui.color_profiles.clone() {+ if let Err(e) = self.session.execute("color.loadProfile", &json!({"path": path})) {+ log::warn!("Color Settings: {e}");+ self.status_error("Color Settings", e);+ }+ }+ if let Some(cs) = self.ui.color_settings.clone() {+ let known = cs.with_known_profiles();+ for (saved, used) in [(&cs.rgb, &known.rgb), (&cs.cmyk, &known.cmyk)] {+ if saved != used {+ let e = format!("saved profile {saved} is not available; using {used}");+ log::warn!("Color Settings: {e}");+ self.status_error("Color Settings", e);+ }+ }+ let _ = designcraft_color::cms::set_active(&known);+ }+ }++ /// Install the UI fonts on the first frame, and again when the language or the system fonts change.+ fn update_fonts(&mut self, ctx: &egui::Context) {+ if !self.styled {+ // The UI scale is a preference (applied above); egui's own Cmd+Plus/Minus/0 would rescale the+ // whole window instead of the canvas, only to be reset next frame.+ ctx.options_mut(|o| o.zoom_with_keyboard = false);+ self.fonts_system = theme::install_fonts(ctx, &self.ui.language);+ self.fonts_lang = self.ui.language.clone();+ self.styled = true;+ self.restyle = true;+ } else {+ if self.fonts_lang != self.ui.language || (!self.fonts_system && theme::system_fonts_ready()) {+ self.fonts_system = theme::install_fonts(ctx, &self.ui.language);+ self.fonts_lang = self.ui.language.clone();+ }+ self.fonts_ready = true;+ }+ }+/// Queue and deadline work, run once per app callback.////// `logic_tick` runs on every call (a first pass, a later discarded pass, or a hidden@@ -1418,45 +1462,12 @@ impl DesignApp {self.egui_ctx = Some(ctx.clone());}self.window_maximized = ctx.input(|i| i.viewport().maximized.unwrap_or(false));- if !self.color_applied {- self.color_applied = true;- for path in self.ui.color_profiles.clone() {- if let Err(e) = self.session.execute("color.loadProfile", &json!({"path": path})) {- log::warn!("Color Settings: {e}");- self.status_error("Color Settings", e);- }- }- if let Some(cs) = self.ui.color_settings.clone() {- let known = cs.with_known_profiles();- for (saved, used) in [(&cs.rgb, &known.rgb), (&cs.cmyk, &known.cmyk)] {- if saved != used {- let e = format!("saved profile {saved} is not available; using {used}");- log::warn!("Color Settings: {e}");- self.status_error("Color Settings", e);- }- }- let _ = designcraft_color::cms::set_active(&known);- }- }+ self.apply_saved_color_settings();let scale = self.ui.ui_scale.clamp(0.5, 3.0);if (ctx.zoom_factor() - scale).abs() > 1e-3 {ctx.set_zoom_factor(scale);}- if !self.styled {- // The UI scale is a preference (applied above); egui's own Cmd+Plus/Minus/0 would rescale the- // whole window instead of the canvas, only to be reset next frame.- ctx.options_mut(|o| o.zoom_with_keyboard = false);- self.fonts_system = theme::install_fonts(ctx, &self.ui.language);- self.fonts_lang = self.ui.language.clone();- self.styled = true;- self.restyle = true;- } else {- if self.fonts_lang != self.ui.language || (!self.fonts_system && theme::system_fonts_ready()) {- self.fonts_system = theme::install_fonts(ctx, &self.ui.language);- self.fonts_lang = self.ui.language.clone();- }- self.fonts_ready = true;- }+ self.update_fonts(ctx);if !self.fonts_system {// The font scan runs in the background: look again shortly.ctx.request_repaint_after(std::time::Duration::from_millis(250));diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rsindex 2084ab128..2b5ef2f69 100644--- a/crates/ui-egui/src/panels/properties.rs+++ b/crates/ui-egui/src/panels/properties.rs@@ -211,6 +211,35 @@ pub(crate) fn preset_name(w: f64, h: f64) -> &'static str {PAGE_PRESETS.iter().find(|p| (p.1 - a).abs() < 0.6 && (p.2 - b).abs() < 0.6).map(|p| p.0).unwrap_or("Custom")}+/// The preset dropdown and orientation toggles for one page; the new (width, height) when one changed.+fn page_preset_row(ui: &mut Ui, lang: &str, w: f64, h: f64) -> Option<(f64, f64)> {+ let landscape = w > h;+ let b = block(ui, FIELD_H);+ let mut size = None;+ place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| {+ let resp = dropdown(ui, crate::i18n::tr(lang, preset_name(w, h)), 93.0);+ egui::Popup::menu(&resp).show(|ui| {+ ui.set_min_width(140.0);+ for p in PAGE_PRESETS {+ if ui.selectable_label(preset_name(w, h) == p.0, crate::i18n::tr(lang, p.0)).clicked() {+ size = Some(if landscape { (p.2, p.1) } else { (p.1, p.2) });+ ui.close();+ }+ }+ });+ });+ place(ui, sub(b, 126.0, 0.0, 52.0, FIELD_H), |ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ if icon_toggle(ui, "orient-portrait", !landscape, crate::i18n::tr(lang, "Portrait")).clicked() && landscape {+ size = Some((h, w));+ }+ if icon_toggle(ui, "orient-landscape", landscape, crate::i18n::tr(lang, "Landscape")).clicked() && !landscape {+ size = Some((h, w));+ }+ });+ size+}+/// Properties with the Page tool (Properties › Edit Page), as InDesign's: a "Page" band with Back,/// Page Size for this page alone (which page, preset, orientation, W/H), Margins and Columns and/// Quick Actions. Back returns to the Selection tool and the document's properties.@@ -257,30 +286,7 @@ fn page_sections(app: &mut DesignApp, ui: &mut Ui, page: usize) {ui.add_space(3.0);// Preset and orientation: this page alone.let (w, h) = (pg.width, pg.height);- let landscape = w > h;- let b = block(ui, FIELD_H);- let mut size = None;- place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| {- let resp = dropdown(ui, crate::i18n::tr(&lang, preset_name(w, h)), 93.0);- egui::Popup::menu(&resp).show(|ui| {- ui.set_min_width(140.0);- for p in PAGE_PRESETS {- if ui.selectable_label(preset_name(w, h) == p.0, crate::i18n::tr(&lang, p.0)).clicked() {- size = Some(if landscape { (p.2, p.1) } else { (p.1, p.2) });- ui.close();- }- }- });- });- place(ui, sub(b, 126.0, 0.0, 52.0, FIELD_H), |ui| {- ui.spacing_mut().item_spacing.x = 4.0;- if icon_toggle(ui, "orient-portrait", !landscape, crate::i18n::tr(&lang, "Portrait")).clicked() && landscape {- size = Some((h, w));- }- if icon_toggle(ui, "orient-landscape", landscape, crate::i18n::tr(&lang, "Landscape")).clicked() && !landscape {- size = Some((h, w));- }- });+ let mut size = page_preset_row(ui, &lang, w, h);ui.add_space(3.0);let b = block(ui, 2.0 * FIELD_H + 5.0);for (row, (label, v, key)) in [("W:", w, "width"), ("H:", h, "height")].into_iter().enumerate() {@@ -4171,21 +4177,16 @@ fn selected_container(app: &DesignApp) -> Option<(designcraft_doc::Item, Vec<desSome((it, kids))}-/// The alignment grid: 3 × 3 cells (one column or row of three when a space justification spreads-/// the objects along the main axis); the chosen cell shows the direction's arrow.-fn flex_grid(ui: &mut Ui, r: Rect, f: Option<&designcraft_doc::FlexLayout>) -> Option<u8> {+/// The chosen (column, row) of the Flex Layout alignment grid, and whether a space justification+/// leaves only one axis (`Some(true)` for a row layout).+fn flex_grid_choice(f: Option<&designcraft_doc::FlexLayout>) -> ((usize, usize), Option<bool>) {use designcraft_doc::{FlexAlign, FlexJustify};- let t = Tokens::get(ui.ctx());- let resp = ui.interact(r, ui.scope_id().with("flex_grid"), Sense::click());- ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);- let cell = r.width() / 3.0;let pos = |a: FlexAlign| match a {FlexAlign::Start => 0,FlexAlign::Center => 1,FlexAlign::End => 2,};- // The chosen (column, row), and whether a space justification leaves only one axis.- let (chosen, spread_row) = match f {+ match f {Some(f) => {let main = match f.justify {FlexJustify::Center => 1,@@ -4197,7 +4198,17 @@ fn flex_grid(ui: &mut Ui, r: Rect, f: Option<&designcraft_doc::FlexLayout>) -> O(if f.direction.is_row() { (main, cross) } else { (cross, main) }, f.justify.distributes().then_some(f.direction.is_row()))}None => ((0, 0), None),- };+ }+}++/// The alignment grid: 3 × 3 cells (one column or row of three when a space justification spreads+/// the objects along the main axis); the chosen cell shows the direction's arrow.+fn flex_grid(ui: &mut Ui, r: Rect, f: Option<&designcraft_doc::FlexLayout>) -> Option<u8> {+ let t = Tokens::get(ui.ctx());+ let resp = ui.interact(r, ui.scope_id().with("flex_grid"), Sense::click());+ ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);+ let cell = r.width() / 3.0;+ let (chosen, spread_row) = flex_grid_choice(f);let mut picked = None;for row in 0..3usize {for col in 0..3usize {diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rsindex 560fd0966..43eee1d32 100644--- a/crates/ui-egui/src/panels/swatches.rs+++ b/crates/ui-egui/src/panels/swatches.rs@@ -242,6 +242,33 @@ fn folder_button(ui: &mut egui::Ui, tip: &str) -> egui::Response {})}+/// The swatch's chip following the pointer while the row is dragged.+fn paint_drag_chip(ui: &egui::Ui, doc: &designcraft_doc::Document, name: &str, p: egui::Pos2) {+ let t = Tokens::get(ui.ctx());+ let (c, g) = crate::widgets::swatch_colors(doc, name, 1.0);+ let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("swatch_drag")));+ let chip = egui::Rect::from_min_size(p + vec2(8.0, 8.0), vec2(16.0, 16.0));+ crate::widgets::paint_chip(&painter, chip, c, g);+ painter.rect_stroke(chip, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+}++/// The type indicator shown at the right of a swatch row: colour mode (spot dot), gradient or tint.+fn swatch_kind_label(lang: &str, value: &SwatchValue) -> String {+ match value {+ SwatchValue::Color { color, color_type } => {+ let m = match color {+ designcraft_color::Color::Cmyk { .. } => "CMYK",+ designcraft_color::Color::Rgb { .. } => "RGB",+ designcraft_color::Color::Gray { .. } => crate::i18n::tr(lang, "Gray"),+ };+ format!("{}{}", if *color_type == ColorType::Spot { "● " } else { "" }, m)+ }+ SwatchValue::Gradient { .. } => "Gradient".into(),+ SwatchValue::Tint { tint, .. } => format!("{:.0}%", tint * 100.0),+ _ => String::new(),+ }+}+/// One Swatches panel row: chip, name, type; click applies it to the fill or stroke in front of/// the proxy (of the frames or their text, see [`super::colors_affect_text`]), the context menu/// to the stroke, colour groups and delete.@@ -261,12 +288,7 @@ fn swatch_row(if resp.dragged()&& let Some(p) = ui.ctx().pointer_interact_pos(){- // The swatch's chip follows the pointer.- let (c, g) = crate::widgets::swatch_colors(doc, &sw.name, 1.0);- let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("swatch_drag")));- let chip = egui::Rect::from_min_size(p + vec2(8.0, 8.0), vec2(16.0, 16.0));- crate::widgets::paint_chip(&painter, chip, c, g);- painter.rect_stroke(chip, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+ paint_drag_chip(ui, doc, &sw.name, p);}if fill_cur == Some(sw.name.as_str()) {ui.painter().rect_filled(row, 0.0, t.row_selected);@@ -278,19 +300,7 @@ fn swatch_row(crate::widgets::paint_chip(ui.painter(), chip, c, g);ui.painter().text(row.min + vec2(28.0 + indent, 11.0), egui::Align2::LEFT_CENTER, &sw.name, egui::FontId::proportional(12.5), t.text);// Type indicators: spot dot / process square, colour mode.- let kind = match &sw.value {- SwatchValue::Color { color, color_type } => {- let m = match color {- designcraft_color::Color::Cmyk { .. } => "CMYK",- designcraft_color::Color::Rgb { .. } => "RGB",- designcraft_color::Color::Gray { .. } => crate::i18n::tr(&app.ui.language, "Gray"),- };- format!("{}{}", if *color_type == ColorType::Spot { "● " } else { "" }, m)- }- SwatchValue::Gradient { .. } => "Gradient".into(),- SwatchValue::Tint { tint, .. } => format!("{:.0}%", tint * 100.0),- _ => String::new(),- };+ let kind = swatch_kind_label(&app.ui.language, &sw.value);if sw.locked {icons::paint(ui.painter(), egui::Rect::from_min_size(egui::pos2(row.max.x - 64.0, row.min.y + 4.0), vec2(13.0, 13.0)), "lock", t.text_dim);}