diff --git a/Cargo.lock b/Cargo.lock index 96a9f4e107..d941f298f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5450,7 +5450,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "emath", @@ -5506,7 +5506,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5541,7 +5541,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "accesskit", "ahash", @@ -5560,7 +5560,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5579,7 +5579,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5599,7 +5599,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "egui", @@ -5612,7 +5612,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "eframe", "egui", @@ -5689,7 +5689,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", ] @@ -5762,7 +5762,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5788,7 +5788,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[package]] name = "equator" @@ -15119,19 +15119,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" diff --git a/Cargo.toml b/Cargo.toml index 8afdc685c5..44b4079a65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -310,20 +310,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -emath = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index acd621c1e8..3890d79811 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"; +pub const REV: &str = "f5025284445ea19c35f746d96fc0b75468b3f560"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 1521d943b7..1fcd062826 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -14,16 +14,18 @@ use craft_behavior::{Codec, EditEvent, IconId, Mixed, NotAValue, PartKey, Sense, use craft_behavior::{HitLevel, HitPriority, NavMove, Preview}; use craft_font_catalog::Catalog; use craft_host::Section; +use craft_theme::variant::Tone; use craft_ui::buttons::{ControlPlace, IconButton}; use craft_ui::contract::{ Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, - Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, + Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, }; use craft_ui::list::{ThumbSize, TrailingPart}; use craft_ui::primitives::{IconSpec, TextKey, TextOptions, TextRun}; use craft_ui::runtime::env::{EnvView, Label}; use craft_ui::runtime::memory::StageAccess; -use craft_ui::text::{Adornment, place, reserve}; +use craft_ui::style::{ComponentStyle, Metrics, Stateful, States, StyleColor, StyleCx, SurfaceLook}; +use craft_ui::text::{Adornment, FieldStyle, place, reserve}; use egui::{Rect, Response, Vec2}; use serde::{Deserialize, Serialize}; @@ -589,18 +591,35 @@ impl<'a> FontPicker<'a> { } } +/// The style of [`FontPicker`]: the field look and the colour of the missing-font warning icon. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct FontPickerStyle { + #[style(surface)] + surface: SurfaceLook, + #[style(metrics)] + metrics: Metrics, + /// The field look the adornments are placed by; `surface` and `metrics` are its own. + field: FieldStyle, + /// The ink of the missing-font warning icon (`status.warn.fg`), dimmed to `text.disabled` while disabled. + warning: Stateful, +} + impl Component for FontPicker<'_> { const ROLE: Role = Role::COMBO_BOX; const INPUT: Input = Input::Text; const KEYS: craft_ui::runtime::focus::KeyUse = craft_ui::runtime::focus::KeyUse::of(Input::Text).with_moves(); - type Style = craft_ui::text::FieldStyle; + type Style = FontPickerStyle; type Output = FontPickerOutput; /// A field; in a ribbon (`ControlPlace::Ribbon`) held at the small field length (`size.length.field.sm`), as a /// ribbon's font box is: wide enough for a family name and its menu arrow, the same width whichever it shows. - fn style(cx: &craft_ui::style::StyleCx<'_>, _: FontPickerStyleKey) -> craft_ui::text::FieldStyle { - let field = craft_ui::text::FieldStyle::at(cx); - if cx.env::() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field } + fn style(cx: &StyleCx<'_>, _: FontPickerStyleKey) -> FontPickerStyle { + let field = FieldStyle::at(cx); + let field = if cx.env::() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field }; + let warn = cx.tone(Tone::Warn); + let off = cx.color(cx.tokens.color.text.disabled); + FontPickerStyle { surface: cx.field(), metrics: field.metrics(), field, warning: Stateful::new(warn).off(States::new(warn, warn, warn, off)) } } /// The wheel steps the family through the list. @@ -620,7 +639,7 @@ impl Component for FontPicker<'_> { let widest = if ribbon { Vec2::new(cx.tokens.size.length.short, widest.y) } else { widest }; let name = cx.words::().list.clone(); let note = self.missing_note(current, &cx.words::()); - Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name, note.is_some())), widest.y) + Vec2::new(widest.x + reserve(&cx.style.field, &[], &Self::trailing(name, note.is_some())), widest.y) } fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { @@ -628,7 +647,7 @@ impl Component for FontPicker<'_> { let family = cx.value().cloned().unwrap_or_default(); let note = self.missing_note(&family, &cx.words::()); let trailing = Self::trailing(name, note.is_some()); - let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.flow.is_rtl()); + let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.flow.is_rtl()); if let (Some(note), Some(at)) = (note, placed.trailing.first()) { cx.part(WARNING, *at).tooltip(note); } @@ -708,9 +727,10 @@ impl Component for FontPicker<'_> { let family = cx.value().cloned().unwrap_or_default(); let missing = self.missing_note(&family, &cx.words::()).is_some(); let trailing = Self::trailing(name.clone(), missing); - let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.env.direction().is_rtl()); + let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.env.direction().is_rtl()); if let (true, Some(at)) = (missing, placed.trailing.first()) { - ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON))); + let color = cx.resolve(&cx.style.warning); + ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON)).color(color)); } ui.face(CHEVRON, IconButton::new(IconId::new(CHEVRON_ICON)).label(name)); } diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 8ef2bc258d..195bf3a1b0 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -400,3 +400,78 @@ fn a_picker_handed_another_catalog_at_the_same_generation_builds_its_family_data fx.frame(vec![]); assert_eq!(family_builds(&fx), 1, "the second catalog builds the data once"); } + +/// Every non-transparent vertex colour of textured meshes whose centre falls inside `rect`. +fn mesh_tints(shapes: &[egui::Shape], rect: egui::Rect, out: &mut Vec) { + for shape in shapes { + match shape { + egui::Shape::Vec(inner) => mesh_tints(inner, rect, out), + egui::Shape::Mesh(mesh) if rect.contains(mesh.calc_bounds().center()) => { + out.extend(mesh.vertices.iter().map(|vertex| vertex.color).filter(|color| color.a() > 0)); + } + _ => {} + } + } +} + +/// The painted tint colours of the missing-font warning icon in `mode`/`contrast`, enabled or disabled, together with +/// the theme's `status.warn.fg`, `text.normal` and `text.disabled` colours. +fn missing_warning_colors( + mode: craft_theme::Mode, + contrast: craft_theme::Contrast, + enabled: bool, +) -> (Vec, egui::Color32, egui::Color32, egui::Color32) { + use craft_ui::contract::Props as _; + use craft_ui::runtime::env::Env; + use egui::Color32; + use std::cell::Cell; + + let catalog = catalog_of(&[INTER_REGULAR]); + let seen = Rc::new(Cell::new((None, Color32::TRANSPARENT, Color32::TRANSPARENT, Color32::TRANSPARENT))); + let held = Rc::clone(&seen); + let mut family = "Gotham".to_owned(); + let mut fx = Fixture::new(move |ui| { + let color = |[r, g, b, a]: [u8; 4]| Color32::from_rgba_unmultiplied(r, g, b, a); + let env = Env::of(ui); + let tokens = &env.tokens.tokens().color; + let out = FontPicker::new("Font family", Bind::bound(&mut family), &catalog) + .kind(FontPickerKind::Plain) + .shown_as("Inter") + .enabled(enabled) + .show(ui); + held.set((Some(out.edit.response.id), color(tokens.status.warn.fg.0), color(tokens.text.normal.0), color(tokens.text.disabled.0))); + }); + fx.theme(mode, contrast); + fx.in_room(Room::Window); + fx.settle(); + let (id, warn_fg, text_normal, text_disabled) = seen.get(); + let picker = id.expect("the picker"); + let mark = fx.part_rect(picker, PartKey::new("missing")).expect("the field carries a mark while the family is not installed"); + let mut tints = Vec::new(); + mesh_tints(&fx.frame_shapes(), mark, &mut tints); + tints.dedup(); + (tints, warn_fg, text_normal, text_disabled) +} + +#[trial] +fn the_missing_font_warning_icon_paints_in_status_warn_fg_and_dims_when_disabled() { + use craft_theme::{Contrast, Mode}; + + for (mode, contrast) in [(Mode::Light, Contrast::Standard), (Mode::Dark, Contrast::Standard), (Mode::Dark, Contrast::High)] { + let (tints, warn_fg, text_normal, _) = missing_warning_colors(mode, contrast, true); + assert_ne!(warn_fg, text_normal, "{mode:?} {contrast:?}: warning ink differs from neutral text ink"); + assert!(!tints.is_empty(), "{mode:?} {contrast:?}: the missing-font warning icon paints"); + assert!( + tints.iter().all(|tint| *tint == warn_fg), + "{mode:?} {contrast:?}: the warning icon paints in status.warn.fg {warn_fg:?}, not {tints:?}" + ); + } + + let (tints, warn_fg, _, text_disabled) = missing_warning_colors(Mode::Dark, Contrast::Standard, false); + assert_ne!(text_disabled, warn_fg, "disabled ink differs from warning ink"); + assert!(!tints.is_empty(), "a disabled picker still paints its warning icon"); + assert!( + tints.iter().all(|tint| *tint == text_disabled), + "a disabled picker paints its warning icon in text.disabled {text_disabled:?}, not {tints:?}" + ); +} diff --git a/crates/imaging/src/ui/liquify/mod.rs b/crates/imaging/src/ui/liquify/mod.rs index 61e2304ebd..708bee7dc1 100644 --- a/crates/imaging/src/ui/liquify/mod.rs +++ b/crates/imaging/src/ui/liquify/mod.rs @@ -77,6 +77,7 @@ use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, }; +use craft_ui::layout::RowAlign; use craft_ui::layout_components::Row; use craft_ui::primitives::Checker; use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; @@ -462,7 +463,7 @@ impl LiquifyWorkspace { .opened(open) .buttons([FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]) .footer(|ui, _| { - ui.vertical_centered(|ui| { + let _ = Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| { let mut guard = this.borrow_mut(); let work: &mut LiquifyWorkspace = &mut guard; let events = Checkbox::new(Bind::given(work.preview)).label(preview_label.clone()).show(ui).events; diff --git a/crates/layers/src/ui/panel/row.rs b/crates/layers/src/ui/panel/row.rs index 1f45b557a6..4be0ab4ea4 100644 --- a/crates/layers/src/ui/panel/row.rs +++ b/crates/layers/src/ui/panel/row.rs @@ -249,7 +249,8 @@ fn layer_row<'r, T: LayerTree>(cx: &'r PanelContext<'r, T>, id: &T::Id) -> ListR let contents = cx.options.thumbnail_contents; let active = cx.selection.active.as_ref() == Some(id); - let mut eye = ToggleCell::eye(EYE, info.visible).name(named(&words.visibility, &info.name)); + // A hidden layer's eye box stays empty, also under the pointer (the reference application, photocraft#16321). + let mut eye = ToggleCell::eye(EYE, info.visible).empty_off().name(named(&words.visibility, &info.name)); if let Some(color) = info.label { eye = eye.fill(DataColor::new(paint_color(color.fill()))); } @@ -369,7 +370,7 @@ fn sub_row<'r, T: LayerTree>(cx: &'r PanelContext<'r, T>, id: &T::Id, group: Sub row = row.ink(RowInk::Dimmed); } if sub.eye_shown { - row = row.toggle(ToggleCell::eye(EYE, sub.on).name(named(&words.visibility, &sub.label))); + row = row.toggle(ToggleCell::eye(EYE, sub.on).empty_off().name(named(&words.visibility, &sub.label))); } let size = cx.options.thumbnail_size; let header_mask = group == SubRowGroup::SmartFilters && index.is_none() && sub.mask && size != ThumbSize::None; diff --git a/crates/layers/tests/it/main.rs b/crates/layers/tests/it/main.rs index cc236b5a08..36c2b8fa5b 100644 --- a/crates/layers/tests/it/main.rs +++ b/crates/layers/tests/it/main.rs @@ -3,6 +3,7 @@ pub(crate) mod blend_rows; pub(crate) mod comps; pub(crate) mod panel_drag_menu; +pub(crate) mod panel_eye; pub(crate) mod panel_filter; pub(crate) mod panel_input; pub(crate) mod panel_memo; diff --git a/crates/layers/tests/it/panel_eye.rs b/crates/layers/tests/it/panel_eye.rs new file mode 100644 index 0000000000..54d74cbf19 --- /dev/null +++ b/crates/layers/tests/it/panel_eye.rs @@ -0,0 +1,47 @@ +//! `LayersPanel` eye boxes: a hidden layer's box stays empty, also under the pointer (photocraft#16321). + +use craft_layers::ui::mock::FakeLayers; +use craft_layers::ui::panel::LayersPanel; +use craft_layers::ui::tree::{LayerInfo, LayerKind}; +use craft_ui::contract::Tracked; +use craft_ui::testing::{Fixture, pointer, trial}; +use egui::{Rect, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; + +/// A visible layer over a hidden one. +fn rig() -> Fixture { + let mut tree = FakeLayers::default(); + tree.add(None, LayerInfo::new("Shown", LayerKind::Pixel), false); + let mut hidden = LayerInfo::new("Hidden", LayerKind::Pixel); + hidden.visible = false; + tree.add(None, hidden, false); + let tree = Rc::new(RefCell::new(Tracked::new(tree))); + let mut fixture = Fixture::new(move |ui| { + let tree = tree.borrow(); + let _ = LayersPanel::new(&tree).show(ui); + }); + fixture.room(Vec2::new(420.0, 560.0)); + fixture.settle(); + fixture +} + +/// How many shapes the frame paints wholly inside the eye box `cell`: its icon, not the row's fill around it. +fn drawn_in(fixture: &mut Fixture, cell: Rect) -> usize { + fixture.frame_shapes().iter().filter(|shape| cell.contains_rect(shape.visual_bounding_rect())).count() +} + +/// The pointer over a hidden layer's eye box draws nothing there (no crossed-out eye), while a visible layer's box +/// under the pointer draws its eye. +#[trial] +fn a_hidden_layers_eye_box_stays_empty_under_the_pointer() { + let mut fixture = rig(); + let shown = fixture.by_label("Visibility Shown").unwrap_or_else(|| panic!("no eye box for Shown")).rect; + let hidden = fixture.by_label("Visibility Hidden").unwrap_or_else(|| panic!("no eye box for Hidden")).rect; + + fixture.frame(vec![pointer::moved(shown.center())]).idle(2); + assert!(drawn_in(&mut fixture, shown) > 0, "the visible layer's eye is drawn"); + + fixture.frame(vec![pointer::moved(hidden.center())]).idle(2); + assert_eq!(drawn_in(&mut fixture, hidden), 0, "the hidden layer's box stays empty under the pointer"); +} diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index f26bb25280..d6b93a7683 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -85,6 +85,8 @@ pub struct Gallery<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { caption: CaptionPlace, /// Each shown tile's rect. laid: Vec, + /// The column of stepper buttons, if shown. + column: Rect, picked: Option, menu: Option>, } @@ -118,6 +120,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> { thumb_size: ThumbSize::Medium, caption: CaptionPlace::None, laid: Vec::new(), + column: Rect::NOTHING, picked: None, menu: None, } @@ -131,7 +134,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> { self } - /// One rounded frame on the raised surface around the tiles and the buttons, as the old Word-style ribbon drew + /// One rounded frame on the sunken well surface around the tiles and the buttons, as the old Word-style ribbon drew /// its Styles gallery. pub fn framed(mut self) -> Self { self.framed = true; @@ -509,6 +512,9 @@ pub struct GalleryStyle { frame: (StyleColor, StyleColor, f32), /// The room inside a frame. inset: f32, + /// The stepper buttons column's track fill and divider. + track: StyleColor, + divider: StyleColor, } /// The sizes the gallery's faces measure. @@ -527,8 +533,10 @@ impl Component for Gallery<'_, K> let colors = &cx.tokens.color; GalleryStyle { metrics: Metrics::new().gap(cx.tokens.space.gap.inline), - frame: (cx.color(colors.surface.raised), cx.color(colors.line.control_edge), cx.tokens.shape.radius.control), + frame: (cx.color(colors.surface.sunken), cx.color(colors.line.control_edge), cx.tokens.shape.radius.control), inset: cx.tokens.space.gap.inline, + track: cx.color(colors.surface.panel), + divider: cx.color(colors.line.divider), } } @@ -566,6 +574,7 @@ impl Component for Gallery<'_, K> let buttons = self.buttons(level); let rect = rect.shrink2(Vec2::new(self.inset(cx.style), 0.0)); let (column, rest) = Flow::new(rect, cx.flow.is_rtl()).take_end(if buttons { sizes.button.x } else { 0.0 }); + self.column = if buttons { column } else { Rect::NOTHING }; self.laid.clear(); for at in 0..shown { let cell = rest.span(at as f32 * (sizes.tile.x + sizes.gap), sizes.tile.x); @@ -702,6 +711,18 @@ impl Component for Gallery<'_, K> if !self.buttons(level) { return; } + if self.framed && self.column.is_positive() { + let draw = ui.draw(); + let radius = cx.style.frame.2.round().clamp(0.0, 255.0) as u8; + let track_shape = PaintShape::Rect(self.column, CornerRadius::same(radius)); + draw.fill(&track_shape, cx.style.track); + draw.stroke(&track_shape, craft_ui::primitives::StrokeWidth::Thin, cx.style.divider); + let height = self.column.height() / 3.0; + let y1 = self.column.min.y + height; + let y2 = self.column.min.y + 2.0 * height; + draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y1), egui::pos2(self.column.right(), y1)); + draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y2), egui::pos2(self.column.right(), y2)); + } ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0)); ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last)); ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone())); diff --git a/crates/menu/tests/it/ribbon_gallery.rs b/crates/menu/tests/it/ribbon_gallery.rs index 41061fe14b..8314365ebc 100644 --- a/crates/menu/tests/it/ribbon_gallery.rs +++ b/crates/menu/tests/it/ribbon_gallery.rs @@ -138,3 +138,56 @@ fn a_wide_captioned_gallery_names_its_tiles_under_wide_pictures() { assert!(name.min.y >= wide.min.y + square.width() / 2.0, "the name {name:?} is under the picture in {wide:?}"); assert!(!plain.iter().any(|(text, _)| text == "Tile 0"), "a plain tile paints no name: {plain:?}"); } + +/// A framed gallery paints a sunken well fill over its bounds, and a panel fill over its stepper button track. +#[trial] +fn a_framed_gallery_paints_sunken_well_and_stepper_track() { + use craft_ui::runtime::env::Env; + use egui::Color32; + + fn fills(shapes: &[egui::Shape], out: &mut Vec<(egui::Rect, egui::Color32)>) { + for shape in shapes { + match shape { + egui::Shape::Vec(inner) => fills(inner, out), + egui::Shape::Rect(rect) => out.push((rect.rect, rect.fill)), + _ => {} + } + } + } + + let colors_and_rect = Rc::new(Cell::new((Rect::NOTHING, Color32::TRANSPARENT, Color32::TRANSPARENT))); + let held = colors_and_rect.clone(); + let mut fixture = Fixture::new(move |ui| { + let [sr, sg, sb, sa] = Env::of(ui).tokens.tokens().color.surface.sunken.0; + let [pr, pg, pb, pa] = Env::of(ui).tokens.tokens().color.surface.panel.0; + let sunken = Color32::from_rgba_unmultiplied(sr, sg, sb, sa); + let panel = Color32::from_rgba_unmultiplied(pr, pg, pb, pa); + + let paint = |_: &ContentPainterCx, _: Rect| {}; + let items: Vec> = + (0..10).map(|at| GalleryItem { key: at, label: Label::from(format!("Tile {at}")), face: GalleryFace::Paint(&paint) }).collect(); + let out = Gallery::new("Styles", &items, None).tiles(6, 3).framed().show(ui); + held.set((out.response.rect, sunken, panel)); + }); + fixture.settle(); + + let (gallery_rect, sunken, panel) = colors_and_rect.get(); + assert!(gallery_rect.is_positive(), "the gallery paints a positive rect"); + + let mut seen = Vec::new(); + fills(&fixture.frame_shapes(), &mut seen); + + assert!( + seen.iter() + .any(|(rect, fill)| *fill == sunken && rect.contains_rect(gallery_rect.shrink(1.0)) && gallery_rect.expand(1.0).contains_rect(*rect)), + "a sunken fill covers the gallery {gallery_rect:?}: {seen:?}" + ); + + let up = fixture.by_label("Previous row").expect("the up button shows"); + let down = fixture.by_label("Next row").expect("the down button shows"); + let more = fixture.by_label("More").expect("the more button shows"); + let column = up.rect.union(down.rect).union(more.rect); + let stepper_track = + seen.iter().find(|(rect, fill)| *fill == panel && rect.contains_rect(column.shrink(1.0)) && gallery_rect.contains_rect(*rect)); + assert!(stepper_track.is_some(), "a panel fill covers the stepper track column {column:?}: {seen:?}"); +} diff --git a/crates/pages/src/layout.rs b/crates/pages/src/layout.rs index ed571bfa72..1189ba99fc 100644 --- a/crates/pages/src/layout.rs +++ b/crates/pages/src/layout.rs @@ -7,13 +7,12 @@ //! out), with a markup column beside each page and Hide White Space. [`PageDisplay`] holds both, //! and [`LayoutOptions`] carries each app's switches ([`LayoutOptions::ACROBAT`], //! [`LayoutOptions::WORD`]). The screen spacing ([`PageSpacing`]: gap, margin, side gutter, Hide -//! White Space's pad and seam) is not a constant here: the page view reads it from the `pages.*` -//! size tokens (`PageView::style`), which an app overrides in its `sizes.json` (WordCraft's wider -//! gap and no side gutter). +//! White Space's pad and seam) is not a constant here: the page view derives it from the scope's +//! semantic tokens and `ComponentSet` (`Creative` keeps the tool-rail side gutter; `Productivity` +//! uses a wider gap and matching margin/side without the rail gutter). //! //! ```ignore //! let sizes: Vec = doc.pages.iter().map(|p| p.size()).collect(); -//! let spacing = PageView::style(&tokens).spacing; //! let scale = fit_scale(&sizes, viewport, view.fit, &options, &spacing, view.current).unwrap_or(view.zoom * SCREEN_POINTS_PER_POINT); //! let laid = place_pages(&sizes, scale, viewport, &options, &spacing); //! let shown = if options.continuous { 0..sizes.len() } else { shown_row(sizes.len(), view.current, &options) }; @@ -118,9 +117,9 @@ impl LayoutOptions { } /// The spacing of a page layout: screen points, except [`white_space_pad`](Self::white_space_pad), -/// which is in points at 100 % zoom and is multiplied by the zoom. The page view takes it from the `pages.*` size tokens -/// (`craft_pages::ui::PageView::style`); this crate's core has no tokens, so the layout functions -/// take it as a value. +/// which is in points at 100 % zoom and is multiplied by the zoom. The page view derives it from the +/// scope's semantic tokens and `ComponentSet`; this crate's core has no tokens, so the layout +/// functions take it as a value. #[derive(Clone, Copy, Debug, PartialEq)] pub struct PageSpacing { /// Between pages, and between rows (the page view's gap); unused with diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index 3d4244cb56..59bb088272 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -38,6 +38,7 @@ use craft_ui::contract::{Bind, BodyCx, Held, Props as _, Show as _, ShowContaine use craft_ui::primitives::EditorPurpose; use craft_ui::primitives::textures::ThumbSource; use craft_ui::runtime::env::{Env, Label}; +use craft_ui::runtime::focus::EditSet; use craft_ui::runtime::memory::Remember as _; use craft_ui::style::DataColor; use egui::{Rect, Ui, Vec2, pos2}; @@ -338,6 +339,7 @@ pub struct PageView<'a> { describer: Option<&'a dyn AccessDescriber>, paper: DataColor, editor: Option, + inactive_edits: EditSet, snap: Option, tool_regions: Vec, rulers: bool, @@ -362,6 +364,7 @@ impl<'a> PageView<'a> { describer: None, paper, editor: None, + inactive_edits: EditSet::NONE, snap: None, tool_regions: Vec::new(), rulers: false, @@ -404,6 +407,13 @@ impl<'a> PageView<'a> { self } + /// Edit commands the view's editor part cannot act on right now, forwarded to [`Canvas::inactive_edits`]. + #[must_use] + pub fn inactive_edits(mut self, inactive: EditSet) -> Self { + self.inactive_edits = inactive; + self + } + /// The snapping of the coordinates the pointer sets on the view, with its targets in page points. The view places /// them on the pages that show this pass, drops those of pages outside the shown row and passes the result to the /// inner canvas. @@ -455,7 +465,22 @@ impl<'a> PageView<'a> { } fn run(self, ui: &mut Ui, rect: Rect, take_room: bool, mut body: impl FnMut(&mut Ui, &PageBody<'_>)) -> PageViewOutput { - let PageView { label, source, state, options, navigation, bodies, describer, paper, editor, snap, tool_regions, rulers, reach } = self; + let PageView { + label, + source, + state, + options, + navigation, + bodies, + describer, + paper, + editor, + inactive_edits, + snap, + tool_regions, + rulers, + reach, + } = self; let spacing = PageMetrics::new().show_at(ui, Rect::from_min_size(rect.min, Vec2::ZERO)).spacing; let count = source.page_count(); @@ -485,7 +510,7 @@ impl<'a> PageView<'a> { let regions: Vec = tool_regions.iter().filter_map(|region| placed_region(region, &geo, &frame)).collect(); let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).tool_regions(regions); if let Some(purpose) = editor { - canvas = canvas.editor(purpose); + canvas = canvas.editor(purpose).inactive_edits(inactive_edits); } if let Some(snap) = &snap { canvas = canvas.snap(placed_snap(snap, &geo, &frame)); diff --git a/crates/pages/src/ui/view/pictures.rs b/crates/pages/src/ui/view/pictures.rs index 3a6d0c0f87..ad9cd40c55 100644 --- a/crates/pages/src/ui/view/pictures.rs +++ b/crates/pages/src/ui/view/pictures.rs @@ -5,6 +5,7 @@ use super::{PageSource, PlacedPage}; use crate::layout::PageSpacing; use crate::ui::access::{AccessDescriber, describe}; use craft_behavior::{Input, Metrics, PixelSize, Sense}; +use craft_theme::ComponentSet; use craft_ui::canvas::DetailPlan; use craft_ui::canvas::PixelRect; use craft_ui::contract::{Access, Common, Component, Cx, DisabledLook, MeasureCx, NoValue, Outcome, PaintUi, Role}; @@ -15,8 +16,12 @@ use craft_ui::runtime::memory::Remember as _; use craft_ui::style::{ComponentStyle, DataColor, StyleCx}; use egui::{Rect, Response, Vec2, pos2}; +/// Productivity inter-page gap as a multiple of `space.gap.section`: 18 pt in Compact (Word's gap) and 24 pt in +/// Comfortable. +const PRODUCTIVITY_GAP_RATIO: f32 = 1.5; + /// The style of the page view's spacing: the gap between pages, the margin, the side column, Hide White Space's pad -/// and its seam, all from the tokens. +/// and its seam, from the tokens and the scope's [`ComponentSet`]. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct PageMetricsStyle { @@ -74,14 +79,26 @@ impl Component for PageMetrics { fn style(cx: &StyleCx<'_>, _: PageMetricsStyleKey) -> PageMetricsStyle { let tokens = cx.tokens; - let pad = tokens.space.pad; - PageMetricsStyle { - metrics: Metrics::new(), - gap: tokens.space.gap.section, - margin: pad.roomy, - side: tokens.size.rail.width, - white_space_pad: tokens.space.gap.inline, - seam: tokens.stroke.thin, + match cx.set() { + ComponentSet::Creative => PageMetricsStyle { + metrics: Metrics::new(), + gap: tokens.space.gap.section, + margin: tokens.space.pad.roomy, + side: tokens.size.rail.width, + white_space_pad: tokens.space.gap.inline, + seam: tokens.stroke.thin, + }, + ComponentSet::Productivity => { + let gap = tokens.space.gap.section * PRODUCTIVITY_GAP_RATIO; + PageMetricsStyle { + metrics: Metrics::new(), + gap, + margin: gap, + side: gap, + white_space_pad: tokens.space.gap.stack, + seam: tokens.stroke.thin, + } + } } } diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index 425a56ccfb..8a8f04cd68 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -3,18 +3,21 @@ use craft_behavior::geometry::{CropBox, SnapKind, SnapOptions, SnapTarget}; use craft_behavior::kurbo; -use craft_behavior::{Axis, CancelReason, CanvasView}; -use craft_pages::layout::{Fit, LayoutOptions, PageDisplay}; +use craft_behavior::{Axis, CancelReason, CanvasView, EditCommand}; +use craft_pages::layout::{Fit, LayoutOptions, PageDisplay, PagedLayout}; use craft_pages::ui::fixtures::{DemoPages, PAPER}; use craft_pages::ui::{ PagePreview, PageRegion, PageSnap, PageSource, PageView, PageViewState, PageViewWords, PlacedPage, ReadingNav, ReadingState, ReadingView, }; +use craft_theme::ComponentSet; use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer}; use craft_ui::contract::{Bind, Role, Show as _}; use craft_ui::primitives::textures::TextureStoreOptions; use craft_ui::primitives::{Draw, EditorPurpose}; +use craft_ui::runtime::commands::{CommandState, EditCommands, resolve}; use craft_ui::runtime::env::Env; +use craft_ui::runtime::focus::EditSet; use craft_ui::testing::{Fixture, pointer, trial}; use egui::{Key, Modifiers, pos2, vec2}; use std::cell::{Cell, RefCell}; @@ -955,3 +958,160 @@ fn go_to_a_point_inside_a_page_puts_it_at_the_top() { assert_eq!(first, Some(5), "the first page in view is the one gone to"); assert!((offset - at).abs() < 0.01, "the view's top {offset} is the point gone to, {at}"); } + +/// Lays out three pages under `set` with `start`, returning the layout and the scope's `space.gap.section` token. +fn layout_in_set(set: ComponentSet, options: LayoutOptions, start: PageViewState, bodies: Option<&'static [(f64, f64)]>) -> (PagedLayout, f32) { + let state = Rc::new(RefCell::new(start)); + let seen: Rc> = Rc::default(); + let (kept, recorded) = (Rc::clone(&state), Rc::clone(&seen)); + let pages = DemoPages::new(3); + let mut fixture = Fixture::new(move |ui| { + let section_gap = Env::of(ui).tokens.space.gap.section; + let mut now = kept.borrow().clone(); + let mut view = PageView::new("Pages", &pages, &mut now, PAPER).options(options); + if let Some(bodies) = bodies { + view = view.bodies(bodies); + } + let out = view.show(ui, |_, _| ()); + *recorded.borrow_mut() = (out.layout, section_gap); + *kept.borrow_mut() = now; + }); + fixture.set(set); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + seen.borrow().clone() +} + +/// The productivity component set gives pages a wider inter-page gap, no tool-rail side gutter under Fit Width (without +/// overflowing the viewport), and wider Hide White Space padding than the creative set, while leaving `space.gap.section` +/// untouched for other components. +#[trial] +fn the_component_set_picks_the_page_spacing_without_changing_section_gap() { + let fixed = state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Columns; + }); + let (creative, creative_section) = layout_in_set(ComponentSet::Creative, LayoutOptions::WORD, fixed.clone(), None); + let (productivity, productivity_section) = layout_in_set(ComponentSet::Productivity, LayoutOptions::WORD, fixed, None); + let creative_gap = creative.rects[1].y0 - creative.rects[0].y1; + let productivity_gap = productivity.rects[1].y0 - productivity.rects[0].y1; + assert_eq!(productivity_section, creative_section, "space.gap.section is unchanged by the component set"); + assert!(productivity_gap > creative_gap, "productivity inter-page gap ({productivity_gap}) is wider than creative ({creative_gap})"); + assert!( + productivity.rects[0].y0 > creative.rects[0].y0, + "productivity top margin ({}) is wider than creative ({})", + productivity.rects[0].y0, + creative.rects[0].y0 + ); + + let fit_width = state_with(|s| { + s.fit = Fit::Width; + s.display = PageDisplay::Columns; + }); + let (creative_fit, _) = layout_in_set(ComponentSet::Creative, LayoutOptions::WORD, fit_width.clone(), None); + let (productivity_fit, _) = layout_in_set(ComponentSet::Productivity, LayoutOptions::WORD, fit_width, None); + assert!( + productivity_fit.rects[0].width() > creative_fit.rects[0].width(), + "productivity Fit Width fills more of the viewport ({}) than creative with its rail gutter ({})", + productivity_fit.rects[0].width(), + creative_fit.rects[0].width() + ); + assert!( + productivity_fit.size.width <= 900.0 + 0.5, + "productivity Fit Width stays within the viewport width without horizontal overflow: {}", + productivity_fit.size.width + ); + + const BODIES: [(f64, f64); 3] = [(72.0, 720.0); 3]; + let hidden = state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Single; + s.hide_white_space = true; + }); + let (creative_hidden, _) = layout_in_set(ComponentSet::Creative, LayoutOptions::ACROBAT, hidden.clone(), Some(&BODIES)); + let (productivity_hidden, _) = layout_in_set(ComponentSet::Productivity, LayoutOptions::ACROBAT, hidden, Some(&BODIES)); + assert!( + productivity_hidden.bands[1].0 < creative_hidden.bands[1].0 && productivity_hidden.bands[1].1 > creative_hidden.bands[1].1, + "productivity Hide White Space keeps more pad around the text body: {:?} vs {:?}", + productivity_hidden.bands[1], + creative_hidden.bands[1] + ); +} + +/// Switching the component set updates the page view's inter-page spacing on the frame of the change and settles. +#[trial] +fn a_component_set_change_updates_the_page_view_spacing() { + let state = Rc::new(RefCell::new(state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Columns; + }))); + let gap = Rc::new(Cell::new(0.0_f64)); + let (kept, seen) = (Rc::clone(&state), Rc::clone(&gap)); + let pages = DemoPages::new(3); + let mut fixture = Fixture::new(move |ui| { + let mut now = kept.borrow().clone(); + let out = PageView::new("Pages", &pages, &mut now, PAPER).options(LayoutOptions::WORD).show(ui, |_, _| ()); + seen.set(out.layout.rects[1].y0 - out.layout.rects[0].y1); + *kept.borrow_mut() = now; + }); + fixture.set(ComponentSet::Creative); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + let creative_gap = gap.get(); + + fixture.set(ComponentSet::Productivity); + fixture.frame(Vec::new()); + let productivity_gap = gap.get(); + assert!( + productivity_gap > creative_gap, + "switching to productivity widens the page gap on the frame of the change: {productivity_gap} vs {creative_gap}" + ); + fixture.idle(1); + assert_eq!(gap.get(), productivity_gap, "an idle frame after the switch keeps the new gap"); +} + +/// `PageView::inactive_edits` forwards to its inner canvas editor: Cut resolves disabled while inactive and enabled +/// once active, and Undo/Redo fall through to app command states while inactive. +#[trial] +fn page_view_forwards_inactive_edits_to_its_editor_canvas() { + let state = Rc::new(RefCell::new(PageViewState::default())); + let inactive = Rc::new(Cell::new(EditSet::NONE.with(EditCommand::Cut).with(EditCommand::Undo).with(EditCommand::Redo))); + let (kept_state, kept_inactive) = (Rc::clone(&state), Rc::clone(&inactive)); + let pages = DemoPages::new(2); + let mut fixture = Fixture::new(move |ui| { + let mut now = kept_state.borrow().clone(); + PageView::new("Pages", &pages, &mut now, PAPER) + .options(LayoutOptions::ACROBAT) + .editor(EditorPurpose::Text) + .inactive_edits(kept_inactive.get()) + .show(ui, |_, _| ()); + *kept_state.borrow_mut() = now; + }); + fixture.command_state(EditCommands::Cut, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(false)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(false)); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + + let canvas_rect = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").rect; + fixture.click_at(canvas_rect.center()); + fixture.settle(); + assert!(fixture.focused().is_some(), "clicking the page view focuses its editor canvas"); + + assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "inactive Cut resolves disabled on focused PageView"); + assert!(!resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo falls through to disabled app state"); + assert!(!resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo falls through to disabled app state"); + + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(true)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo follows enabled app state"); + assert!(resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo follows enabled app state"); + + inactive.set(EditSet::NONE.with(EditCommand::Undo).with(EditCommand::Redo)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "active Cut resolves enabled on focused PageView"); +} diff --git a/crates/text/src/ui/editor.rs b/crates/text/src/ui/editor.rs index fad53f0831..eeb07900d3 100644 --- a/crates/text/src/ui/editor.rs +++ b/crates/text/src/ui/editor.rs @@ -40,7 +40,7 @@ use craft_ui::contract::{ use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState, PaintShape, StrokeWidth}; use craft_ui::runtime::commands::ClipItem; use craft_ui::runtime::env::Label; -use craft_ui::runtime::focus::KeyUse; +use craft_ui::runtime::focus::{FocusPolicy, KeyUse}; use craft_ui::runtime::pending::Pending; use craft_ui::style::{ComponentStyle, StyleColor, StyleCx}; use egui::{Pos2, Rect, Response, Vec2}; @@ -445,6 +445,14 @@ fn char_at(lines: &[HostLine], pos: TextPos) -> usize { line.chars.start + line.text[..byte].chars().count() } +/// The I-beam is the editor's over its text and while its own press is held; elsewhere the canvas's tool or the rest +/// of the UI sets the pointer. +fn show_i_beam(cx: &mut Cx<'_, TextEditor<'_>>, phase: &PressPhase, vertical: bool) { + if !matches!(phase, PressPhase::Idle) { + cx.cursor(if vertical { CursorIcon::VerticalText } else { CursorIcon::Text }, CursorPriority::Hover); + } +} + /// The clipboard's text when the pass's input asks to paste and the clipboard has it ready. fn pasted_text(cx: &mut Cx<'_, TextEditor<'_>>, inputs: &[EditorInput]) -> Option> { if !inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))) { @@ -461,6 +469,8 @@ impl Component for TextEditor<'_> { const INPUT: craft_ui::contract::Input = craft_ui::contract::Input::Editor; /// Escape always ends the session, so the editor keeps it from its row and from the shortcuts while focused. const KEYS: KeyUse = KeyUse::CODE.with_claims(&[ESCAPE]); + /// When the session ends, focus goes back to the stop it came from (the canvas), not to the stop before the editor. + const FOCUS_SCOPE: FocusPolicy = FocusPolicy::TAB_LAYER; type Style = TextEditorStyle; type Output = TextEditorOutput; @@ -618,7 +628,7 @@ impl Component for TextEditor<'_> { if let Some(text) = copied { cx.clipboard().put(&[ClipItem::Text(text.into())]); } - cx.cursor(if vertical { CursorIcon::VerticalText } else { CursorIcon::Text }, CursorPriority::Hover); + show_i_beam(cx, &press.phase, vertical); if done.changed { cx.propose(selection); } else if selection != before { diff --git a/crates/text/tests/it/editor.rs b/crates/text/tests/it/editor.rs index f23eb21f19..ef7e1ee25f 100644 --- a/crates/text/tests/it/editor.rs +++ b/crates/text/tests/it/editor.rs @@ -210,6 +210,25 @@ fn a_secondary_click_on_the_text_reports_a_context_click_and_starts_no_drag() { assert_eq!(editor.commits.get() + editor.cancels.get(), 0, "the session stays open"); } +/// The I-beam is the editor's only over its text and while its own press is held: elsewhere the pointer is the +/// canvas's or the rest of the UI's. +#[trial] +fn the_i_beam_shows_over_the_text_and_during_its_drag_but_not_elsewhere() { + let mut editor = session("abc def", None); + editor.focus(); + let i_beam = Some(craft_behavior::Cursor::System(craft_behavior::CursorIcon::Text)); + let cursor = |editor: &Session| craft_ui::runtime::cursor::current(editor.fixture.ctx()); + let (on_text, away) = (pos2(40.0, 10.0), pos2(300.0, 300.0)); + editor.fixture.frame(vec![pointer::moved(on_text)]).settle(); + assert_eq!(cursor(&editor), i_beam, "over the text"); + editor.fixture.frame(vec![pointer::moved(away)]).settle(); + assert_ne!(cursor(&editor), i_beam, "away from the text, with the session open"); + editor.fixture.frame(vec![pointer::moved(on_text)]).frame(vec![pointer::press(on_text)]).frame(vec![pointer::moved(away)]); + assert_eq!(cursor(&editor), i_beam, "a drag that leaves the text keeps it"); + editor.fixture.frame(vec![pointer::release(away)]).settle(); + assert_ne!(cursor(&editor), i_beam, "after the release"); +} + fn preedit(text: &str) -> Event { Event::Ime(ImeEvent::Preedit { text: text.to_owned(), active_range_chars: None }) } @@ -346,3 +365,51 @@ fn formatting_keys_follow_the_flow_and_fall_back_to_caret_moves() { assert!(!plain.host.borrow().styles.is_empty(), "the host was asked for the leading step"); assert_eq!(plain.selection.borrow().caret, before.saturating_sub(LINE), "the step the host did not take moved the caret a line up"); } + +/// #15555: a session the app ends (Cmd+Enter, then the editor is not shown) on a canvas with rulers hands the focus back +/// to the canvas it came from, not to the stop before the editor (the rulers' corner, whose arrows move the zero point), +/// and the view stays where it was. Without rulers the canvas is that stop anyway. +#[trial] +fn an_ended_session_returns_the_focus_to_the_canvas_and_the_view_stays() { + const EDITOR: craft_behavior::DocKey = craft_behavior::DocKey::new("trial.type-editor"); + use craft_ui::canvas::Rulers; + use craft_ui::contract::Props as _; + use craft_ui::runtime::focus::{FocusTarget, request}; + use craft_ui::testing::access::{focused_key, name}; + + for rulers in [true, false] { + let editing = Rc::new(Cell::new(false)); + let view = Rc::new(Cell::new(None::)); + let (shown_editing, shown_view) = (Rc::clone(&editing), Rc::clone(&view)); + let mut host = Host { text: "abc".to_owned(), ..Host::default() }; + let mut selection = TextSelection::caret_at(3); + let mut zero = Point::ZERO; + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let given = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(100.0, 100.0), 1.0)); + let strips = rulers.then(|| Rulers::new("Rulers", Bind::bound(&mut zero))); + let canvas = Canvas::new("Document").view(given).with_rulers(strips).show(ui, |ui, body| { + if shown_editing.get() { + let bounds = Rect::from_min_size(body.rect.min + vec2(40.0, 40.0), vec2(200.0, 20.0)); + drop(TextEditor::new("Text", &mut host, Bind::bound(&mut selection)).doc_key(EDITOR).show_at(ui, bounds)); + } + }); + shown_view.set(Some(canvas.output.view.unwrap_or(given))); + }); + fixture.room(vec2(600.0, 400.0)).settle(); + let focused = |fixture: &Fixture| name(fixture.tree(), focused_key(fixture.tree())).map(str::to_owned); + // A press on the canvas focuses it, and the session that press starts asks for the editor's focus. + fixture.click_at(pos2(400.0, 300.0)).settle(); + assert_eq!(focused(&fixture).as_deref(), Some("Document"), "rulers {rulers}: the press focused the canvas"); + editing.set(true); + fixture.settle(); + request(fixture.ctx(), FocusTarget::Doc(EDITOR)); + fixture.settle(); + assert_eq!(focused(&fixture).as_deref(), Some("Text"), "rulers {rulers}: the editor took the focus"); + let before = view.get(); + editing.set(false); + fixture.settle(); + assert_eq!(focused(&fixture).as_deref(), Some("Document"), "rulers {rulers}: the focus went back to the canvas"); + assert_eq!(view.get(), before, "rulers {rulers}: the view stays"); + } +} diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 1e4895efef..dea38e0381 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -107,7 +107,7 @@ use crate::contract::{ use crate::primitives::{EditorPurpose, ImeStamp}; use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; -use crate::runtime::focus::KeyUse; +use crate::runtime::focus::{EditSet, KeyUse}; use crate::runtime::lock_keys; use crate::runtime::measure; use crate::runtime::motion::{Animate as _, spec}; @@ -217,6 +217,12 @@ pub struct Canvas<'a> { /// does not apply. The body reports its editor state through [`ToolPass::editor`]. #[prop] editor: Option, + /// Edit commands the canvas's editor part cannot act on right now (for instance Cut and Copy with nothing + /// selected, or Undo and Redo with no editor-local history). Applied to [`KeyUse::inactive`] while + /// [`editor`](Self::editor) is set: Cut, Copy, Paste and Select All stay the editor's and resolve disabled; Undo + /// and Redo fall through to the app command's state. Ignored without [`editor`](Self::editor). + #[prop] + inactive_edits: EditSet, /// The editor part's inputs of this pass, taken once in `update`: `tool_pass` is built from a shared `Cx`. editor_input: Arc<[EditorInput]>, /// The rulers' units and zero point, published to the body in its [`CanvasSpace`]. @@ -308,6 +314,7 @@ impl<'a> Canvas<'a> { ruler_output: None, keys_to_body: false, editor: None, + inactive_edits: EditSet::NONE, editor_input: Arc::from([]), pasteboard: PasteboardColor::Default, precise_cursors: false, @@ -825,7 +832,7 @@ impl Component for Canvas<'_> { /// nudges. It still marks its window as showing a document. fn keys(&self) -> KeyUse { match self.editor { - Some(_) => KeyUse::of(Input::Editor).with_chrome_key(true).with_moves(), + Some(_) => KeyUse::of(Input::Editor).with_chrome_key(true).with_moves().with_inactive(self.inactive_edits), None => Self::KEYS, } } diff --git a/crates/ui-canvas/src/canvas/scrollbars/mod.rs b/crates/ui-canvas/src/canvas/scrollbars/mod.rs index a4311c53b5..6b64e16245 100644 --- a/crates/ui-canvas/src/canvas/scrollbars/mod.rs +++ b/crates/ui-canvas/src/canvas/scrollbars/mod.rs @@ -3,9 +3,13 @@ //! thickness at rest and under the pointer. Document chrome uses inset thumbs, step buttons and a corner. //! The thumb is the visible fraction of //! the scrollable extent (the document, plus wherever the view has been scrolled past it); drag it to scroll, or press -//! the track to page by one screenful. With overscroll on, a document smaller than the window can also be scrolled from -//! one edge of the window to the other. With overscroll off the app clamps the view before it draws -//! ([`CanvasScrollbars::clamp`]). +//! the track to page by one screenful. With overscroll on, the extent also takes in the pasteboard around the document, +//! as in the reference application: at either end of a track [`KEPT_IN_VIEW`] points of the document stay in view at +//! the opposite edge, whether the document is larger or smaller than the window. With overscroll off the app clamps the +//! view before it draws ([`CanvasScrollbars::clamp`]). +//! +//! A thumb drag keeps the extent it began with and follows the pointer from the press: the thumb stays under the +//! pointer, also after the pointer went past a track's end and came back. //! //! The bars measure the view along the screen axes, so on a rotated view they show the extent of the unrotated //! document. @@ -44,6 +48,10 @@ const ARROW_STEP_PIXELS: f64 = 16.0; const ARROW_HOLD_DELAY: f64 = 0.4; const ARROW_HOLD_INTERVAL: f64 = 0.06; +/// With overscroll on, how much of the document stays in view, in screen points, when a thumb is at either end of its +/// track: the reference application keeps 100 screen pixels at every zoom, on both axes. +const KEPT_IN_VIEW: f64 = 100.0; + /// The popup of the tip beside a dragged vertical thumb. const TIP: &str = "tip"; @@ -76,26 +84,30 @@ struct Span { /// First and last visible coordinate. v0: f64, v1: f64, + /// [`KEPT_IN_VIEW`] in document units on this axis. + kept: f64, } impl Span { - /// The axis of a view: `size` screen points at `zoom` around `center`. - fn of(len: f64, center: f64, size: f64, zoom: f64) -> Option { + /// The axis of a view: `size` screen points at `zoom` around `center`; `kept` is [`KEPT_IN_VIEW`] in the same + /// points (the horizontal axis divides both by the pixel aspect). + fn of(len: f64, center: f64, size: f64, zoom: f64, kept: f64) -> Option { let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { return None }; let half = size / zoom / 2.0; - let span = Span { len, v0: center - half, v1: center + half }; + let span = Span { len, v0: center - half, v1: center + half, kept: kept / zoom }; (span.len.is_finite() && span.len > 0.0 && span.v0.is_finite() && span.v1.is_finite() && span.v1 > span.v0).then_some(span) } - /// The scrollable extent: the document and the visible span. With `overscroll`, a document shorter than the span - /// may slide edge to edge within it. + /// The scrollable extent: the document and the visible span. With `overscroll` also the pasteboard on both sides, + /// up to where only [`KEPT_IN_VIEW`] of the document (all of a shorter one) is left in view at the opposite edge. fn content(&self, overscroll: bool) -> Range { let (lo, hi) = (self.v0.min(0.0), self.v1.max(self.len)); if !overscroll { return lo..hi; } - let visible = self.v1 - self.v0; - lo.min(self.len - visible)..hi.max(visible) + let kept = if self.kept.is_finite() { self.kept.clamp(0.0, self.len) } else { self.len }; + let room = (self.v1 - self.v0 - kept).max(0.0); + lo.min(-room)..hi.max(self.len + room) } fn scroll(&self, overscroll: bool) -> ScrollSpan { @@ -142,6 +154,26 @@ impl Bar { } } +/// A pressed thumb: the extent and the visible range it was pressed at. Its drag maps the pointer's movement from the +/// press onto that extent, so the track does not grow or shrink under the pointer while the view moves, and the thumb +/// stays under the pointer. +#[derive(Clone, Debug, Default, PartialEq)] +struct HeldThumb { + horizontal: bool, + content: Range, + visible: Range, +} + +impl HeldThumb { + fn of(axis: Axis, span: &ScrollSpan) -> Self { + HeldThumb { horizontal: axis == Axis::X, content: span.content.clone(), visible: span.visible.clone() } + } + + fn on(&self, axis: Axis) -> bool { + self.horizontal == (axis == Axis::X) + } +} + /// The bars of a view over a document, in the order horizontal, vertical. struct Bars { horizontal: Option, @@ -198,6 +230,11 @@ fn paint_arrow(draw: &Draw<'_>, rect: Rect, axis: Axis, after: bool, color: Styl draw.stroke(&path, StrokeWidth::Thin, color); } +/// The length of a scroll bar's track along `axis`. +fn scroll_track_length(track: Rect, axis: Axis) -> f32 { + if axis == Axis::X { track.width() } else { track.height() } +} + /// How the document's x axis runs on screen: with the view flipped, backwards. fn along_x(view: &CanvasView, width: f64, c: f64) -> f64 { if view.flip_x { width - c } else { c } @@ -208,20 +245,43 @@ fn aspect(view: &CanvasView) -> f64 { } impl Bars { - /// The bars inside `rect` (bottom and right edges), `width` thick, for `view` over the document `doc`. - fn of(view: &CanvasView, doc: DocRect, overscroll: bool, horizontal: bool, rect: Rect, style: &ScrollbarsStyle) -> Bars { + /// The bars inside `rect` (bottom and right edges), `width` thick, for `view` over the document `doc`. A `held` + /// thumb's bar keeps the extent the thumb was pressed at. + fn of( + view: &CanvasView, + doc: DocRect, + overscroll: bool, + horizontal: bool, + rect: Rect, + style: &ScrollbarsStyle, + held: Option<&HeldThumb>, + ) -> Bars { let document_chrome = style.document.is_some(); let mut width = style.look.thickness; if document_chrome { width = width.min(rect.width().max(0.0)).min(rect.height().max(0.0)); } - let x = Span::of(doc.width(), along_x(view, doc.width(), view.center.x - doc.x0), f64::from(view.rect.width()) / aspect(view), view.zoom) - .filter(|_| horizontal); - let y = Span::of(doc.height(), view.center.y - doc.y0, f64::from(view.rect.height()), view.zoom); + let x = Span::of( + doc.width(), + along_x(view, doc.width(), view.center.x - doc.x0), + f64::from(view.rect.width()) / aspect(view), + view.zoom, + KEPT_IN_VIEW / aspect(view), + ) + .filter(|_| horizontal); + let y = Span::of(doc.height(), view.center.y - doc.y0, f64::from(view.rect.height()), view.zoom, KEPT_IN_VIEW); let right = if y.is_some() { rect.right() - width } else { rect.right() }; let bottom = if x.is_some() { rect.bottom() - width } else { rect.bottom() }; let corner = (document_chrome && x.is_some() && y.is_some()).then(|| Rect::from_min_max(pos2(right, bottom), rect.max)); - let bar = |span: Option, axis, rect| span.map(|span| Bar::new(rect, axis, span.scroll(overscroll), document_chrome)); + let bar = |span: Option, axis, rect| { + span.map(|span| { + let mut scroll = span.scroll(overscroll); + if let Some(held) = held.filter(|held| held.on(axis)) { + scroll.content = held.content.start.min(scroll.visible.start)..held.content.end.max(scroll.visible.end); + } + Bar::new(rect, axis, scroll, document_chrome) + }) + }; Bars { horizontal: bar(x, Axis::X, Rect::from_min_max(pos2(rect.left(), bottom), pos2(right, rect.bottom()))), vertical: bar(y, Axis::Y, Rect::from_min_max(pos2(right, rect.top()), pos2(rect.right(), bottom))), @@ -298,13 +358,24 @@ pub struct CanvasScrollbars<'a> { /// thumb on the reading-start side. #[prop] tip: Option<&'a dyn Fn(&CanvasView) -> Label>, + /// The thumb pressed in this pass, as `update` read it from the press slot, for `paint` and `access`. + held: Option, } impl<'a> CanvasScrollbars<'a> { /// Scroll bars named `label` that edit `view`, a view over the document `document` (document units). pub fn new(label: impl Into