From ae722739ab984d9daa1f0f4c6cea1a6ea82f5cc2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 03:28:05 +0000 Subject: [PATCH 01/16] ui-contract: presses the focused component holds leave egui's input again, and Tab stays navigation with nothing focused The merge of next (b138b533fe) passed whether a stop was focused where withdraw_taken takes whether the app's own widget reads its keys from egui, so no held press left egui's input while anything had focus. With nothing focused the document canvas's held claims leave out Tab and Shift+Tab: a tool that claims the plain keys no longer keeps keyboard navigation from moving into the window. The unfocused-canvas trial releases its keys, since a press of a key already down is a repeat. --- crates/ui-contract/src/runtime/keys/input.rs | 11 ++++++++--- crates/ui-contract/src/runtime/keys/route.rs | 4 +++- crates/ui-contract/src/testing/key_trials.rs | 3 ++- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index de0b670c2..b0ca7a5fc 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -541,12 +541,17 @@ enum PressUse { /// The chords the focused component of `record` claims: its stop's, the state-dependent ones (`keys::claim`) of the /// component, its arena root and its menu level, and a bare End where it declares `EndKey::EndMode`. With nothing -/// focused and no modal layer open, the window's document canvas's state-dependent claims hold instead. +/// focused and no modal layer open, the window's document canvas's state-dependent claims hold instead, except Tab and +/// Shift+Tab. pub(super) fn focused_claims(record: &focus::FocusedRecord, stage: &Stage) -> Vec { let mut claims = record.claims.clone(); let canvas = record.canvas.filter(|_| !record.foreign); - let holds = |owner: Id| [record.focused, record.root, record.menu, record.menu_bar, canvas].contains(&Some(owner)); - claims.extend(stage.claims.iter().filter(|(owner, _)| holds(*owner)).map(|(_, chord)| *chord)); + let holds = |owner: Id| [record.focused, record.root, record.menu, record.menu_bar].contains(&Some(owner)); + // The unfocused canvas's tool never takes Tab or Shift+Tab: with nothing focused they move focus into the window, + // so a tool that claims the plain keys cannot trap keyboard navigation. + let canvas_holds = + |owner: Id, chord: &Chord| Some(owner) == canvas && !(chord.key == Key::Tab && (chord.mods == Mods::NONE || chord.mods == Mods::SHIFT)); + claims.extend(stage.claims.iter().filter(|(owner, chord)| holds(*owner) || canvas_holds(*owner, chord)).map(|(_, chord)| *chord)); // A bare End belongs to a stop that declares `EndKey::EndMode`: it reads the key as a claimed chord and toggles its // mode, so no collection navigation or scroll owner takes it as a move to the end. if record.keys.is_some_and(|keys| keys.end == EndKey::EndMode) { diff --git a/crates/ui-contract/src/runtime/keys/route.rs b/crates/ui-contract/src/runtime/keys/route.rs index f88b186d9..a889e9d4d 100644 --- a/crates/ui-contract/src/runtime/keys/route.rs +++ b/crates/ui-contract/src/runtime/keys/route.rs @@ -185,7 +185,9 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { } let over: Vec = batch.presses.iter().map(held_press).collect(); let (shortcuts, held) = owned_shortcuts(ctx, target.as_ref(), &batch, &consumed, &taken_texts, &over); - withdraw_taken(ctx, target.is_some(), &batch, &held, &withdrawn_texts); + // The app's own widget, focused or the window's canvas, reads its keys from egui. + let host = target.as_ref().or(canvas.as_ref()).is_some_and(|rec| rec.stop.host); + withdraw_taken(ctx, host, &batch, &held, &withdrawn_texts); let pasted = batch.paste.clone().zip(focused).map(|(content, id)| (id, content)); // PLAN: a repeat Tab of a held-over key is not gated; `take_nav` reads `batch.tabs` before this hook runs (owner: focus). // One Escape press cancels once: its repeats cancel nothing more, in the layer it closed or in what that uncovered. diff --git a/crates/ui-contract/src/testing/key_trials.rs b/crates/ui-contract/src/testing/key_trials.rs index acc91136a..1efd74fce 100644 --- a/crates/ui-contract/src/testing/key_trials.rs +++ b/crates/ui-contract/src/testing/key_trials.rs @@ -258,7 +258,8 @@ fn an_unfocused_press_the_window_canvas_takes_reaches_no_app_shortcut() { take_output(&frames.ctx); let fired = |frames: &mut Frames, show: &mut dyn FnMut(&mut Ui)| { frames.frame(vec![key_press(Key::PageDown, Modifiers::NONE), key_press(Key::ArrowRight, Modifiers::NONE)], &mut *show); - frames.frame(Vec::new(), &mut *show); + // Released, so the next round's presses are fresh presses, not repeats of held keys. + frames.frame(vec![key_release(Key::PageDown, Modifiers::NONE), key_release(Key::ArrowRight, Modifiers::NONE)], &mut *show); take_output(&frames.ctx).fired.len() }; assert_eq!(fired(&mut frames, &mut show), 0, "neither press reaches the app's commands"); From 22205fffd1db1ba95a65564a2607593f77a45b5c Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 03:28:05 +0000 Subject: [PATCH 02/16] ui-contract: an OS file drop lands where it was dropped, and files hovering in the pass that takes it start their own drag A drop the next frame takes reads the drop's own position, not a pointer the next files have moved, and the files the OS holds over the window in that pass start a session once the drop ends the old one. The files' pointer is the system pointer where the platform tells one, else the pass's own: the drag's noted source pointer is from the pass before. --- crates/ui-contract/src/runtime/drag.rs | 88 ++++++++++++++++++-------- 1 file changed, 61 insertions(+), 27 deletions(-) diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index bfe015694..30dfc6f6a 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -260,6 +260,12 @@ struct Session { dropped: Option, /// A file drop has arrived but no pointer position is available yet. waiting_for_pointer: bool, + /// Where the OS dropped the files: the pass that takes a drop after the frame of its arrival places it there, not + /// at a pointer that has moved on (files hovering again for a drag of their own). + dropped_at: Option, + /// Files the OS holds over the window in the pass that takes this session's drop: a drag of their own, which + /// starts when the drop ends this session (`end_pass`). + hovering_next: Vec, /// The root frame the session started in, the only one in which [`amend`] changes its payload. began: u64, } @@ -364,6 +370,8 @@ pub fn start( os: false, dropped: None, waiting_for_pointer: false, + dropped_at: None, + hovering_next: Vec::new(), began, }); board.ended = None; @@ -489,8 +497,7 @@ fn os_files(ctx: &Context) { let hovering = !seen.hovered.is_empty(); // A session whose window closed has no pass left to end it. let closed = source_viewport(ctx).is_some_and(|window| !pass::live_viewports(ctx).contains(&window)); - let host = WindowHost::of(ctx); - let position = if host.desktop_pointer().is_some() { host.pointer_in(viewport) } else { pointer::frame_raw(ctx).pos }; + let position = os_files_pointer(ctx, viewport, pointer::frame_raw(ctx).pos); let positioned = position.is_some(); // A window target can take the drop immediately only if the pointer has not moved since resolution. let window_winner = PerViewport::::with(ctx, viewport, |targets| targets.winner_window && targets.pointer == position); @@ -501,23 +508,11 @@ fn os_files(ctx: &Context) { if has_drop { repaint = true; } - board.session = Some(Session { - source: Id::NULL.with("craft_ui::os_files"), - moving: Moving::default(), - viewport, - button: PointerButton::Primary, - payload: Arc::new(OsFiles { files: if has_drop { seen.dropped } else { seen.hovered } }), - also: Vec::new(), - preview: DragPreview::None, - env: None, - mark: None, - released: None, - taken: false, - os: true, - dropped: (has_drop && positioned).then_some(frame.saturating_add(1)), - waiting_for_pointer: has_drop && !positioned, - began: frame, - }); + let mut session = os_session(if has_drop { seen.dropped } else { seen.hovered }, viewport, frame); + session.dropped = (has_drop && positioned).then_some(frame.saturating_add(1)); + session.dropped_at = position.filter(|_| has_drop); + session.waiting_for_pointer = has_drop && !positioned; + board.session = Some(session); board.ended = None; board.started += 1; } @@ -527,6 +522,7 @@ fn os_files(ctx: &Context) { let files = seen.dropped.into_iter().map(|file| with_hovered_type(file, hovered)).collect(); session.payload = Arc::new(OsFiles { files }); session.viewport = viewport; + session.dropped_at = position; if window_winner { session.dropped = Some(frame); } else if positioned { @@ -540,9 +536,13 @@ fn os_files(ctx: &Context) { // Targets register this pass and take the drop in the next, after their winner is resolved. session.waiting_for_pointer = false; session.dropped = Some(frame.saturating_add(1)); + session.dropped_at = position; repaint = true; } else if hovering { session.viewport = viewport; + if session.dropped == Some(frame) { + session.hovering_next = seen.hovered; + } } else if (session.viewport == viewport || closed) && !seen.reading && !session.waiting_for_pointer @@ -560,6 +560,29 @@ fn os_files(ctx: &Context) { } } +/// A session of `files` the OS holds over `viewport`, started in root frame `frame`. +fn os_session(files: Vec, viewport: ViewportId, frame: u64) -> Session { + Session { + source: Id::NULL.with("craft_ui::os_files"), + moving: Moving::default(), + viewport, + button: PointerButton::Primary, + payload: Arc::new(OsFiles { files }), + also: Vec::new(), + preview: DragPreview::None, + env: None, + mark: None, + released: None, + taken: false, + os: true, + dropped: None, + waiting_for_pointer: false, + dropped_at: None, + hovering_next: Vec::new(), + began: frame, + } +} + /// `file` with the media type the OS gave the hovered file at the same path, which egui does not repeat on a drop. fn with_hovered_type(mut file: OsFile, hovered: Option<&OsFiles>) -> OsFile { let held = hovered.and_then(|hovered| hovered.files.iter().find(|held| held.path.is_some() && held.path == file.path)); @@ -588,12 +611,22 @@ pub fn cross_window_pointer(ctx: &Context, viewport: ViewportId) -> Option } /// The pointer of the running session in screen space, whatever its payload: the pointer `dragging_of` pairs with a -/// payload, where the button went up in the pass of its release (`PointerFrame::pick_pos`). `None` without a session or -/// a pointer. +/// payload, where the button went up in the pass of its release (`PointerFrame::pick_pos`); for an OS drop, where the +/// files were dropped in the pass that takes it. `None` without a session or a pointer. pub(crate) fn session_pointer(ctx: &Context) -> Option { - let os = board(ctx, |board| board.session.as_ref().map(|session| session.os))?; - let host = WindowHost::of(ctx); - if os && host.desktop_pointer().is_some() { host.pointer_in(pass::current_viewport(ctx)) } else { pointer::frame_raw(ctx).pick_pos } + let frame = pass::root_frame_nr(ctx); + let (os, dropped_at) = + board(ctx, |board| board.session.as_ref().map(|session| (session.os, session.dropped_at.filter(|_| session.dropped == Some(frame)))))?; + let own = pointer::frame_raw(ctx).pick_pos; + if os { dropped_at.or_else(|| os_files_pointer(ctx, pass::current_viewport(ctx), own)) } else { own } +} + +/// The pointer of OS files over `viewport`: the system pointer where the platform tells one, since the OS sends the +/// window no pointer events while it drags files over it; else `own`, the pass's own pointer. A drag's noted source +/// pointer (`windows::note_source_pointer`) is from the pass before, for the other windows, so it never stands in for +/// the pass's own. +fn os_files_pointer(ctx: &Context, viewport: ViewportId, own: Option) -> Option { + if windows::system_pointer(ctx).is_some() { WindowHost::of(ctx).pointer_in(viewport) } else { own } } /// The running session's payload whose type is `payload` and the pointer in screen space. For files the OS drags, the @@ -799,8 +832,7 @@ pub(crate) fn ended(ctx: &Context, source: Id) -> Option released + 1); let ended_here = is_source && !held && session.released.is_none(); if expired || (ended_here && !foreign_target) { - board.session = None; + let next = std::mem::take(&mut session.hovering_next); + board.session = (!next.is_empty()).then(|| os_session(next, viewport, frame)); + board.started += u64::from(board.session.is_some()); } else if ended_here { session.released = Some(frame); } From 3b200f43d66b3273f5d42ef55235747ac5e1f789 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 03:28:05 +0000 Subject: [PATCH 03/16] text: a one-line field pastes each line ending as a space again; the editor's step loop is its own function The merge of next (b138b533fe) dropped one_line from the paste when it took the step loop. Moving the loop out of TextEditor::update keeps the update under clippy's cognitive complexity limit. --- crates/text/src/ui/editor.rs | 139 ++++++++++++++++++++--------------- 1 file changed, 80 insertions(+), 59 deletions(-) diff --git a/crates/text/src/ui/editor.rs b/crates/text/src/ui/editor.rs index 29a7d6b94..93a9a5ee6 100644 --- a/crates/text/src/ui/editor.rs +++ b/crates/text/src/ui/editor.rs @@ -376,6 +376,11 @@ impl EditorMode { } } +/// `text` on one line: each line ending (`\r\n`, `\r` or `\n`) becomes one space. +fn one_line(text: &str) -> String { + text.replace("\r\n", " ").replace(['\r', '\n'], " ") +} + /// What the editor did this pass. #[derive(Debug)] #[non_exhaustive] @@ -572,6 +577,80 @@ fn show_i_beam(cx: &mut Cx<'_, TextEditor<'_>>, phase: &PressPhase, vertical: bo } } +/// Applies one pass's editor steps to `edits` in order: typing, the marked text, moves, deletes, selections, the edit +/// commands and the commands keys fired. Returns the text a Copy or Cut put on the clipboard, and whether a command +/// asked for the character panel. +fn apply_steps( + edits: &mut Edits<'_>, + steps: Vec>, + mode: EditorMode, + masked: bool, + pasted: Option<&str>, + fallback: Rect, +) -> (Option, bool) { + let mut copied: Option = None; + let mut ending: Option> = None; + let mut character_panel = false; + for step in steps { + // A commit or cancel ends the session; an input method's committed text still lands. + if (edits.done.commit || edits.done.cancel) && ending.is_none() { + break; + } + let input = match step { + EditorStep::Input(input) => input, + EditorStep::Command(command, _) => { + edits.command(command, &mut character_panel); + continue; + } + _ => continue, + }; + if let Some(range) = ending.take() { + if let EditorInput::Text(text) = &input { + edits.commit_marked(range, text); + continue; + } + edits.drop_marked(range); + } + match input { + EditorInput::Preedit { text, cursor, .. } => { + let active = cursor.map(|bytes| byte_range_to_chars(&text, bytes)); + ending = edits.preedit(&text, active); + } + EditorInput::ImeCommit => ending = edits.session.preedit.take(), + EditorInput::Text(text) => edits.done.changed |= edits.insert_typed(&text), + EditorInput::Newline { .. } if edits.session.preedit.is_none() && mode.multiline() => { + edits.done.changed |= edits.insert_text("\n", EditKind::Typed); + } + EditorInput::Tab if mode.takes_tab() => edits.done.changed |= edits.insert_text("\t", EditKind::Typed), + EditorInput::Move(step, mods) => edits.motion(step, mods), + EditorInput::Delete { forward, by, .. } => edits.done.changed |= edits.delete(forward, by), + EditorInput::DeleteSurrounding { before, after, unit, .. } => edits.done.changed |= edits.delete_around(before, after, unit), + EditorInput::Select { anchor, focus, .. } => { + let lines = lines_of(&mut *edits.host, fallback); + edits.end_composition(); + edits.selection = TextSelection { anchor: char_at(&lines, anchor), caret: char_at(&lines, focus) }; + } + EditorInput::Edit(EditCommand::SelectAll) => edits.select_all(), + EditorInput::Edit(EditCommand::Copy) if !masked => copied = edits.selected_text(), + EditorInput::Edit(EditCommand::Cut) if !masked => { + copied = edits.selected_text(); + edits.done.changed |= edits.delete_selection(); + } + EditorInput::Edit(EditCommand::Paste) => { + if let Some(text) = pasted { + let text = if mode.multiline() { text.to_string() } else { one_line(text) }; + edits.done.changed |= edits.insert_text(&text, EditKind::Pasted); + } + } + _ => {} + } + } + if let Some(range) = ending { + edits.drop_marked(range); + } + (copied, character_panel) +} + /// 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<'_>>, steps: &[EditorStep]) -> Option> { if !steps.iter().any(|step| matches!(step, EditorStep::Input(EditorInput::Edit(EditCommand::Paste)))) { @@ -636,7 +715,6 @@ impl Component for TextEditor<'_> { let now = cx.now(); let pasted = pasted_text(cx, &steps); let (mode, masked) = (self.mode, self.masked); - let mut copied: Option = None; let mut session = std::mem::take(cx.memory::()); let mut edits = Edits { host: &mut *self.host, @@ -652,64 +730,7 @@ impl Component for TextEditor<'_> { edits.reconcile(); let fallback = space.doc_rect(cx.rect); - let mut ending: Option> = None; - let mut character_panel = false; - for step in steps { - // A commit or cancel ends the session; an input method's committed text still lands. - if (edits.done.commit || edits.done.cancel) && ending.is_none() { - break; - } - let input = match step { - EditorStep::Input(input) => input, - EditorStep::Command(command, _) => { - edits.command(command, &mut character_panel); - continue; - } - _ => continue, - }; - if let Some(range) = ending.take() { - if let EditorInput::Text(text) = &input { - edits.commit_marked(range, text); - continue; - } - edits.drop_marked(range); - } - match input { - EditorInput::Preedit { text, cursor, .. } => { - let active = cursor.map(|bytes| byte_range_to_chars(&text, bytes)); - ending = edits.preedit(&text, active); - } - EditorInput::ImeCommit => ending = edits.session.preedit.take(), - EditorInput::Text(text) => edits.done.changed |= edits.insert_typed(&text), - EditorInput::Newline { .. } if edits.session.preedit.is_none() && mode.multiline() => { - edits.done.changed |= edits.insert_text("\n", EditKind::Typed); - } - EditorInput::Tab if mode.takes_tab() => edits.done.changed |= edits.insert_text("\t", EditKind::Typed), - EditorInput::Move(step, mods) => edits.motion(step, mods), - EditorInput::Delete { forward, by, .. } => edits.done.changed |= edits.delete(forward, by), - EditorInput::DeleteSurrounding { before, after, unit, .. } => edits.done.changed |= edits.delete_around(before, after, unit), - EditorInput::Select { anchor, focus, .. } => { - let lines = lines_of(&mut *edits.host, fallback); - edits.end_composition(); - edits.selection = TextSelection { anchor: char_at(&lines, anchor), caret: char_at(&lines, focus) }; - } - EditorInput::Edit(EditCommand::SelectAll) => edits.select_all(), - EditorInput::Edit(EditCommand::Copy) if !masked => copied = edits.selected_text(), - EditorInput::Edit(EditCommand::Cut) if !masked => { - copied = edits.selected_text(); - edits.done.changed |= edits.delete_selection(); - } - EditorInput::Edit(EditCommand::Paste) => { - if let Some(text) = &pasted { - edits.done.changed |= edits.insert_text(text, EditKind::Pasted); - } - } - _ => {} - } - } - if let Some(range) = ending { - edits.drop_marked(range); - } + let (copied, character_panel) = apply_steps(&mut edits, steps, mode, masked, pasted.as_deref(), fallback); // A press is the pass's last pointer event (H0), so the pass's editor input came before it. match press.phase { PressPhase::Down { start, .. } if start.button == craft_behavior::PointerButton::Primary => { From 8ef406cd5d04a983e6c47a805101ef25e991bfe4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 03:28:05 +0000 Subject: [PATCH 04/16] ui-widgets: a tile grid that takes its width from its content asks for at least one card again The merge of next (b138b533fe) brought back the early zero width that ebf9254522 removed, so a measured stack lost the grid's rows and what follows them. The selectable-text trial names its canvas with Id::unique. --- crates/ui-widgets/src/tile_grid/grid.rs | 3 --- crates/ui-widgets/tests/it/text/selectable.rs | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/ui-widgets/src/tile_grid/grid.rs b/crates/ui-widgets/src/tile_grid/grid.rs index 36961bf62..07d0c57aa 100644 --- a/crates/ui-widgets/src/tile_grid/grid.rs +++ b/crates/ui-widgets/src/tile_grid/grid.rs @@ -1042,9 +1042,6 @@ impl Collection for TileGrid<'_, K /// The last layout again while the width, the rows stamp and everything the arrangement reads are the same. fn ideal_width(&self, item: Option, _rows: usize, cx: &StyleCx<'_>) -> f32 { - if self.card_columns == 0 { - return 0.0; - } let style = GridSizes::of(cx, self.card, self.card_text, self.items.row_height, self.regular_card_padding, self.action_place); let aspect = if self.aspect.is_finite() && self.aspect > 0.0 { self.aspect } else { 1.0 }; let around = style.around.get(self.caption, self.detail_line); diff --git a/crates/ui-widgets/tests/it/text/selectable.rs b/crates/ui-widgets/tests/it/text/selectable.rs index c471d839b..ecc76542b 100644 --- a/crates/ui-widgets/tests/it/text/selectable.rs +++ b/crates/ui-widgets/tests/it/text/selectable.rs @@ -153,7 +153,7 @@ fn metadata_value_copies_without_selecting_the_row() { fn tab_toggles_the_panels_from_read_only_text_a_press_or_drag_focused() { let text = Rc::new(Cell::new(Id::NULL)); let seen = text.clone(); - let canvas = Id::new("document canvas"); + let canvas = Id::unique("document canvas"); let mut fixture = Fixture::new(move |ui| { Button::new("Save").show(ui); seen.set(SelectableText::new("Path", "/projects/poster.indd").show(ui).id); From c13c6eeed5d059b870a1498e325be7409bfabe02 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 03:28:05 +0000 Subject: [PATCH 05/16] docs: regenerate the components index --- docs/components-index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/components-index.md b/docs/components-index.md index 2a3c0638f..a0bbf32a2 100644 --- a/docs/components-index.md +++ b/docs/components-index.md @@ -236,7 +236,7 @@ Grouped by gallery level, then shape, then name. | `Watermark` | Pattern | `craft_ui_patterns::patterns::form_dialogs::watermark` | The watermark rows of an export dialog: Style (Text, Graphic), the text field or the image path with Choose…, Orientation, Position as the 3 by 3 reference point, Rotation, Size, Opacity, Inset X and Y, and Shadow | | `WindowMenuRows` | Pattern | `craft_ui_panels::docking::window_menu` | One check row per panel in the order the app gives, for a Window menu | | `WorkspaceSwitcher` | Pattern | `craft_ui_patterns::patterns::dock::switcher` | The switcher at the end of an options bar: a small select showing the current workspace's name | -| `ZoomField` | Pattern | `craft_ui_widgets::text::zoom_field` | A zoom field: a `NumberField` over the view's zoom in percent on its [`ZoomScale`] (device pixels unless set), with the zoom codec and the zoom ladder's range | +| `ZoomField` | Pattern | `craft_ui_widgets::text::zoom_field` | A zoom field: a `NumberField` over the view's zoom in percent on its [`ZoomScale`] (device pixels unless set), with the zoom codec and the zoom scheme's range | | `RecoveryDialog` | Dialog | `craft_ui_panels::dialog::recovery` | Recover Unsaved Work, one document at a time: a prompt saying when the document was autosaved, with Discard and Recover (the accepting answer) | ### Shells @@ -273,7 +273,7 @@ Grouped by gallery level, then shape, then name. | `craft_behavior::eviction` | When a component's remembered state is due for eviction | | `craft_behavior::fit` | The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu | | `craft_behavior::flow` | `Insets`, `Flow` and `Axis`: start and end geometry resolved once for the layout direction | -| `craft_behavior::focus` | Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, focus after removal, the Escape order and the focus-on-press kinds | +| `craft_behavior::focus` | Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, the Escape order and the focus-on-press kinds | | `craft_behavior::frame_step` | The step of one pass of motion: a Hand glide, a held Zoom press and an autoscroll integrate over it | | `craft_behavior::grid` | The `Grid` cursor: columns resolved from last pass's measurements, and the cell each child takes | | `craft_behavior::hit` | Hit shapes, their priority and the arena's resolve rule (8.3) | From 9750fe6d77d16a8b014a37a4755767cdfddc50e2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 03:41:37 +0000 Subject: [PATCH 06/16] i18n: the region test module builds only where its one test runs --- crates/i18n/src/region.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/i18n/src/region.rs b/crates/i18n/src/region.rs index f34cac506..9f1559913 100644 --- a/crates/i18n/src/region.rs +++ b/crates/i18n/src/region.rs @@ -389,11 +389,10 @@ fn read_system() -> Region { Region::from_tag(&sys_locale::get_locale().unwrap_or_default()) } -#[cfg(test)] +#[cfg(all(test, unix, not(any(target_vendor = "apple", target_os = "android"))))] mod tests { use super::*; - #[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))] #[test] fn each_locale_category_decides_its_own_part_and_lc_all_all_of_them() { let env = From eaeb0fa0283a24b0fcdad77ea3705b150db37b8e Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 04:02:17 +0000 Subject: [PATCH 07/16] platform: owner_only's docs name its Windows-only functions as code, not links From storytold/craft-libs#3236, so this PR's Workspace docs check can pass. Co-authored-by: skylartaylor --- crates/platform/src/owner_only.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/platform/src/owner_only.rs b/crates/platform/src/owner_only.rs index 506907e03..e664dcffe 100644 --- a/crates/platform/src/owner_only.rs +++ b/crates/platform/src/owner_only.rs @@ -2,23 +2,23 @@ //! //! On Windows a file created in a folder inherits the folder's access list, and folders such as //! a new folder at a drive root, `C:\Users\Public` or `C:\ProgramData` let every signed-in user -//! read what is created in them. [`restrict_to_owner`] replaces the whole list with the current -//! user and SYSTEM only, makes that user the owner, and checks the result. [`create_private_dir`] +//! read what is created in them. `restrict_to_owner` replaces the whole list with the current +//! user and SYSTEM only, makes that user the owner, and checks the result. `create_private_dir` //! does the same for a new folder whose list the files created in it inherit, so a file can be -//! private from the moment it exists. [`read_with_sddl`] reads a file and its security descriptor +//! private from the moment it exists. `read_with_sddl` reads a file and its security descriptor //! through one handle. [`foreign_access`] reads the descriptor in SDDL form, which names accounts //! by SID and so reads the same in every Windows language, and says why another user could have //! written or could read the file. They run the tools Windows ships rather than calling the //! security API directly, which would need `unsafe`. /// Why the file whose security descriptor is `sddl` (`O:` owner and `D:` access list, in SDDL or -/// as [`read_with_sddl`] writes it) can't be trusted as user `me`'s own: it is owned by someone else, it has no +/// as `read_with_sddl` writes it) can't be trusted as user `me`'s own: it is owned by someone else, it has no /// access list (everyone may use it), or it lets an account other than `me` or SYSTEM use it. /// Accounts are compared by SID; `None` means it is `me`'s alone. /// /// Stricter than OpenSSH's rule for private keys, which also lets Administrators in: an entry for /// the Administrators group would let another administrator read the token without taking the -/// file over. [`restrict_to_owner`] never grants it, so the app's own file always passes; a file +/// file over. `restrict_to_owner` never grants it, so the app's own file always passes; a file /// that inherited it from a user's folder is refused. pub fn foreign_access(sddl: &str, me: &str) -> Option { let me = me.trim(); From 52503acd71e159867795275d7214df6b64e24239 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 00:23:15 +0100 Subject: [PATCH 08/16] Fix the macOS test failures next picked up from the PdfCraft framework sync (#3232) - atomic: a file the user may write but not read (mode 0200) saves again on macOS; its extended attributes can't be read, so there are none to keep. - menu, ui-shell, pages, ui-contract, ui-canvas tests: follow the macOS conventions the code already has. The in-window bar test pins its target as the other bar tests do; macOS has no Menu key and no Cmd+Home/End move; its platform copy key is Option; a press with Control there is a secondary click, so Control comes after the press. --- crates/atomic/src/lib.rs | 7 ++++--- crates/menu/tests/it/bar.rs | 3 +++ crates/pages/tests/it/views.rs | 11 +++++------ crates/ui-canvas/tests/it/canvas/crop.rs | 9 ++++++++- crates/ui-contract/tests/it/collection/drops.rs | 6 ++++-- crates/ui-shell/tests/it/shell/start.rs | 8 +++++--- 6 files changed, 29 insertions(+), 15 deletions(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 2fa589d09..c417eec67 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -548,8 +548,9 @@ const MAX_XATTR_TOTAL_BYTES: usize = 64 * 1024 * 1024; /// binding, quarantine, resource forks) to the stage. The attributes are as untrusted as the /// bytes, so the reads are bounded; one that cannot be read or written whole, or passes a bound, /// refuses the save rather than dropping the user's metadata unnoticed. Only a volume without -/// extended attributes (`ENOTSUP`) is skipped. `com.apple.provenance` belongs to macOS, which -/// gives the new file its own. Compression bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`). +/// extended attributes (`ENOTSUP`) and a file the user may write but not read (mode 0200, whose +/// attributes the user can't read either) are skipped; those save as they did before attributes +/// were kept. `com.apple.provenance` belongs to macOS, which gives the new file its own. Compression bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`). #[cfg(target_os = "macos")] fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { use rustix::fs::{Mode, OFlags, XattrFlags, fgetxattr, fgetxattr_query, flistxattr, fsetxattr, open}; @@ -559,7 +560,7 @@ fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { // names another file. NONBLOCK keeps a FIFO put at the name from hanging the open. let source = match open(target, OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK, Mode::empty()) { Ok(fd) => File::from(fd), - Err(Errno::NOENT | Errno::LOOP) => return Ok(()), + Err(Errno::NOENT | Errno::LOOP | Errno::ACCESS) => return Ok(()), Err(e) => return Err(e.into()), }; if !source.metadata()?.is_file() { diff --git a/crates/menu/tests/it/bar.rs b/crates/menu/tests/it/bar.rs index 071ae4684..efe960a13 100644 --- a/crates/menu/tests/it/bar.rs +++ b/crates/menu/tests/it/bar.rs @@ -1,5 +1,6 @@ //! The in-window bar's own rules over the model. +use craft_host::target::Os; use craft_menu::{Item, Menu, MenuBar, MenuBarUi, Node}; use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, trial}; @@ -18,6 +19,8 @@ fn a_disabled_submenu_is_greyed_and_does_not_open() { let mut fixture = Fixture::new(move |ui| { MenuBarUi::new(&bar).show(ui); }); + // The in-window bar's rules; a Mac's menus are in the system bar. + fixture.os(Os::Linux); fixture.settle(); let Some(file) = fixture.by_label("File") else { panic!("the bar shows File") }; fixture.click(&file).settle(); diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index e4e60c79a..e0aa1babf 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -1007,12 +1007,11 @@ fn shift_and_command_with_the_page_keys_and_arrows_go_to_the_ends() { ); focus_canvas(&mut fixture); let keys = [(Key::PageDown, both, 4), (Key::PageUp, both, 0), (Key::ArrowDown, both, 4), (Key::ArrowUp, both, 0)]; - let ends = [ - (Key::End, Modifiers::SHIFT, 4), - (Key::Home, Modifiers::SHIFT, 0), - (Key::End, Modifiers::COMMAND, 4), - (Key::Home, Modifiers::COMMAND, 0), - ]; + // Off macOS Ctrl+End and Ctrl+Home go to the ends too; macOS gives Cmd with Home and End no move. + let mut ends = vec![(Key::End, Modifiers::SHIFT, 4), (Key::Home, Modifiers::SHIFT, 0)]; + if !cfg!(target_os = "macos") { + ends.extend([(Key::End, Modifiers::COMMAND, 4), (Key::Home, Modifiers::COMMAND, 0)]); + } for (key, mods, want) in keys.into_iter().chain(ends) { fixture.key(key, mods); fixture.idle(2); diff --git a/crates/ui-canvas/tests/it/canvas/crop.rs b/crates/ui-canvas/tests/it/canvas/crop.rs index d2b6a8b73..69b91085d 100644 --- a/crates/ui-canvas/tests/it/canvas/crop.rs +++ b/crates/ui-canvas/tests/it/canvas/crop.rs @@ -451,6 +451,7 @@ fn a_quick_drag_in_one_frame_starts_at_the_press() { assert_eq!((events.first(), events.last()), (Some(&"begin"), Some(&"commit")), "{events:?}"); } +/// Control is pressed once the resize has started: on macOS a press with Control held is a secondary click. #[trial] fn the_control_key_held_during_a_resize_turns_snapping_off() { for (held, right) in [(Modifiers::NONE, 310.0), (Modifiers::CTRL, 307.0)] { @@ -459,7 +460,13 @@ fn the_control_key_held_during_a_resize_turns_snapping_off() { s.snap_x = Some(310.0); s }); - rig.drag(rig.at(300.0, 220.0), rig.at(307.0, 220.0), held); + let (from, to) = (rig.at(300.0, 220.0), rig.at(307.0, 220.0)); + rig.press(from); + rig.frames.hold(held); + rig.move_to(from.lerp(to, 0.5)); + rig.move_to(to); + rig.release(to); + rig.frames.hold(Modifiers::NONE); assert!((rig.rect().x1 - right).abs() < 1e-6, "{held:?}: {:?}", rig.rect()); } } diff --git a/crates/ui-contract/tests/it/collection/drops.rs b/crates/ui-contract/tests/it/collection/drops.rs index 331ba96bf..ec8c2179b 100644 --- a/crates/ui-contract/tests/it/collection/drops.rs +++ b/crates/ui-contract/tests/it/collection/drops.rs @@ -137,13 +137,15 @@ fn rows_from_another_list_drop_into_a_gap_only_where_a_kind_takes_them() { } /// A list's copy keys decide which held key makes its own row drag a copy, and the pointer over it shows the copy -/// while they are held: off macOS Ctrl for the platform's keys, Alt for Alt; the other key moves. +/// while they are held: the platform's keys copy with Ctrl off macOS and Option on it, Alt copies with Alt; the other +/// key moves. #[trial] fn a_lists_copy_keys_pick_the_key_that_copies_its_rows() { use craft_behavior::{CopyKeys, Cursor, CursorIcon}; use egui::Modifiers; let ctrl = Modifiers::CTRL | Modifiers::COMMAND; - for (keys, copies, moves) in [(CopyKeys::Platform, ctrl, Modifiers::ALT), (CopyKeys::Alt, Modifiers::ALT, ctrl)] { + let platform = if cfg!(target_os = "macos") { (Modifiers::ALT, ctrl) } else { (ctrl, Modifiers::ALT) }; + for (keys, copies, moves) in [(CopyKeys::Platform, platform.0, platform.1), (CopyKeys::Alt, Modifiers::ALT, ctrl)] { for (held, copy) in [(copies, true), (moves, false)] { let words = Words::flat(&["a", "b", "c", "d"]); let run = Run::default(); diff --git a/crates/ui-shell/tests/it/shell/start.rs b/crates/ui-shell/tests/it/shell/start.rs index c53a8cb9a..32b596852 100644 --- a/crates/ui-shell/tests/it/shell/start.rs +++ b/crates/ui-shell/tests/it/shell/start.rs @@ -196,8 +196,8 @@ fn a_recent_row_names_its_full_path_and_reveals_remove_on_hover_or_focus() { assert!(log.borrow().contains(&StartAction::ClearRecent), "Clear reports ClearRecent: {:?}", log.borrow()); } -/// A recent file's menu offers Show in Folder exactly where the platform can reveal a file, and the menu key and -/// Shift+F10 open it from the focused card. The menu is told by "Clear Recent Files", which only the menu has: the +/// A recent file's menu offers Show in Folder exactly where the platform can reveal a file, and the menu key (off +/// macOS, which has none) and Shift+F10 open it from the focused card. The menu is told by "Clear Recent Files", which only the menu has: the /// card's hover action carries "Remove from Recent" too. #[trial] fn the_recent_menu_offers_show_in_folder_where_the_platform_can_reveal() { @@ -213,7 +213,9 @@ fn the_recent_menu_offers_show_in_folder_where_the_platform_can_reveal() { assert!(fixture.by_label(MENU_ONLY).is_some(), "a right click on a recent file opens its menu"); assert_eq!(fixture.by_label("Show in Folder").is_some(), craft_platform::open::CAN_REVEAL); - for (key, modifiers) in [(Key::Menu, Modifiers::NONE), (Key::F10, Modifiers::SHIFT)] { + let keys: &[(Key, Modifiers)] = + if cfg!(target_os = "macos") { &[(Key::F10, Modifiers::SHIFT)] } else { &[(Key::Menu, Modifiers::NONE), (Key::F10, Modifiers::SHIFT)] }; + for &(key, modifiers) in keys { fixture.key(Key::Escape, Modifiers::NONE).idle(3); assert!(fixture.by_label(MENU_ONLY).is_none(), "Escape closes the menu before {key:?}"); let card = fixture.by_label("Poster.psd").expect("the card shows"); From f29372d28066eb09c0184616a8e39941d6780b69 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 00:58:10 +0100 Subject: [PATCH 09/16] atomic: an unreadable file saves only when it has no attributes to lose (review) When the old file can't be opened for reading, its attribute names are listed by path: none (or only com.apple.provenance) lets the save go on; any other refuses it, since they can't be copied without the file. --- crates/atomic/src/lib.rs | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index c417eec67..da11bf153 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -548,9 +548,11 @@ const MAX_XATTR_TOTAL_BYTES: usize = 64 * 1024 * 1024; /// binding, quarantine, resource forks) to the stage. The attributes are as untrusted as the /// bytes, so the reads are bounded; one that cannot be read or written whole, or passes a bound, /// refuses the save rather than dropping the user's metadata unnoticed. Only a volume without -/// extended attributes (`ENOTSUP`) and a file the user may write but not read (mode 0200, whose -/// attributes the user can't read either) are skipped; those save as they did before attributes -/// were kept. `com.apple.provenance` belongs to macOS, which gives the new file its own. Compression bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`). +/// extended attributes (`ENOTSUP`) is skipped, and so is a file whose data the user may not read +/// (mode 0200) when it has no attribute names the user can list either; one whose names can be +/// listed refuses the save, as its attributes can't be copied without its data. +/// `com.apple.provenance` belongs to macOS, which gives the new file its own. Compression +/// bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`). #[cfg(target_os = "macos")] fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { use rustix::fs::{Mode, OFlags, XattrFlags, fgetxattr, fgetxattr_query, flistxattr, fsetxattr, open}; @@ -560,7 +562,8 @@ fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { // names another file. NONBLOCK keeps a FIFO put at the name from hanging the open. let source = match open(target, OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK, Mode::empty()) { Ok(fd) => File::from(fd), - Err(Errno::NOENT | Errno::LOOP | Errno::ACCESS) => return Ok(()), + Err(Errno::NOENT | Errno::LOOP) => return Ok(()), + Err(Errno::ACCESS) => return unreadable_has_no_attributes(target), Err(e) => return Err(e.into()), }; if !source.metadata()?.is_file() { @@ -596,6 +599,27 @@ fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { Ok(()) } +/// For a target whose data can't be opened for reading: `Ok` when it has no extended attribute the +/// user can list (or the volume has none), so the save loses nothing; otherwise refuse the save, as +/// the attributes can't be copied without opening the file. The names are read without following a +/// link, by path. +#[cfg(target_os = "macos")] +fn unreadable_has_no_attributes(target: &Path) -> io::Result<()> { + use rustix::fs::llistxattr; + use rustix::io::Errno; + let mut names = vec![0u8; MAX_XATTR_NAMES_BYTES]; + match llistxattr(target, names.as_mut_slice()) { + Ok(0) | Err(Errno::NOTSUP | Errno::ACCESS | Errno::NOENT) => Ok(()), + Ok(len) if names.get(..len).is_some_and(|names| names.split(|b| *b == 0).all(|name| name.is_empty() || name == b"com.apple.provenance")) => { + Ok(()) + } + Ok(_) | Err(Errno::RANGE) => { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "the file can't be read, so its extended attributes can't be copied")) + } + Err(e) => Err(e.into()), + } +} + /// Read one attribute value of `size` bytes (already within the bounds) with `read`, then ask /// its size again with `query_size`. A read that does not fill `size`, or a size that changed, /// is refused: a growing resource fork returns the prefix that fits instead of an error. From 1d281f38c1e1e9c6b58cd6e401689db0760ef6a2 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 01:48:07 +0100 Subject: [PATCH 10/16] atomic: a write-only file's unreadable attributes are dropped, as documented and tested (review) On macOS a mode-0200 file's owner can list none of its attribute names either, so they are dropped, as before attributes were kept. An ACL that denies the data but lets the names be listed still refuses the save. Both are now tested on macOS. Also: the pages key doc gives the macOS exception for Cmd+Home/End. --- crates/atomic/src/lib.rs | 15 +++++----- crates/atomic/tests/atomic_tests.rs | 46 +++++++++++++++++++++++++++++ crates/pages/src/ui/view.rs | 3 +- 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index da11bf153..5aa3c75cd 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -548,9 +548,10 @@ const MAX_XATTR_TOTAL_BYTES: usize = 64 * 1024 * 1024; /// binding, quarantine, resource forks) to the stage. The attributes are as untrusted as the /// bytes, so the reads are bounded; one that cannot be read or written whole, or passes a bound, /// refuses the save rather than dropping the user's metadata unnoticed. Only a volume without -/// extended attributes (`ENOTSUP`) is skipped, and so is a file whose data the user may not read -/// (mode 0200) when it has no attribute names the user can list either; one whose names can be -/// listed refuses the save, as its attributes can't be copied without its data. +/// extended attributes (`ENOTSUP`) is skipped. So is a file whose data the user may not read when +/// its attribute names can't be listed either, as with mode 0200: its attributes are dropped, as +/// before attributes were kept, since the user can't read them (or its bytes) at all. One whose +/// data is denied but whose names can be listed (an ACL that denies reading) refuses the save. /// `com.apple.provenance` belongs to macOS, which gives the new file its own. Compression /// bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`). #[cfg(target_os = "macos")] @@ -599,10 +600,10 @@ fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { Ok(()) } -/// For a target whose data can't be opened for reading: `Ok` when it has no extended attribute the -/// user can list (or the volume has none), so the save loses nothing; otherwise refuse the save, as -/// the attributes can't be copied without opening the file. The names are read without following a -/// link, by path. +/// For a target whose data can't be opened for reading: `Ok` when the user can list no extended +/// attribute names on it (none, only `com.apple.provenance`, none supported, or listing is denied too, +/// as for mode 0200, whose attributes are then dropped); otherwise refuse the save, as the attributes +/// can't be copied without opening the file. The names are read without following a link, by path. #[cfg(target_os = "macos")] fn unreadable_has_no_attributes(target: &Path) -> io::Result<()> { use rustix::fs::llistxattr; diff --git a/crates/atomic/tests/atomic_tests.rs b/crates/atomic/tests/atomic_tests.rs index b1da9be0a..fcafd2ca7 100644 --- a/crates/atomic/tests/atomic_tests.rs +++ b/crates/atomic/tests/atomic_tests.rs @@ -99,3 +99,49 @@ fn private_staging_preserves_existing_modes_after_callback() -> io::Result<()> { assert_no_temp(&d.0); Ok(()) } + +/// Extended attribute names on `path`, read by path. +#[cfg(target_os = "macos")] +fn xattr_names(path: &Path) -> Vec> { + let mut names = vec![0u8; 64 * 1024]; + let len = rustix::fs::listxattr(path, names.as_mut_slice()).unwrap_or(0); + names.truncate(len); + names.split(|b| *b == 0).filter(|n| !n.is_empty()).map(<[u8]>::to_vec).collect() +} + +/// A write-only file (mode 0200) saves: macOS lets its owner neither read its data nor list its +/// attributes, so its attributes are dropped, as before attributes were kept. +#[cfg(target_os = "macos")] +#[test] +fn a_write_only_file_saves_and_drops_the_attributes_it_cannot_read() -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("write_only_xattrs"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL)?; + rustix::fs::setxattr(&p, "com.craft.t", b"tag", rustix::fs::XattrFlags::empty())?; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o200))?; + atomic_write(&p, b"new")?; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600))?; + assert_eq!(std::fs::read(&p)?, b"new"); + assert!(!xattr_names(&p).iter().any(|n| n == b"com.craft.t"), "the unreadable attribute is dropped"); + Ok(()) +} + +/// A file whose data an ACL denies but whose attribute names can be listed is not replaced: its +/// attributes can't be copied without its data, and the save refuses rather than drop them. +#[cfg(target_os = "macos")] +#[test] +fn an_unreadable_file_with_listable_attributes_is_not_replaced() -> io::Result<()> { + let d = TempDir::new("acl_denied_xattrs"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL)?; + rustix::fs::setxattr(&p, "com.craft.t", b"tag", rustix::fs::XattrFlags::empty())?; + let denied = std::process::Command::new("/bin/chmod").arg("+a").arg("everyone deny read").arg(&p).status()?; + assert!(denied.success(), "the ACL is set"); + let result = atomic_write(&p, b"new"); + let _ = std::process::Command::new("/bin/chmod").arg("-N").arg(&p).status(); + assert!(result.is_err(), "the save is refused"); + assert_eq!(std::fs::read(&p)?, ORIGINAL, "the original is unchanged"); + assert!(xattr_names(&p).iter().any(|n| n == b"com.craft.t"), "and keeps its attribute"); + Ok(()) +} diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index 2fc10109b..0b08850bb 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -1544,7 +1544,8 @@ impl KeyMoves { /// Page Up and Down a screen less a key line (a row when not continuous, and with Cmd), Home and End the first /// and last page, Up and Down a key line (not continuous, a turn once the row is at its edge that way), Left and /// Right a key line sideways while the current page or spread has more to show that way, else a turn of a page or - /// spread; Cmd with Left or Right turns at once. Home and End with Shift or Cmd, and Page Up, Page Down, Up and + /// spread; Cmd with Left or Right turns at once. Home and End with Shift, or with Cmd off macOS (which gives Cmd + /// with them no move), and Page Up, Page Down, Up and /// Down with Shift and Cmd together, go to the first or last page; Alt, and Shift alone with the other keys, /// leave them to nothing. fn of( From 2eb195b88907079ebf8a837e48bbb1c331a85d6f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 17:45:08 +0700 Subject: [PATCH 11/16] ui-panels, dock area: DockConfig::column_cards (was rail_cards) shows every docked column as a card, expanded or collapsed to icons: surface.panel with shape.radius.surface corners on the dock's background, inset by space.gap.stack on top, bottom and at the window edge, and space.gap.tight between neighbouring cards; each column wider by its inset so its content keeps its width; group dividers stay inside the card; container surfaces keep to their layer's frame --- crates/ui-contract/src/primitives/surface.rs | 5 +- crates/ui-panels/src/docking/config.rs | 19 ++-- crates/ui-panels/src/docking/dock_column.rs | 103 ++++++++++-------- .../src/docking/dock_column/stories.rs | 44 ++++++-- crates/ui-panels/src/docking/iconic.rs | 29 ++++- .../ui-panels/src/docking/iconic/stories.rs | 32 +++++- crates/ui-panels/src/docking/spec.rs | 5 - crates/ui-panels/src/docking/targets.rs | 77 +++++++------ crates/ui-patterns/src/patterns/dock/area.rs | 54 +++++---- .../ui-patterns/tests/it/docking/columns.rs | 103 +++++++++++++++++- 10 files changed, 336 insertions(+), 135 deletions(-) diff --git a/crates/ui-contract/src/primitives/surface.rs b/crates/ui-contract/src/primitives/surface.rs index 1bf9a7a63..a220e4f83 100644 --- a/crates/ui-contract/src/primitives/surface.rs +++ b/crates/ui-contract/src/primitives/surface.rs @@ -136,9 +136,10 @@ impl SurfaceSlot { SurfaceSlot { painter, slot } } - /// Paints the surface `kind` over `rect`. + /// Paints the surface `kind` over `rect`, kept to its layer's frame ([`frame_surfaces`]). pub(crate) fn paint(&self, tokens: &UiTokens, kind: SurfaceKind, rect: Rect, direction: Direction) { - let shapes = Surface::shapes(&surface_style(tokens, kind), None, rect, Corners::All, direction, self.painter.pixels_per_point()); + let mut shapes = Surface::shapes(&surface_style(tokens, kind), None, rect, Corners::All, direction, self.painter.pixels_per_point()); + fit_to_frame(self.painter.ctx(), self.painter.layer_id(), &mut shapes); self.painter.set(self.slot, Shape::Vec(shapes)); } } diff --git a/crates/ui-panels/src/docking/config.rs b/crates/ui-panels/src/docking/config.rs index 4dccf3741..e2d19ff42 100644 --- a/crates/ui-panels/src/docking/config.rs +++ b/crates/ui-panels/src/docking/config.rs @@ -80,12 +80,13 @@ pub struct DockConfig { /// sides ([`FloatingGroup::rounded_body`](super::FloatingGroup)): a floating tool rail reads as one rounded piece. /// Off: the panels and rails inside paint their own square surfaces to the window's edge. pub floating_rounded_body: bool, - /// A docked column of a tool rail (a stepped column whose panel has a [`DockGrid::rail`](super::DockGrid::rail)) - /// shows as a card: inset by `space.gap.stack` on its outer, top and bottom sides, where the dock's background - /// shows, and painted `surface.panel` with `shape.radius.surface` corners and no frame. The column is wider by the - /// inset, so it keeps its steps; its dividers, drop bands and edge handle stay on its outer rect. Off: the column + /// Every docked column, expanded or collapsed to icons, shows as a card on the dock's `surface.background`: + /// painted `surface.panel` with `shape.radius.surface` corners and no frame, inset by `space.gap.stack` on its top + /// and bottom and, for the column at the window edge, on its outer side; each further column stands + /// `space.gap.tight` from its outer neighbour's card. A column is wider by its inset, so it keeps its content's + /// width (a tool rail its steps); its dividers, drop bands and edge handle stay on its outer rect. Off: a column /// fills its cell. - pub rail_cards: bool, + pub column_cards: bool, /// Shows a close button on the tabs of closable panels in docked and floating groups, where a middle click also /// closes them, for tabs that act as documents. Off: panels close from their menu. Accordion headers and iconic /// columns never show it. @@ -126,7 +127,7 @@ impl Default for DockConfig { close_button: true, floating_grip: false, floating_rounded_body: false, - rail_cards: false, + column_cards: false, tab_close_buttons: false, titled_headers: false, wheel_selects_tabs: false, @@ -245,10 +246,10 @@ impl DockConfig { self } - /// Docked tool rails as cards on or off ([`rail_cards`](Self::rail_cards)). + /// Docked columns as cards on or off ([`column_cards`](Self::column_cards)). #[must_use] - pub fn rail_cards(mut self, on: bool) -> Self { - self.rail_cards = on; + pub fn column_cards(mut self, on: bool) -> Self { + self.column_cards = on; self } diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 70511455e..3d3b0ecba 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -156,8 +156,7 @@ pub struct DockColumnStyle { #[style(metrics)] metrics: Metrics, sizes: DockSizes, - /// The card of a column shown as one ([`card`](DockColumn::card)): `surface.panel` with `shape.radius.surface` - /// corners and no edge. + /// The card of a column shown as one ([`card`](DockColumn::card)). card: SurfaceStyle, } @@ -198,10 +197,11 @@ pub struct DockColumn<'a, P: Value + Hash + 'static> { /// The rect the dock may grow within, which bounds how wide its inner edge can make the column. #[prop] within: Rect, - /// Whether a column of a tool rail shows as a card ([`DockConfig::rail_cards`](super::DockConfig::rail_cards)): - /// its bar and groups inset by the card's inset ([`DockSizes::card_inset`]) on its outer, top and bottom sides. + /// The inset on the outer side of the column's card, when it shows as one + /// ([`DockConfig::column_cards`](super::DockConfig::column_cards), [`DockSizes::card_inset`]): its bar and groups + /// sit inside the card, inset by that on its outer side and by [`DockSizes::card`] on its top and bottom. #[prop] - card: bool, + card: Option, /// The plan `parts` laid out this pass, which update, paint and access read. laid: Option, resized: Vec<(P, f32)>, @@ -225,7 +225,7 @@ impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { bar: ColumnBar::Own, arrow: ColumnArrow::Collapse, within: Rect::NOTHING, - card: false, + card: None, laid: None, resized: Vec::new(), width: None, @@ -258,8 +258,8 @@ impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { let shown = &mut bar; let body = move |ui: &mut Ui, body: &mut BodyCx<'_>| { let Some(style) = body.style::>() else { return }; - let sizes = DockSizes { rail_cards: card, ..style.sizes }; - let inner = card_rect(column, spec, body.rect, edge, body.env.direction().is_rtl(), &sizes); + let sizes = style.sizes; + let inner = card_rect(body.rect, card, &sizes, edge, body.env.direction().is_rtl()); if inner != body.rect { // The groups' own surfaces keep to the card's rounded corners. crate::primitives::frame_surfaces(ui, inner, style.card.radius); @@ -287,9 +287,12 @@ impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { } /// The divider on the column's inner edge, which moves between the width bounds of its panels, or of its steps - /// for a stepped column ([`stepped`](super::stepped)), whose host takes the width as whole steps. + /// for a stepped column ([`stepped`](super::stepped)), whose host takes the width as whole steps; a card's inset + /// on top. fn edge_divider(&self, rect: Rect, sizes: &DockSizes) -> Divider { let (least, most) = sizes.shown_bounds(self.column, self.spec); + let inset = self.card.unwrap_or(0.0); + let (least, most) = (least + inset, most + inset); Divider::column_edge(rect, self.edge, (least, most.min((self.within.width() - sizes.least_pane).max(rect.width()))), sizes.reach) } @@ -301,14 +304,9 @@ impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { } } - /// The sizes of `style` with the column's card on or off. - fn sizes(&self, style: &DockColumnStyle) -> DockSizes { - DockSizes { rail_cards: self.card, ..style.sizes } - } - /// Where the column's bar and groups sit in `rect`: inside its card, if it shows as one. fn inner(&self, rect: Rect, rtl: bool, sizes: &DockSizes) -> Rect { - card_rect(self.column, self.spec, rect, self.edge, rtl, sizes) + card_rect(rect, self.card, sizes, self.edge, rtl) } fn anchor(&self, group: usize) -> Option<&P> { @@ -316,13 +314,30 @@ impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { } } -/// The card of `column` in `rect`, the column's rect in a dock on the window edge `edge`: `rect` inset by the card's -/// inset ([`DockSizes::card_inset`]) on its outer side, the one towards `edge`, and on its top and bottom; `rect` for a -/// column that is no card. -fn card_rect

(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, rect: Rect, edge: DockEdge, rtl: bool, sizes: &DockSizes) -> Rect { - let inset = sizes.card_inset(column, spec); - let card = rect.shrink2(egui::vec2(0.0, inset)); - if (edge == DockEdge::Start) != rtl { card.with_min_x(card.left() + inset) } else { card.with_max_x(card.right() - inset) } +/// The card of a docked column in `rect`, the column's rect in a dock on the window edge `edge`: `rect` inset by +/// `card`, the card's outer inset ([`DockSizes::card_inset`]), on its outer side, the one towards `edge`, and by +/// [`DockSizes::card`] on its top and bottom; `rect` for a column that is no card. +pub(crate) fn card_rect(rect: Rect, card: Option, sizes: &DockSizes, edge: DockEdge, rtl: bool) -> Rect { + let Some(outer) = card else { return rect }; + let inner = rect.shrink2(egui::vec2(0.0, sizes.card)); + if (edge == DockEdge::Start) != rtl { inner.with_min_x(inner.left() + outer) } else { inner.with_max_x(inner.right() - outer) } +} + +/// The look of a docked column's card ([`DockConfig::column_cards`](super::DockConfig::column_cards)): `surface.panel` +/// with `shape.radius.surface` corners and no edge. +pub(crate) fn card_style(cx: &StyleCx<'_>) -> SurfaceStyle { + SurfaceStyle { radius: UiTokens::corner(cx.tokens.shape.radius.surface), edge: SurfaceEdge::None, shadow: None, ..cx.surface(SurfaceKind::Panel) } +} + +/// Paints a column in `rect` whose content sits in `card`: the card over the dock's background where the column is +/// one, else the column's panel surface. +pub(crate) fn paint_card(ui: &mut PaintUi<'_>, rect: Rect, card: Rect, style: &SurfaceStyle) { + if card == rect { + ui.draw().surface(rect, SurfaceKind::Panel, Corners::All); + } else { + ui.draw().surface(rect, SurfaceKind::Background, Corners::None); + ui.draw().surface_styled(card, style); + } } /// Where the groups of `column` sit in `rect`, the column's rect with its bar `bar`, as the column lays them out while @@ -398,6 +413,12 @@ impl Plan { /// The divider after each open group but the last: its part index (the group above it), its position among the open /// groups and the divider. + /// The room the dividers between the groups take in the column's `rect`: the body, inside the column's card if it + /// shows as one, in the frame of `rect` mirrored for right-to-left that dividers are declared in. + fn divider_room(&self, rect: Rect, rtl: bool) -> Rect { + Flow::new(rect, rtl).to_physical(self.body) + } + fn dividers(&self, rect: Rect, reach: f32) -> Vec<(u64, usize, Divider)> { let row = self.row(); self.open @@ -424,13 +445,7 @@ impl Component for DockColumn<'_, P> { } fn style(cx: &StyleCx<'_>, _: DockColumnStyleKey

) -> DockColumnStyle { - let card = SurfaceStyle { - radius: UiTokens::corner(cx.tokens.shape.radius.surface), - edge: SurfaceEdge::None, - shadow: None, - ..cx.surface(SurfaceKind::Panel) - }; - DockColumnStyle { metrics: Metrics::new(), sizes: DockSizes::style(cx), card } + DockColumnStyle { metrics: Metrics::new(), sizes: DockSizes::style(cx), card: card_style(cx) } } fn sense(&self) -> Sense { @@ -440,14 +455,14 @@ impl Component for DockColumn<'_, P> { /// The chevron at the bar's outer end, a divider between every two open groups and the inner edge's divider; a /// column in a floating window has the group dividers only. fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { - let sizes = self.sizes(cx.style); + let sizes = cx.style.sizes; let plan = column_plan(self.column, self.spec, self.inner(rect, cx.flow.is_rtl(), &sizes), self.bar, &sizes, |_, _| None); if self.bar == ColumnBar::Own && self.arrow.shown() { let (chevron, _) = bar_slots(plan.bar, self.edge, cx.flow.is_rtl()); let name = self.arrow.name(&cx.words::(), true); let _ = cx.part(CHEVRON, chevron).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); } - let dividers = plan.dividers(rect, sizes.reach); + let dividers = plan.dividers(plan.divider_room(rect, cx.flow.is_rtl()), sizes.reach); for (key, _, divider) in dividers { divider::declare(cx, rect, DIVIDER, key, ÷r); } @@ -458,14 +473,14 @@ impl Component for DockColumn<'_, P> { } fn update(&mut self, cx: &mut Cx<'_, Self>) { - let sizes = self.sizes(cx.style); + let sizes = cx.style.sizes; let (rect, rtl, ctx) = (cx.rect, cx.flow.is_rtl(), cx.core.ctx.clone()); let own = self.bar == ColumnBar::Own; self.collapse = own && self.arrow.shown() && cx.part_activated(CHEVRON).is_some(); let Some(base) = self.laid.take() else { return }; let inner = self.inner(rect, rtl, &sizes); let mut plan = column_plan(self.column, self.spec, inner, self.bar, &sizes, |key, divider| divider::pointer(cx, DIVIDER, key, divider)); - let dividers = base.dividers(rect, sizes.reach); + let dividers = base.dividers(base.divider_room(rect, rtl), sizes.reach); let keyed: Vec<(u64, Divider)> = dividers.iter().map(|(key, _, divider)| (*key, *divider)).collect(); if let Some((key, coord)) = divider::keys(cx, DIVIDER, &keyed, sizes.step, sizes.jump) && let Some((_, index, divider)) = dividers.iter().find(|(at, ..)| *at == key) @@ -496,17 +511,11 @@ impl Component for DockColumn<'_, P> { fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let Some(plan) = self.laid.as_ref() else { return }; // Painted here, not as the container's surface, which lies over what `paint` draws. - let card = self.inner(cx.rect, cx.flow.is_rtl(), &self.sizes(cx.style)); - let carded = card != cx.rect; - if carded { - // The card on the dock's background; the bar is part of the card. - ui.draw().surface(cx.rect, SurfaceKind::Background, Corners::None); - ui.draw().surface_styled(card, &cx.style.card); - } else { - ui.draw().surface(cx.rect, SurfaceKind::Panel, Corners::All); - } + let card = self.inner(cx.rect, cx.flow.is_rtl(), &cx.style.sizes); + paint_card(ui, cx.rect, card, &cx.style.card); if self.bar == ColumnBar::Own { - if !carded { + // A card's bar is part of the card. + if card == cx.rect { ui.draw().surface(plan.bar, SurfaceKind::Background, Corners::None); } if self.arrow.shown() { @@ -525,23 +534,23 @@ impl Component for DockColumn<'_, P> { return; } // A card has no frame. - if self.inner(cx.rect, cx.flow.is_rtl(), &self.sizes(cx.style)) == cx.rect { + if self.card.is_none() { ui.draw().surface(cx.rect, SurfaceKind::Frame, Corners::None); } for pair in plan.open.windows(2) { ui.face(DIVIDER.at(pair[0] as u64), Splitter::new(Axis::Y)); } // The edge's line lies on the column's inner edge, over the frame; its handle stays inside the column. - let (rect, edge) = (cx.rect, self.edge_divider(cx.rect, &self.sizes(cx.style))); + let (rect, edge) = (cx.rect, self.edge_divider(cx.rect, &cx.style.sizes)); let x = if cx.flow.is_rtl() { rect.right() - (edge.at - rect.left()) } else { edge.at }; ui.face(EDGE.at(0), Splitter::new(Axis::X).boundary(x)); } fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { let words = cx.words::(); - let sizes = self.sizes(cx.style); + let sizes = cx.style.sizes; let Some(plan) = self.laid.as_ref() else { return }; - for (key, _, divider) in plan.dividers(cx.rect, sizes.reach) { + for (key, _, divider) in plan.dividers(plan.divider_room(cx.rect, cx.flow.is_rtl()), sizes.reach) { divider::describe(access, DIVIDER, key, ÷r, words.resize.as_str(), sizes.step); } if self.bar == ColumnBar::Own { diff --git a/crates/ui-panels/src/docking/dock_column/stories.rs b/crates/ui-panels/src/docking/dock_column/stories.rs index 98b42d0ae..ef8d5f3b0 100644 --- a/crates/ui-panels/src/docking/dock_column/stories.rs +++ b/crates/ui-panels/src/docking/dock_column/stories.rs @@ -12,9 +12,12 @@ use craft_behavior::Flow; use craft_behavior::dock::{Column, Group}; use egui::{Ui, UiBuilder}; -/// The height of the rail card story's column. +/// The height of the card stories' columns. const CARD_HEIGHT: f32 = 160.0; +/// The width of the panel card story's column, before its card's inset. +const CARD_WIDTH: f32 = 240.0; + fn spec(panel: &u8) -> PanelSpec { PanelSpec::new(format!("Panel {panel}")) } @@ -44,9 +47,9 @@ fn in_a_floating_window(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { .into() } -/// A docked column of a tool rail shown as a card (`DockConfig::rail_cards`), at each rail density and one or two -/// steps: inset on its outer, top and bottom sides, where the dock's background shows, with its bar and its rail on -/// the rounded panel card. The column is wider than its steps by the inset. +/// A docked column of a tool rail at the window edge shown as a card (`DockConfig::column_cards`), at each rail density +/// and one or two steps: inset on its outer, top and bottom sides, where the dock's background shows, with its bar and +/// its rail on the rounded panel card. The column is wider than its steps by the inset. #[story(DockColumn<'static, u8>, covers = [], drive = Drive::Never)] fn a_tool_rail_card(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let density = *data.choice("density", RailDensity::Dense, &[("Regular", RailDensity::Regular), ("Dense", RailDensity::Dense)]); @@ -56,16 +59,41 @@ fn a_tool_rail_card(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let cells = slots.len(); let spec = move |_: &u8| PanelSpec::new("Tools").grid(DockGrid::rail(cells).density(density)); let column = Column::new(vec![Group::new(vec![0], 0)]).with_steps(steps); - let sizes = DockSizes { rail_cards: true, ..DockSizes::of_scope(ui) }; + let sizes = DockSizes { column_cards: true, ..DockSizes::of_scope(ui) }; let width = sizes.natural(std::slice::from_ref(&column), &spec).first().map_or(0.0, |(width, _)| *width); let room = Flow::new(ui.available_rect_before_wrap(), Env::of(ui).direction.is_rtl()).span(0.0, width); let rect = room.with_max_y(room.top() + CARD_HEIGHT); // The column takes the cell a dock gives it, as high as the dock, whatever its rail's height. - let shown = - DockColumn::new("Panels", global("dock column", "rail card story"), &column, &spec).card(true).show_groups_at(ui, rect, |_, rect, ui, _| { + let shown = DockColumn::new("Panels", global("dock column", "rail card story"), &column, &spec).card(sizes.card_inset(0)).show_groups_at( + ui, + rect, + |_, rect, ui, _| { let rail = ToolRail::new("Tools", &slots, &BRUSH, &last).density(density); ui.scope_builder(UiBuilder::new().max_rect(rect), |ui| rail.show_rail(ui, |_, _| {})); - }); + }, + ); + ui.advance_cursor_after_rect(rect); + shown.into() +} + +/// A docked panel column of two groups shown as a card (`DockConfig::column_cards`), at the window edge or inward of +/// another column: inset on its top and bottom, and on its outer side by the window edge's inset or by the gutter +/// between two cards, its bar and groups on the rounded panel card with no frame. +#[story(DockColumn<'static, u8>, covers = [], drive = Drive::Never)] +fn a_panel_column_card(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let at = *data.choice("place", 0_usize, &[("At the window edge", 0), ("Inward of another column", 1)]); + let column = Column::new(vec![Group::new(vec![0, 1], 0), Group::new(vec![2], 0)]); + let inset = DockSizes { column_cards: true, ..DockSizes::of_scope(ui) }.card_inset(at); + let room = Flow::new(ui.available_rect_before_wrap(), Env::of(ui).direction.is_rtl()).span(0.0, CARD_WIDTH + inset); + let rect = room.with_max_y(room.top() + 2.0 * CARD_HEIGHT); + let shown = DockColumn::new("Panels", global("dock column", "panel card story"), &column, &spec).card(inset).show_groups_at( + ui, + rect, + |group, rect, ui, _| { + let title = group.active_panel().map_or_else(String::new, |panel| spec(panel).label.as_str().to_owned()); + Panel::new(title).show_at(ui, rect, |_, _| ()); + }, + ); ui.advance_cursor_after_rect(rect); shown.into() } diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 7f5edb52d..42e0c7f4d 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -2,7 +2,8 @@ use super::divider::{self, Divider, Drag}; use super::dock_column::{ - BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_band, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, show_bar, + BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_band, bar_slots, card_rect, card_style, column_grip, describe_chevron, paint_card, paint_chevron, + register_edges, show_bar, }; use super::group::GripMarks; use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag}; @@ -17,7 +18,7 @@ use crate::menu::GroupItem; use crate::primitives::{IconSpec, TextRun}; use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; -use crate::style::{ComponentStyle, Corners, GlyphRole, StyleColor, StyleCx, SurfaceKind}; +use crate::style::{ComponentStyle, Corners, GlyphRole, StyleColor, StyleCx, SurfaceKind, SurfaceStyle}; use craft_behavior::dock::{Column, DockEdge, Group}; use craft_behavior::overlay::Side; use craft_behavior::{Axis, CursorIcon, DockSide, Metrics, PartKey, PressPhase, Sense, Value}; @@ -163,6 +164,8 @@ pub struct IconicColumnStyle { name_gap: f32, /// The marks of a group's grip. grip: GripMarks, + /// The card of a column shown as one ([`card`](IconicColumn::card)). + card: SurfaceStyle, } /// A column collapsed to icons: the column bar over icon groups, one cell per panel. A panel without an icon shows the @@ -222,6 +225,11 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> { /// palette window, the work area. #[prop] within: Rect, + /// The inset on the outer side of the docked column's card, when it shows as one + /// ([`DockConfig::column_cards`](super::DockConfig::column_cards), [`DockSizes::card_inset`]): its bar and icons + /// sit inside the card, inset by that on its outer side and by [`DockSizes::card`] on its top and bottom. + #[prop] + card: Option, open: Bind<'a, Option

>, view: Option>, /// The bar's rect this pass. @@ -283,6 +291,7 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { auto_collapse: false, mode: IconicMode::Flyouts, within: Rect::NOTHING, + card: None, open, view: None, bar_rect: Rect::NOTHING, @@ -352,9 +361,12 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { } } - /// The divider on the column's inner edge: the width runs from the rail to the width the column expands to. + /// The divider on the column's inner edge: the width runs from the rail to the width the column expands to, and + /// a card's inset on top. fn edge_divider(&self, rect: Rect, sizes: &DockSizes) -> Divider { let (least, most) = sizes.iconic_bounds(self.column, self.spec); + let inset = self.card.unwrap_or(0.0); + let (least, most) = (least + inset, most + inset); let most = most.min((self.within.width() - sizes.least_pane).max(rect.width())); Divider::column_edge(rect, self.edge, (least, most), sizes.reach) } @@ -375,7 +387,9 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { self.column.groups.get(group).and_then(|group| group.panels.get(panel)) } + /// Where the parts sit in the column's `rect`: inside its card, if it shows as one. fn plan(&self, rect: Rect, sizes: &IconicSizes, rtl: bool) -> Plan { + let rect = card_rect(rect, self.card, &sizes.column, self.edge, rtl); let bar = Rect::from_min_max(rect.min, Pos2::new(rect.right(), (rect.top() + self.bar.height(&sizes.column)).min(rect.bottom()))); let body = Rect::from_min_max(Pos2::new(rect.left(), bar.bottom()), rect.max); let wide = body.width() >= sizes.labels; @@ -473,6 +487,7 @@ impl Component for IconicColumn<'_, P> { name_gap: cx.tokens.space.gap.item, // The references' grip: a row of upright ticks, in the theme's grip ink. grip: GripMarks::style(cx), + card: card_style(cx), } } @@ -613,9 +628,13 @@ impl Component for IconicColumn<'_, P> { fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { // Painted here, not as the container's surface, which lies over what `paint` draws. - ui.draw().surface(cx.rect, SurfaceKind::Panel, Corners::All); + let card = card_rect(cx.rect, self.card, &cx.style.sizes.column, self.edge, cx.flow.is_rtl()); + paint_card(ui, cx.rect, card, &cx.style.card); if self.bar == ColumnBar::Own { - ui.draw().surface(self.bar_rect, SurfaceKind::Background, Corners::None); + // A card's bar is part of the card. + if self.card.is_none() { + ui.draw().surface(self.bar_rect, SurfaceKind::Background, Corners::None); + } paint_chevron(ui, self.edge, ColumnArrow::Collapse, self.expanded(), cx.flow.is_rtl(), &cx.words::()); } let flat = self.flat(); diff --git a/crates/ui-panels/src/docking/iconic/stories.rs b/crates/ui-panels/src/docking/iconic/stories.rs index 7d79e2699..27b3d9ee6 100644 --- a/crates/ui-panels/src/docking/iconic/stories.rs +++ b/crates/ui-panels/src/docking/iconic/stories.rs @@ -4,7 +4,7 @@ use super::CELL; use crate::buttons::Button; use crate::contract::ShowContainer as _; use crate::contract::{Bind, BodyCx, Show as _, Validity}; -use crate::docking::{ColumnBar, GroupAt, IconicColumn, IconicColumnOutput, IconicMode, PanelSpec}; +use crate::docking::{ColumnBar, DockSizes, GroupAt, IconicColumn, IconicColumnOutput, IconicMode, PanelSpec}; use crate::runtime::commands::{CommandState, CommandStates}; use crate::runtime::env::{Env, Message}; use crate::sections::Panel; @@ -56,10 +56,20 @@ fn at_stage<'a>( ui: &mut Ui, column: IconicColumn<'a, u8>, view: impl FnMut(&Group, GroupAt, &mut Ui, &mut BodyCx<'_>) -> Option + 'a, +) -> IconicColumnOutput { + at_stage_wider(ui, column, 0.0, view) +} + +/// [`at_stage`] with the column `extra` wider than the rail: a card's inset. +fn at_stage_wider<'a>( + ui: &mut Ui, + column: IconicColumn<'a, u8>, + extra: f32, + view: impl FnMut(&Group, GroupAt, &mut Ui, &mut BodyCx<'_>) -> Option + 'a, ) -> IconicColumnOutput { let room = stage(ui); let env = Env::of(ui); - let width = env.tokens.tokens().size.rail.width; // design: allow[style/token-read](a story sizes its stage from the rail token) + let width = env.tokens.tokens().size.rail.width + extra; // design: allow[style/token-read](a story sizes its stage from the rail token) let cell = if env.direction.is_rtl() { Rect::from_min_max(room.min, egui::pos2(room.left() + width, room.bottom())) } else { @@ -81,6 +91,24 @@ fn icon_groups(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { .into() } +/// A docked column of icons shown as a card (`DockConfig::column_cards`), at the window edge or inward of another +/// column: inset on its top and bottom, and on its outer side by the window edge's inset or by the gutter between two +/// cards, its bar and icons on the rounded panel card over the dock's background. +#[story(IconicColumn<'static, u8>, covers = [], drive = Drive::Never)] +fn icons_as_a_card(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let at = *data.choice("place", 1_usize, &[("At the window edge", 0), ("Inward of another column", 1)]); + let inset = DockSizes { column_cards: true, ..DockSizes::of_scope(ui) }.card_inset(at); + let column = Column::new(vec![Group::new(vec![0, 1], 0), Group::new(vec![2], 0)]); + let column = IconicColumn::new("Panels", global("iconic column", "card story"), &column, Bind::kept(), &spec).card(inset); + at_stage_wider(ui, column, inset, |group, at, ui, _| { + let GroupAt::Show(rect) = at else { return None }; + let title = group.active_panel().map_or_else(String::new, |panel| spec(panel).label.as_str().to_owned()); + Panel::new(title).titled().show_at(ui, rect, |_, _| ()); + None + }) + .into() +} + /// Cells bound to their panels' toggle commands: a marked command whose panel is closed shows the marker. #[story(IconicColumn<'static, u8>, covers = [Default], drive = Drive::Never, commands = marked_states)] fn icon_groups_with_marked_panels(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { diff --git a/crates/ui-panels/src/docking/spec.rs b/crates/ui-panels/src/docking/spec.rs index dbdea4370..2fed17f8f 100644 --- a/crates/ui-panels/src/docking/spec.rs +++ b/crates/ui-panels/src/docking/spec.rs @@ -107,11 +107,6 @@ impl DockGrid { } } - /// Whether the grid is a [`rail`](Self::rail) grid, before it is [`resolved`](Self::resolved). - pub(crate) fn is_rail(self) -> bool { - matches!(self.widths, GridWidths::Rail(_)) - } - /// The content's width at one column and the width each further column adds; zero for a rail grid not yet /// [`resolved`](Self::resolved). fn first_step(self) -> (f32, f32) { diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index bd29d87c0..467df4b57 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -4,7 +4,7 @@ //! previous pass's registry, because a drop is decided against what was on screen when the pointer moved. Every //! zone is a rect. A spot names a group by an anchor panel, as the dock model does. -use super::{DockGrid, DragUnit, PanelKey, PanelSpec, scale_widths, width_bounds}; +use super::{DragUnit, PanelKey, PanelSpec, scale_widths, width_bounds}; use crate::contract::DropMark; use crate::rails::RailDensity; use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored}; @@ -86,12 +86,16 @@ pub struct DockSizes { pub dense_rail_first: f32, /// [`rail_step`](Self::rail_step) with the buttons of a dense rail ([`RailDensity::Dense`]). pub dense_rail_step: f32, - /// The inset of a docked tool rail's column shown as a card ([`rail_cards`](Self::rail_cards)) on its outer, top - /// and bottom sides: `space.gap.stack`. - pub rail_card: f32, - /// Whether the dock shows its docked tool rails as cards ([`DockConfig::rail_cards`](super::DockConfig::rail_cards)): - /// off in the style, set by the dock that shows them. - pub rail_cards: bool, + /// The inset of a docked column shown as a card ([`column_cards`](Self::column_cards)) on its top and bottom, and + /// on its outer side at the dock's window edge: `space.gap.stack`. + pub card: f32, + /// The gutter between two neighbouring cards of a dock, on the outer side of each card past the window edge's: + /// `space.gap.tight`. + pub card_gutter: f32, + /// Whether the dock shows its docked columns as cards + /// ([`DockConfig::column_cards`](super::DockConfig::column_cards)): off in the style, set by the dock that shows + /// them. + pub column_cards: bool, /// The height of a grip strip, the band with the dock's grip marks: above each icon group of a collapsed column, /// and under the column bar of a tool rail (a group whose panel has a [`DockGrid`](super::DockGrid)) that the host /// shows itself: the least hit size, or the theme's grip marks with `space.gap.tight` above and below them. @@ -147,8 +151,9 @@ impl DockSizes { rail_step, dense_rail_first, dense_rail_step, - rail_card: cx.tokens.space.gap.stack, - rail_cards: false, + card: cx.tokens.space.gap.stack, + card_gutter: cx.tokens.space.gap.tight, + column_cards: false, grip: super::group::grip_strip(cx.tokens), } } @@ -196,21 +201,16 @@ impl DockSizes { column.width.unwrap_or(self.column).clamp(lo, hi) } - /// The inset of `column`'s card: [`rail_card`](Self::rail_card) for an expanded stepped column of a tool rail - /// ([`DockGrid::rail`](super::DockGrid::rail)) in a dock that shows [`rail_cards`](Self::rail_cards), else none. - /// A docked column is that much wider than its steps. - pub fn card_inset

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> f32 { - let rail = || { - column.steps.is_some() - && column.panels().find_map(|panel| spec(panel).grid.filter(|grid| grid.resolved(self).valid())).is_some_and(DockGrid::is_rail) - }; - if self.rail_cards && !column.iconic && rail() { self.rail_card } else { 0.0 } - } - - /// The width of a docked column before the dock's room shrinks it: its [`width`](Self::width) and its card's - /// inset. - fn docked_width

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> f32 { - self.width(column, spec) + self.card_inset(column, spec) + /// The inset on the outer side of the card of a dock's docked column `at` from the window edge inwards: none + /// without [`column_cards`](Self::column_cards); [`card`](Self::card) for the first column, at the window edge; + /// [`card_gutter`](Self::card_gutter) for the others, which stand that far from their outer neighbour's card. A + /// docked column is that much wider than its content. + pub fn card_inset(&self, at: usize) -> f32 { + match (self.column_cards, at) { + (false, _) => 0.0, + (true, 0) => self.card, + (true, _) => self.card_gutter, + } } /// The width bounds of a column collapsed to icons, docked or floating: the rail width up to the width it expands @@ -226,8 +226,7 @@ impl DockSizes { if column.iconic { self.iconic_bounds(column, spec) } else if let Some((grid, _)) = self.stepped(column, spec) { - let inset = self.card_inset(column, spec); - (grid.width(1) + inset, grid.width(grid.most) + inset) + (grid.width(1), grid.width(grid.most)) } else { self.width_bounds(column, spec) } @@ -264,33 +263,41 @@ impl DockSizes { _ => return Vec::new(), }; let fixed = |column: &Column

| !column.iconic && self.stepped(column, spec).is_some(); + // Each column with its card's inset, which the scaling leaves as it is. let current: Vec<(f32, (f32, f32))> = columns .iter() - .map(|column| { - let width = self.docked_width(column, spec); - (width, if fixed(column) { (width, width) } else { self.shown_bounds(column, spec) }) + .enumerate() + .map(|(at, column)| { + let (width, inset) = (self.width(column, spec), self.card_inset(at)); + let (lo, hi) = if fixed(column) { (width, width) } else { self.shown_bounds(column, spec) }; + (width + inset, (lo + inset, hi + inset)) }) .collect(); let widths = scale_widths(¤t, total); columns .iter() + .enumerate() .zip(current.iter().zip(widths)) - .filter(|(column, ((width, _), scaled))| !fixed(column) && (scaled - width).abs() >= 0.01) - .filter_map(|(column, (_, width))| { + .filter(|((_, column), ((width, _), scaled))| !fixed(column) && (scaled - width).abs() >= 0.01) + .filter_map(|((at, column), (_, width))| { + let width = width - self.card_inset(at); let panel = column.groups.iter().find_map(|group| group.panels.first())?.clone(); Some(if column.iconic { Action::resize_iconic(panel, Some(width)) } else { Action::resize_column(panel, width) }) }) .collect() } - /// The `(width, floor)` of every column, for [`fit_widths`](super::fit_widths): an expanded column shrinks down to - /// its least width, an iconic or stepped one keeps its width. + /// The `(width, floor)` of every column of a dock, from its window edge inwards, for + /// [`fit_widths`](super::fit_widths), each with its card's inset ([`card_inset`](Self::card_inset)): an expanded + /// column shrinks down to its least width, an iconic or stepped one keeps its width. pub fn natural

(&self, columns: &[Column

], spec: &dyn Fn(&P) -> PanelSpec) -> Vec<(f32, Option)> { columns .iter() - .map(|column| { + .enumerate() + .map(|(at, column)| { let keeps = column.iconic || self.stepped(column, spec).is_some(); - (self.docked_width(column, spec), (!keeps).then(|| self.width_bounds(column, spec).0.max(1.0))) + let inset = self.card_inset(at); + (self.width(column, spec) + inset, (!keeps).then(|| self.width_bounds(column, spec).0.max(1.0) + inset)) }) .collect() } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 78ac389cf..f4e5c57fe 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -271,10 +271,10 @@ impl Drops<'_, P> { } } -/// The sizes a dock area lays out with: the dock's style, with its docked tool rails as cards when `config` shows -/// them ([`DockConfig::rail_cards`]). +/// The sizes a dock area lays out with: the dock's style, with its docked columns as cards when `config` shows them +/// ([`DockConfig::column_cards`]). fn area_sizes(mut sizes: DockSizes, config: &DockConfig) -> DockSizes { - sizes.rail_cards = config.rail_cards; + sizes.column_cards = config.column_cards; sizes } @@ -451,6 +451,8 @@ struct ColumnAt

{ bar: ColumnBar, within: Rect, open: Option

, + /// The outer inset of the column's card, a docked column's in a dock that shows cards ([`DockSizes::card_inset`]). + card: Option, } /// What a column reported. @@ -1226,7 +1228,7 @@ impl Pass<'_, P> { let reading = plan.flow.to_physical(plan.rect); let start = plan.edge == DockEdge::Start; let mut cursor = if start { reading.left() } else { reading.right() }; - for (column, width) in plan.columns.iter().zip(widths) { + for (at, (column, width)) in plan.columns.iter().zip(widths).enumerate() { let span = if start { (cursor, cursor + width) } else { (cursor - width, cursor) }; cursor = if start { span.1 } else { span.0 }; let cell = plan.flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range())); @@ -1236,7 +1238,8 @@ impl Pass<'_, P> { // (photocraft#16461). Content taller than the dock scrolls inside. Only a floating stepped window is as // tall as its content. self.report.placed.push((first.clone(), cell)); - let at = ColumnAt { cell, edge: plan.edge, bar: ColumnBar::Own, within: body.rect, open: plan.open.clone() }; + let card = scene.sizes.column_cards.then(|| scene.sizes.card_inset(at)); + let at = ColumnAt { cell, edge: plan.edge, bar: ColumnBar::Own, within: body.rect, open: plan.open.clone(), card }; self.column(ui, body, column, at); } } @@ -1329,7 +1332,7 @@ impl Pass<'_, P> { let spec = |panel: &P| scene.spec(panel); let name = Label::from(body.words::().panels.as_str().to_owned()); let dock = self.dock; - let ColumnAt { mut cell, edge, bar, within, open } = at; + let ColumnAt { mut cell, edge, bar, within, open, card } = at; let in_window = bar == ColumnBar::Window; if in_window { DockTargets::

::register_room(ui.ctx(), dock, cell); @@ -1337,18 +1340,24 @@ impl Pass<'_, P> { let opens = if edge == DockEdge::Start { Side::End } else { Side::Start }; // Only a docked column's icons are a rail; a floating window's open flyouts. let mode = if in_window { IconicMode::Flyouts } else { scene.config.iconic_mode }; - let mut icons = |cell: Rect, open: Option

| { + // The width the user gives a column by its inner edge leaves out its card's inset. + let inset = card.unwrap_or(0.0); + let mut icons = |cell: Rect, open: Option

, card: Option| { let footer = scene.rail_footer.filter(|panel| mode == IconicMode::Rail && column.panels().any(|item| item == *panel)); let pass = RefCell::new(&mut *self); let draw = |ui: &mut Ui, rect: Rect, open: Option

| { - IconicColumn::new(name.clone(), dock, column, Bind::given(open), &spec) + let shown = IconicColumn::new(name.clone(), dock, column, Bind::given(open), &spec) .edge(edge) .opens(opens) .bar(bar) .within(within) .auto_collapse(scene.auto_collapse) - .mode(mode) - .show_flyouts_at(ui, rect, |group, at, ui, body| pass.borrow_mut().group_of(ui, body, group, at, in_window)) + .mode(mode); + let shown = match card { + Some(inset) => shown.card(inset), + None => shown, + }; + shown.show_flyouts_at(ui, rect, |group, at, ui, body| pass.borrow_mut().group_of(ui, body, group, at, in_window)) }; if let Some(panel) = footer { let height = IconicSizes::of(ui.ctx()).icons_height(column) + scene.sizes.bar; @@ -1370,10 +1379,11 @@ impl Pass<'_, P> { } }; let work = if column.iconic { - let Some(output) = icons(cell, open) else { return }; + let Some(output) = icons(cell, open, card) else { return }; self.report.flyout.extend(output.edit.events); self.rail_work(output.front); - ColumnWork { iconic: output.iconic, picked: output.picked, resized: Vec::new(), width: output.width, flyout: output.flyout } + let width = output.width.map(|width| width - inset); + ColumnWork { iconic: output.iconic, picked: output.picked, resized: Vec::new(), width, flyout: output.flyout } } else { if !in_window && scene.rail_beside(column) { // The rail keeps to the dock's window edge and the expanded column shows inward of it. @@ -1385,7 +1395,8 @@ impl Pass<'_, P> { (cell.with_min_x(cell.right() - rail), cell.with_max_x(cell.right() - rail)) }; cell = rest; - let Some(output) = icons(rail_cell, None) else { return }; + // The rail stands square at the window edge; the expanded column's card is inward of it. + let Some(output) = icons(rail_cell, None, None) else { return }; self.rail_work(output.front); // The rail's inner edge sets its own width, not the expanded column's. self.column_work(column, ColumnWork { iconic: output.iconic, picked: output.picked, resized: Vec::new(), width: None, flyout: None }); @@ -1398,12 +1409,16 @@ impl Pass<'_, P> { .bar(bar) .arrow(self.arrow_of(column)) .within(within) - .auto_collapse(scene.auto_collapse) - .card(scene.sizes.rail_cards && !in_window); + .auto_collapse(scene.auto_collapse); + let shown = match card { + Some(inset) => shown.card(inset), + None => shown, + }; let output = shown.show_groups_at(ui, cell, |group, rect, ui, body| { self.group_of(ui, body, group, GroupAt::Show(rect), in_window); }); - ColumnWork { iconic: output.iconic, picked: output.picked, resized: output.resized, width: output.width, flyout: None } + let width = output.width.map(|width| width - inset); + ColumnWork { iconic: output.iconic, picked: output.picked, resized: output.resized, width, flyout: None } }; self.column_work(column, work); } @@ -1430,10 +1445,9 @@ impl Pass<'_, P> { let spec = |panel: &P| scene.spec(panel); if let Some(width) = work.width { match scene.sizes.stepped(column, &spec) { - // The edge of a stepped column moves in whole steps: the most that fit where it is dragged, inside its - // card. + // The edge of a stepped column moves in whole steps: the most that fit where it is dragged. Some((grid, steps)) if !column.iconic => { - let to = grid.steps_within(width - scene.sizes.card_inset(column, &spec)); + let to = grid.steps_within(width); if to != steps { self.report.actions.push(Action::set_column_steps(first.clone(), to)); } @@ -1594,7 +1608,7 @@ impl Pass<'_, P> { // An OS window's flyouts and other layers take the room around the window (`overlay::layer_room`); an // in-app window's stay in the float area. let within = if opening.spec.is_some() { Rect::NOTHING } else { scene.bounds }; - let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within, open: open.clone() }; + let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within, open: open.clone(), card: None }; self.column(ui, body, &window.column, at); }); self.dock = area_dock; diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index e274aefde..217f91ad0 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -509,7 +509,7 @@ impl DockPanels for RailStage { } /// A start dock in `direction` of a toolbar column of two rail steps, at the window edge, and a side column beside it, -/// with `DockConfig::rail_cards` set to `cards`: the toolbar's cell, the side column's cell and the rail's stage. +/// with `DockConfig::column_cards` set to `cards`: the toolbar's cell, the side column's cell and the rail's stage. fn rail_dock(cards: bool, direction: Direction) -> (Rect, Rect, Rect) { let columns = vec![Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(2), Column::new(vec![Group::new(vec![2], 0)]).with_width(150.0)]; let root = Node::split(Axis::X, SplitSize::FixedFirst(300.0), Node::dock(DockEdge::Start, columns), Node::tabs(vec![1], 0)); @@ -519,7 +519,7 @@ fn rail_dock(cards: bool, direction: Direction) -> (Rect, Rect, Rect) { let (held, seen, shown, specs) = (Rc::clone(&workspace), Rc::clone(&placed), Rc::clone(&stage), Tracked::new(RailTools)); let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); - let config = DockConfig::default().rail_cards(cards); + let config = DockConfig::default().column_cards(cards); let out = DockArea::new("Rail dock", Bind::bound(&mut workspace), &specs, &mut RailStage(Rc::clone(&shown)), config).show(ui); *held.borrow_mut() = workspace; *seen.borrow_mut() = out.columns; @@ -555,3 +555,102 @@ fn a_rail_card_is_inset_alike_on_three_sides_and_keeps_its_steps() { ); } } + +/// The panel of the card dock's expanded column, and of its column collapsed to icons. +const SIDE: u32 = 2; +const ICONS: u32 = 4; + +/// Panels named for the card dock: an expanded column's panel, and a collapsed column's, whose icon the trial finds by +/// its name. +#[derive(PlainData)] +struct CardPanels; + +impl PanelSpecs for CardPanels { + fn spec(&self, panel: &u32) -> PanelSpec { + PanelSpec::new(if *panel == ICONS { "Icons" } else { "Side" }) + } +} + +/// Panels that record the rect the expanded column's group gets. +struct CardStage(Rc>>); + +impl DockPanels for CardStage { + fn body(&mut self, panel: &u32, _: &mut Ui, body: &mut BodyCx<'_>) { + if *panel == SIDE { + self.0.set(Some(body.rect)); + } + } +} + +/// What a card dock trial reads: the cells of the expanded column and of the column of icons, the body of the expanded +/// column's panel and the icon's cell. +struct CardDock { + side: Rect, + icons: Rect, + body: Rect, + icon: Rect, +} + +/// An end dock in `direction` beside the canvas: an expanded column at the window edge and, inward of it, a column +/// collapsed to icons, with `DockConfig::column_cards` set to `cards`. +fn card_dock(cards: bool, direction: Direction) -> CardDock { + let mut iconic = Column::new(vec![Group::new(vec![ICONS], 0)]); + iconic.iconic = true; + let columns = vec![Column::new(vec![Group::new(vec![SIDE], 0)]).with_width(220.0), iconic]; + let root = Node::split(Axis::X, SplitSize::Ratio(0.6), Node::tabs(vec![1], 0), Node::dock(DockEdge::End, columns)); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))))); + let placed: Rc>> = Rc::default(); + let body: Rc>> = Rc::default(); + let (held, seen, shown, specs) = (Rc::clone(&workspace), Rc::clone(&placed), Rc::clone(&body), Tracked::new(CardPanels)); + let mut fixture = Fixture::new(move |ui| { + let mut workspace = held.borrow().clone(); + let config = DockConfig::default().column_cards(cards); + let out = DockArea::new("Card dock", Bind::bound(&mut workspace), &specs, &mut CardStage(Rc::clone(&shown)), config).show(ui); + *held.borrow_mut() = workspace; + *seen.borrow_mut() = out.columns; + }); + fixture.direction(direction).room(Vec2::new(900.0, 500.0)).settle(); + let cell = |panel: u32| placed.borrow().iter().find(|(at, _)| *at == panel).map(|(_, rect)| *rect).expect("the column shows"); + let icon = fixture.by_label("Icons").expect("the icon shows").rect; + CardDock { side: cell(SIDE), icons: cell(ICONS), body: body.get().expect("the side panel shows"), icon } +} + +/// The insets of `inner` in `cell` on the outer side, the window edge's (the right in left to right), and on the inner +/// side. +fn sides(cell: Rect, inner: Rect, rtl: bool) -> (f32, f32) { + if rtl { (inner.left() - cell.left(), cell.right() - inner.right()) } else { (cell.right() - inner.right(), inner.left() - cell.left()) } +} + +/// Every docked column shows as a card: the column at the window edge is inset alike on its outer side and its foot, +/// the column of icons inward of it stands a gutter from its card, narrower than the edge's inset, and both cards keep +/// to their inner edges. The columns do not overlap, and each is wider than without cards by its inset, so its +/// content keeps its width. Right to left mirrors the outer sides. +#[trial] +fn every_docked_column_is_a_card_with_gutters_between_them() { + for direction in [Direction::Ltr, Direction::Rtl] { + let rtl = direction == Direction::Rtl; + let plain = card_dock(false, direction); + let cards = card_dock(true, direction); + // Each inset is measured against the same column without cards, so a panel's own padding cancels out. + let inset = |cell: Rect, inner: Rect, plain_cell: Rect, plain_inner: Rect| { + let ((outer, inward), (plain_outer, plain_inward)) = (sides(cell, inner, rtl), sides(plain_cell, plain_inner, rtl)); + (outer - plain_outer, inward - plain_inward) + }; + let (edge, side_inner) = inset(cards.side, cards.body, plain.side, plain.body); + let foot = (cards.side.bottom() - cards.body.bottom()) - (plain.side.bottom() - plain.body.bottom()); + assert!(edge > 0.5, "{direction:?}: the edge column's card is inset from the window edge: {:?} in {:?}", cards.body, cards.side); + assert!((foot - edge).abs() <= 0.5, "{direction:?}: the edge column's card is inset {edge} at the edge and {foot} at its foot"); + assert!(side_inner.abs() <= 0.5, "{direction:?}: the edge column's card keeps to its inner edge"); + let (gutter, icons_inner) = inset(cards.icons, cards.icon, plain.icons, plain.icon); + assert!( + gutter > 0.5 && gutter < edge, + "{direction:?}: the icons' card stands a gutter {gutter} from its neighbour's, under the edge's {edge}" + ); + assert!(icons_inner.abs() <= 0.5, "{direction:?}: the icons' card keeps to its inner edge"); + let apart = if rtl { cards.icons.left() >= cards.side.right() - 0.5 } else { cards.icons.right() <= cards.side.left() + 0.5 }; + assert!(apart, "{direction:?}: the icons' column {:?} overlaps the edge column {:?}", cards.icons, cards.side); + assert!((cards.body.width() - plain.body.width()).abs() <= 0.5, "{direction:?}: the panel keeps its width in its card"); + assert!((cards.side.width() - plain.side.width() - edge).abs() <= 0.5, "{direction:?}: the edge column grows by its inset"); + assert!((cards.icons.width() - plain.icons.width() - gutter).abs() <= 0.5, "{direction:?}: the icons' column grows by its gutter"); + } +} From 06e94d7321869b721e5b4c815fc09c7685327863 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 17:59:45 +0700 Subject: [PATCH 12/16] tabs, dock: PanelTabLook::Pill shows a panel strip's shown tab on a filled rounded pill (surface.control, shape.radius.control, size.control.sm high in the middle of the strip; a hovered tab shows it too); TabStrip::panel_look and DockConfig::tab_look choose it, Plain by default --- crates/ui-panels/src/docking/config.rs | 12 +++++++ crates/ui-panels/src/docking/group.rs | 9 ++++- crates/ui-patterns/src/patterns/dock/area.rs | 1 + crates/ui-widgets/src/tabs/mod.rs | 2 +- crates/ui-widgets/src/tabs/rules.rs | 13 ++++++++ crates/ui-widgets/src/tabs/strip.rs | 8 +++-- crates/ui-widgets/src/tabs/strip/stories.rs | 9 ++++- crates/ui-widgets/src/tabs/tab.rs | 35 +++++++++++++++++++- 8 files changed, 83 insertions(+), 6 deletions(-) diff --git a/crates/ui-panels/src/docking/config.rs b/crates/ui-panels/src/docking/config.rs index e2d19ff42..d3b885867 100644 --- a/crates/ui-panels/src/docking/config.rs +++ b/crates/ui-panels/src/docking/config.rs @@ -3,6 +3,7 @@ use super::IconicMode; use super::targets::ZoneRule; +use crate::tabs::PanelTabLook; use craft_behavior::{DockSide, IconId}; /// A set of the sides of the layout's outer edge or of a group. @@ -97,6 +98,9 @@ pub struct DockConfig { pub titled_headers: bool, /// The wheel over a tab strip shows the next or previous panel, one per wheel notch. pub wheel_selects_tabs: bool, + /// The look of the groups' panel tabs: the shown tab on the panel surface ([`PanelTabLook::Plain`]), or on a + /// filled rounded pill ([`PanelTabLook::Pill`]). + pub tab_look: PanelTabLook, /// A floating window opens in an OS window of its own where the window host opens OS windows and reports where /// they are on the desktop (not on Wayland) and its panels allow it (`PanelSpec::allow_native`). Elsewhere, and /// with this off, it shows in the app window. @@ -131,6 +135,7 @@ impl Default for DockConfig { tab_close_buttons: false, titled_headers: false, wheel_selects_tabs: false, + tab_look: PanelTabLook::Plain, native_windows: true, group_order_items: false, panel_menu_always: false, @@ -253,6 +258,13 @@ impl DockConfig { self } + /// The look of the groups' panel tabs ([`tab_look`](Self::tab_look)). + #[must_use] + pub fn tab_look(mut self, look: PanelTabLook) -> Self { + self.tab_look = look; + self + } + /// Close buttons on tabs on or off. #[must_use] pub fn tab_close_buttons(mut self, on: bool) -> Self { diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index cc7a1bcb7..16184feac 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -21,7 +21,7 @@ use crate::runtime::focus::{self, FocusTarget}; use crate::runtime::memory::sub; use crate::sections::FooterBar; use crate::style::{ComponentStyle, Corners, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind, TypeRole}; -use crate::tabs::{Tab, TabKind, TabStrip, TornOff}; +use crate::tabs::{PanelTabLook, Tab, TabKind, TabStrip, TornOff}; use craft_behavior::{CursorIcon, CursorPriority, DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed}; use craft_theme::{ControlSize, GripMark, GripShape, Tokens}; use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; @@ -347,6 +347,9 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { /// The wheel over the tabs shows the next or previous panel, one per wheel notch. #[prop(flag)] wheel_selects_tabs: bool, + /// The look of the tabs ([`DockConfig::tab_look`](super::DockConfig::tab_look)). + #[prop] + tab_look: PanelTabLook, /// The header shows the shown panel's title (with its count) and a close button in place of the tab strip, as a /// single titled panel does: the panels are shown from a rail, not by tabs. #[prop(flag)] @@ -402,6 +405,7 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< movable: true, closable: false, wheel_selects_tabs: false, + tab_look: PanelTabLook::Plain, titled: false, dock: None, zones: ZoneRule::Fraction, @@ -666,6 +670,7 @@ impl Container for active: self.active, closable: self.closable, wheel_selects: self.wheel_selects_tabs, + look: self.tab_look, dock: self.dock, sent: Outbox::new(&mut sent), }; @@ -740,6 +745,7 @@ struct TabRow<'a, P> { active: PanelKey, closable: bool, wheel_selects: bool, + look: PanelTabLook, dock: Option, sent: Outbox<'a, TabEvent>, } @@ -768,6 +774,7 @@ fn tab_row(row: &mu let kind = if panels.iter().any(closes) { TabKind::Document } else { TabKind::Panel }; let mut strip = TabStrip::new(name) .kind(kind) + .panel_look(row.look) .shown(active) .tear_off() .natural_height(true) diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index f4e5c57fe..c8f50a75a 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1104,6 +1104,7 @@ impl Pass<'_, P> { .menu(move || panel_menu_rows(scene, &mut **panels.borrow_mut(), words, shown).0) .panel_menu_shown(*hosted || scene.config.panel_menu_always) .panel_menu_icon(scene.config.panel_menu_icon.clone()) + .tab_look(scene.config.tab_look) .command_states(states.clone()); if look.in_window { group = group.in_window(); diff --git a/crates/ui-widgets/src/tabs/mod.rs b/crates/ui-widgets/src/tabs/mod.rs index 43a3f8982..4e27b1c62 100644 --- a/crates/ui-widgets/src/tabs/mod.rs +++ b/crates/ui-widgets/src/tabs/mod.rs @@ -6,7 +6,7 @@ mod words; mod rules; pub(crate) mod tab; -pub use rules::{CloseSide, DocumentTabLook, FitMode, OverflowMenu, OverflowPlace, TabKind, close_side}; +pub use rules::{CloseSide, DocumentTabLook, FitMode, OverflowMenu, OverflowPlace, PanelTabLook, TabKind, close_side}; pub use tab::{Tab, TabOutput, TabPartEvent, TabRole, TabStyle}; pub use words::TabWords; diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index 3583682b3..19a74b597 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -17,6 +17,19 @@ pub enum DocumentTabLook { Shrinking, } +/// The look of panel tabs ([`TabKind::Panel`]): a strip's choice ([`TabStrip::panel_look`](super::TabStrip)), which a +/// dock makes for its groups' tabs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::contract::MemoProps)] +#[non_exhaustive] +pub enum PanelTabLook { + /// The shown tab on the panel surface, square and as tall as the strip. + #[default] + Plain, + /// VectorCraft's tabs: the shown tab on a filled pill (`surface.control` with `shape.radius.control` corners), a + /// small control high in the middle of the strip; a tab under the pointer shows the pill too. + Pill, +} + /// The kind of a strip. It sets the defaults below; the host picks one per strip. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] diff --git a/crates/ui-widgets/src/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index 4d48ba9e1..da1ab7e01 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -516,6 +516,9 @@ pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + ' /// The strip's taller form with the body type. #[prop(flag)] large: bool, + /// The look of a panel strip's tabs ([`TabKind::Panel`]). + #[prop] + panel_look: super::PanelTabLook, /// The tab the host shows. A click, Space, Enter or a drop reports the new one in the output. #[prop] shown: Option, @@ -586,6 +589,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri .primary_picks(TabKind::Document.primary_shows()), kind: TabKind::Document, large: false, + panel_look: super::PanelTabLook::Plain, shown: None, tear_off: false, wheel_selects: false, @@ -1023,9 +1027,9 @@ impl Collection StripLayout::new(count, Vec2::new(width, cx.tokens.size.bar.tab), tab_gap, fitting, self.report.clone(), cx.frame_ctx().clone()) } - /// Every tab takes the strip's kind and size. + /// Every tab takes the strip's kind, panel look and size. fn dress<'r>(&self, tab: Self::Item<'r>, _: &RowState) -> Self::Item<'r> { - let tab = tab.kind(self.kind); + let tab = tab.kind(self.kind).panel_look(self.panel_look); if self.large { tab.large() } else { tab } } diff --git a/crates/ui-widgets/src/tabs/strip/stories.rs b/crates/ui-widgets/src/tabs/strip/stories.rs index 1d38a446f..863e07c5a 100644 --- a/crates/ui-widgets/src/tabs/strip/stories.rs +++ b/crates/ui-widgets/src/tabs/strip/stories.rs @@ -3,7 +3,7 @@ use super::{StripEnd, TabKind, TabStrip}; use crate::contract::{CollectionEvent, Entry, ReorderRule, ShowCollection as _}; use crate::runtime::commands::{CommandRef, EditCommands}; -use crate::tabs::{Tab, TabRole}; +use crate::tabs::{PanelTabLook, Tab, TabRole}; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use craft_behavior::{DisplayOrder, IconId, ItemSource, SelectionChange}; use egui::{Key, Modifiers, Ui}; @@ -94,6 +94,13 @@ fn tab_strip_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { strip(ui, data, TabStrip::new("Panels").shown(1), &TITLES, 4, TabKind::Panel) } +/// Panel tabs in the pill look (`PanelTabLook::Pill`, a dock's `DockConfig::tab_look`): the shown tab on a filled +/// rounded pill in the middle of the strip, the others bare until the pointer rests on one. +#[story(TabStrip<'static, usize>, covers = [], drive = Drive::Never)] +fn tab_strip_panel_pill(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + strip(ui, data, TabStrip::new("Panels").shown(1).panel_look(PanelTabLook::Pill), &TITLES, 4, TabKind::Panel) +} + /// The width the narrow panel story's room is held to: the shown tab whole, the others at their first letters. const NARROW_ROOM: f32 = 260.0; diff --git a/crates/ui-widgets/src/tabs/tab.rs b/crates/ui-widgets/src/tabs/tab.rs index 0b69e1e72..729f598f3 100644 --- a/crates/ui-widgets/src/tabs/tab.rs +++ b/crates/ui-widgets/src/tabs/tab.rs @@ -5,7 +5,7 @@ //! measure is its natural width (`Proposal::Min` the room for the first letters of its title), and a narrower rect cuts the label //! first, then the detail, and shows the whole text as a tooltip. -use super::rules::{CloseSide, TabKind, close_side}; +use super::rules::{CloseSide, PanelTabLook, TabKind, close_side}; use super::words::TabWords; use std::borrow::Cow; @@ -133,6 +133,8 @@ pub struct TabStyle { indicator: Option, /// A divider at the tab's trailing edge. divider: bool, + /// The pill a panel tab in [`PanelTabLook::Pill`] shows under its label in place of the surface. + pill: Option, close_side: CloseSide, sizes: Sizes, /// Document tabs in [`DocumentTabLook::Shrinking`](super::DocumentTabLook::Shrinking): a name capped at @@ -146,6 +148,15 @@ pub struct TabStyle { marker_edge: StyleColor, } +/// The pill of a panel tab in [`PanelTabLook::Pill`]: its fill in each state, its corners and its height, in the +/// middle of the tab's height. +#[derive(Clone, Debug, PartialEq)] +struct Pill { + fill: Stateful, + radius: egui::CornerRadius, + height: f32, +} + /// Where the parts of a tab lie in its content rect. #[derive(Clone, Copy, Debug)] struct Placed { @@ -180,6 +191,10 @@ pub struct Tab<'a> { #[style_key] #[prop(flag)] large: bool, + /// The look of a panel tab ([`TabKind::Panel`]); the other kinds have their own. + #[style_key] + #[prop] + panel_look: PanelTabLook, /// Secondary text after the label (a colour mode, a zoom). #[prop(into)] detail: Option