diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 3550e4563..8b57e2b93 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -32,7 +32,11 @@ fn tab_extent(value: f32) -> f32 { /// points. Empty input and an out-of-range selection are valid. The widths of all shown tabs plus /// `overflow_width` never exceed the sanitized available width. Work and storage are linear in /// the input count (with at most 32 fitting passes); callers keep their own tab-count policy. -pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32) -> TabFit { +/// +/// With `keep_selected` the selected tab keeps its natural width (only a tab wider than the strip minus the +/// button shrinks); the other tabs share the rest down to `minimum_width`, and the ones that still do not fit go to +/// the overflow, the last ones first. +pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32, keep_selected: bool) -> TabFit { let available = tab_extent(available); let minimum_width = tab_extent(minimum_width); let natural: Vec = natural.iter().map(|&w| tab_extent(w)).collect(); @@ -45,6 +49,9 @@ pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, return TabFit { shown: vec![(0, available)], ..Default::default() }; } let floor = |w: f32| w.min(minimum_width); + if keep_selected { + return fit_keeping_selected(&natural, selected, available, minimum_width, overflow_width); + } if natural.iter().map(|&w| f64::from(floor(w))).sum::() <= f64::from(available) { return TabFit { shown: squeeze(&natural, &all, available, minimum_width), ..Default::default() }; } @@ -68,6 +75,44 @@ pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, TabFit { shown, overflow, overflow_width } } +/// [`fit`] with the selected tab at its natural width: the others squeeze beside it, then overflow from the end. +fn fit_keeping_selected(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32) -> TabFit { + let selected = selected.min(natural.len().saturating_sub(1)); + let floor = |i: usize| natural.get(i).copied().unwrap_or(0.0).min(minimum_width); + let others: Vec = (0..natural.len()).filter(|&i| i != selected).collect(); + let pinned = natural.get(selected).copied().unwrap_or(0.0); + let floors: f64 = others.iter().map(|&i| f64::from(floor(i))).sum(); + let (kept, room, overflow_width) = if floors + f64::from(pinned) <= f64::from(available) { + (others, available - pinned, 0.0) + } else { + let overflow_width = tab_extent(overflow_width).min(available); + let room = (available - overflow_width - pinned).max(0.0); + let mut used = 0.0f64; + let kept: Vec = others + .into_iter() + .take_while(|&i| { + used += f64::from(floor(i)); + used <= f64::from(room) + }) + .collect(); + (kept, room, overflow_width) + }; + let squeezed = squeeze(natural, &kept, room, minimum_width); + let pinned = pinned.min(available - overflow_width); + let mut shown = Vec::with_capacity(squeezed.len() + 1); + let mut overflow = Vec::new(); + for i in 0..natural.len() { + if i == selected { + shown.push((i, pinned)); + } else if let Some(&(_, width)) = squeezed.iter().find(|&&(at, _)| at == i) { + shown.push((i, width)); + } else { + overflow.push(i); + } + } + TabFit { shown, overflow, overflow_width } +} + /// Fit tabs at their natural widths; the tabs that do not fit go to an overflow menu. /// /// Tabs are shown in input order up to the first one that does not fit beside the selected tab diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index e570866d3..7ec8b3f1b 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -11,7 +11,7 @@ fn overflow_retains_selection_and_partitions_all_tabs() { let natural = [80.0, 90.0, 85.0, 95.0]; for selected in [0, 1, 2, 3, usize::MAX] { for available in [0.0, 1.0, 5.0, 18.0, 19.0, 55.0, 120.0, 200.0, 500.0] { - let f = fit(&natural, selected, available, 40.0, 18.0); + let f = fit(&natural, selected, available, 40.0, 18.0, false); let selected = selected.min(natural.len() - 1); assert!(f.shown.iter().any(|&(i, _)| i == selected), "{selected} at {available}: {f:?}"); assert!(!f.overflow.contains(&selected)); @@ -24,3 +24,33 @@ fn overflow_retains_selection_and_partitions_all_tabs() { } } } + +#[test] +fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { + let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; + for selected in 0..natural.len() { + for available in [0.0, 30.0, 60.0, 120.0, 160.0, 200.0, 260.0, 300.0, 420.0, 500.0] { + let f = fit(&natural, selected, available, 40.0, 18.0, true); + assert!(f.shown.iter().any(|&(i, _)| i == selected), "{selected} at {available}: {f:?}"); + assert!(total(&f) <= available + 0.001, "{available}: {f:?}"); + let kept = f.shown.iter().find(|&&(i, _)| i == selected).map(|&(_, w)| w).unwrap_or(0.0); + if natural[selected] + f.overflow_width <= available { + assert!((kept - natural[selected]).abs() < 0.001, "the shown tab keeps its width: {f:?}"); + } + for &(i, width) in &f.shown { + if i != selected { + assert!(width >= natural[i].min(40.0) - 0.001, "others keep the minimum: {f:?}"); + } + } + let others_hidden: Vec = f.overflow.clone(); + let others: Vec = (0..natural.len()).filter(|&i| i != selected).collect(); + let first_hidden = others.iter().position(|i| others_hidden.contains(i)); + if let Some(at) = first_hidden { + assert!(others[at..].iter().all(|i| others_hidden.contains(i)), "overflow takes the last tabs: {f:?}"); + assert!(f.overflow_width > 0.0 || available == 0.0, "the button is reserved: {f:?}"); + } else { + assert_eq!(f.overflow_width, 0.0); + } + } + } +} diff --git a/crates/color-ui/src/ui/picker/full.rs b/crates/color-ui/src/ui/picker/full.rs index ec1e68ee1..bb48b6bce 100644 --- a/crates/color-ui/src/ui/picker/full.rs +++ b/crates/color-ui/src/ui/picker/full.rs @@ -4,11 +4,10 @@ use craft_behavior::{ColumnWidth, IconId, Metrics, Mixed, NavShape, Sense}; use craft_theme::{ColorModel, HsbModel, OklchModel, RgbModel, Srgba}; use craft_ui::choice::{Checkbox, Radio, RadioGroup, Swatch}; use craft_ui::contract::{ - Bind, Common, Component, Cx, GlyphLabel, LabelKind, LabelScheme, MeasureCx, Outcome, PaintUi, Props as _, Role, Show as _, ShowContainer as _, + Bind, BodyCx, Common, Component, Cx, FieldLayout, LabelKind, MeasureCx, Outcome, PaintUi, Props as _, Role, Show as _, ShowContainer as _, SideLabel, Sizing, }; use craft_ui::display::{Icon, Shade, Text}; -use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::{Grid, Row, Stack}; use craft_ui::primitives::IconSpec; use craft_ui::runtime::env::{Env, Label}; @@ -36,6 +35,7 @@ pub struct ColorWarning { struct ModelChoice<'m> { visible: &'m [&'m dyn ColorModel], offered: &'m [AreaMode], + words: &'m ColorPickerWords, } impl ColorWarning { @@ -256,14 +256,16 @@ impl<'a> Body<'a> { }; Grid::new(widths).show(ui, |ui, _| { for (column, models) in columns.iter().enumerate() { - FieldGroup::new(words.channels.as_str().to_owned()).labels(LabelScheme::Inspector).show(ui, |ui, _| { + // Each model column is its own grid of radio, letter and field cells, so the fields of a + // column share one x whether or not their row has a radio. + Grid::new(THREE_COLUMNS).show(ui, |ui, cx| { for model in models { - self.model_fields(ui, pass, *model, ModelChoice { visible, offered: &offered }, words, got); + self.model_fields(ui, cx, pass, *model, ModelChoice { visible, offered: &offered, words }, got); } if column == 0 { - Field::new(words.hex.as_str().to_owned()) - .side(HexField::hash_label()) - .show(ui, |ui, _| self.hex_field(ui, pass, words, got)); + Text::new(Label::from("")).show(ui); + Text::new(Label::from(HexField::HASH)).shade(Shade::Muted).show(ui); + self.hex_field(ui, pass, words, got); } }); } @@ -275,59 +277,53 @@ impl<'a> Body<'a> { } } - /// The rows of one model's channels. + /// The rows of one model's channels, three cells each: the radio that chooses the area mode (an empty cell where the + /// channel offers none), the channel's letter and its number field. The radio's name stays its accessible name. fn model_fields( &self, ui: &mut Ui, + cx: &mut BodyCx<'_>, pass: &Pass<'a>, model: &'a dyn ColorModel, choice: ModelChoice<'_>, - words: &ColorPickerWords, got: &mut Collected, ) { - let ModelChoice { visible, offered } = choice; + let ModelChoice { visible, offered, words } = choice; let values = pass.shown.values_in(model); for (i, channel) in model.channels().iter().enumerate() { let name = channel_name(model, i, visible); - let short = words.grid_label.fill(&[("label", channel.label)]); - let short: &str = &short; - let label = SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(Label::from(short.to_owned())))); + let letter = words.grid_label.fill(&[("label", channel.label)]); + let letter: &str = &letter; let mode = offered.iter().find(|mode| mode.model().id() == model.id() && mode.strip() == i).copied(); + match mode { + Some(mode) => { + let side = SideLabel::new().layout(FieldLayout::After).kind(LabelKind::Hidden); + cx.labelled(ui, (model.id(), i), name.clone(), side, Radio::new(mode)); + } + None => { + Text::new(Label::from("")).show(ui); + } + } + Text::new(Label::from(letter.to_owned())).shade(Shade::Muted).show(ui); let rule = ChannelRule::of(channel); let unit = ChannelUnit::of(channel.unit); let value = f64::from(values.values[i]); - let edit = Field::new(name.clone()) - .side(label) - .show(ui, |ui, _| { - Row::new() - .show(ui, |ui, _| { - if let Some(mode) = mode { - Radio::new(mode).label(name.clone()).show(ui); - } - let field = NumberField::new(name.clone(), Bind::given(pass.shows(Some(value)))) - .range(rule.range.clone()) - .step(rule.step) - .snap_typed(true) - .commit_decimals(usize::from(rule.decimals)); - let field = match unit { - ChannelUnit::None => field, - ChannelUnit::Percent => field.unit_kind(craft_ui::runtime::env::UnitKind::Percent), - ChannelUnit::Degrees => field.unit_kind(craft_ui::runtime::env::UnitKind::Degrees), - ChannelUnit::Text(text) => field.unit(Label::from(text)), - }; - field.show(ui).edit - }) - .inner - }) - .inner - .flatten(); - if let Some(edit) = edit { - got.adopt(edit, pass.shown, |v, mine| { - if let Some(v) = v { - *mine = mine.with_channel(model, i, *v, &pass.rules); - } - }); - } + let field = NumberField::new(name, Bind::given(pass.shows(Some(value)))) + .range(rule.range.clone()) + .step(rule.step) + .snap_typed(true) + .commit_decimals(usize::from(rule.decimals)); + let field = match unit { + ChannelUnit::None => field, + ChannelUnit::Percent => field.unit_kind(craft_ui::runtime::env::UnitKind::Percent), + ChannelUnit::Degrees => field.unit_kind(craft_ui::runtime::env::UnitKind::Degrees), + ChannelUnit::Text(text) => field.unit(Label::from(text)), + }; + got.adopt(field.show(ui).edit, pass.shown, |v, mine| { + if let Some(v) = v { + *mine = mine.with_channel(model, i, *v, &pass.rules); + } + }); } } } diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index afc6b7057..170d3cb74 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -4,10 +4,10 @@ use std::cell::RefCell; use std::rc::Rc; use craft_behavior::Mixed; -use craft_color_ui::ui::{ColorPickerDialog, ColorReadout, PickedColor}; +use craft_color_ui::ui::{ColorPicker, ColorPickerDialog, ColorPickerLayout, ColorReadout, PickedColor}; use craft_host::{AppInfo, Host}; -use craft_theme::{ModelValues, Rgba, Srgba}; -use craft_ui::contract::Bind; +use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, RgbModel, Rgba, Srgba}; +use craft_ui::contract::{Bind, Role}; use craft_ui::dialog::{DialogHost, DialogResult, dialog_id}; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, vec2}; @@ -117,3 +117,38 @@ fn a_dialog_reopened_keeps_only_web_colors_and_recalls_the_values_kept_on_ok() { fixture.hold(Modifiers::NONE).idle(2); assert_eq!(edited(&dialogs), Some(values), "Reset returns the typed values"); } + +/// The Full picker's channel rows show a letter after each radio and no channel words; the radios keep their names, and +/// the number fields of a column, the hex field included, start at one x whether or not their row has a radio. +#[trial] +fn the_full_pickers_channel_rows_show_letters_and_align_their_fields() { + let mut fixture = Fixture::new(|ui| { + let models: [&dyn ColorModel; 3] = [&HsbModel, &RgbModel, &LabModel]; + let mut color = PickedColor::rgb(Srgba::rgb(0.2, 0.4, 0.6)); + let _ = ColorPicker::new("Color", Bind::bound(&mut color)).layout(ColorPickerLayout::Full).models(models).show(ui); + }); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + let texts = fixture.texts(); + for word in ["Hue", "Saturation", "Brightness", "Red", "Lightness"] { + assert!(texts.iter().all(|run| run.text != word), "{word} is not shown beside its radio"); + } + for letter in ["H:", "S:", "R:", "L:"] { + assert!(texts.iter().any(|run| run.text == letter), "{letter} is shown"); + } + assert_eq!(fixture.by_role(Role::RADIO_BUTTON).len(), 9, "every channel keeps its radio"); + let fields = fixture.by_role(Role::SPIN_BUTTON); + assert_eq!(fields.len(), 9); + // The columns are found by x, not by tree order: HSB and RGB fields share the first, Lab's the second. + let mut starts: Vec = Vec::new(); + for field in &fields { + if !starts.iter().any(|start| (start - field.rect.min.x).abs() < 0.5) { + starts.push(field.rect.min.x); + } + } + starts.sort_by(f32::total_cmp); + let rects: Vec<_> = fields.iter().map(|field| field.rect).collect(); + assert_eq!(starts.len(), 2, "the fields start in two columns, one per model column: {rects:?}"); + let hex = fixture.by_label("Hex color").expect("the hex field"); + assert!((hex.rect.min.x - starts[0]).abs() < 0.5, "the hex field, which has no radio, starts in the first column: {:?}", hex.rect); +} diff --git a/crates/ui-canvas/src/canvas/navigator_panel.rs b/crates/ui-canvas/src/canvas/navigator_panel.rs index 927a7f156..eea453822 100644 --- a/crates/ui-canvas/src/canvas/navigator_panel.rs +++ b/crates/ui-canvas/src/canvas/navigator_panel.rs @@ -1,7 +1,7 @@ //! `NavigatorPanel`: the Navigator panel's body, the preview box over the zoom row, bound to one view. use crate::canvas::{NavigationOptions, Navigator, NavigatorPreview, NavigatorZoomRow, ProxyColor}; -use crate::contract::{Bind, NoValue, Outcome, Props as _, Show as _, ShowContainer as _}; +use crate::contract::{Bind, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing}; use crate::layout_components::Stack; use crate::runtime::env::Label; use craft_behavior::kurbo::Size; @@ -35,6 +35,8 @@ impl Outcome for NavigatorPanelOutput { /// The Navigator panel (Photoshop's Window, Navigator): the [`Navigator`] preview box over the [`NavigatorZoomRow`], /// both bound to one view. /// +/// - The preview box takes the width and the height the panel leaves above the zoom row, never less than the plot +/// size, so it grows and shrinks with the panel; the document is fitted inside it keeping its aspect. /// - Both parts edit the one bound view. Under Animated Zoom a preview zoom and the row's Zoom In and Zoom Out ease on /// the active canvas: the canvas the view commands reach shows the way to the new view. /// - The row's Zoom In and Zoom Out are the view commands of the active canvas: the canvas steps its own view and @@ -80,10 +82,14 @@ impl<'a> NavigatorPanel<'a> { let NavigatorPanel { label, mut view, document, mut preview, navigation, proxy, enabled } = self; let mut change = EditEvents::new(); let mut invalid_zoom = None; - let shown = Stack::new().enabled(enabled).show(ui, |ui, _| { + let shown = Stack::new().enabled(enabled).fill().show(ui, |ui, _| { // The body runs for the measuring pass and again for the real one, so each run lends the picture. - let preview = - Navigator::new(label.clone(), view.reborrowed(), document).preview(preview.reborrowed()).navigation(navigation).proxy(proxy).show(ui); + let preview = Navigator::new(label.clone(), view.reborrowed(), document) + .preview(preview.reborrowed()) + .navigation(navigation) + .proxy(proxy) + .sizing(Sizing::Fill) + .show(ui); let row = NavigatorZoomRow::new(view.reborrowed(), document).show(ui); invalid_zoom = row.invalid_zoom; change = preview.view.events.clone().into_iter().chain(row.view).collect(); diff --git a/crates/ui-canvas/src/canvas/scrollbars/mod.rs b/crates/ui-canvas/src/canvas/scrollbars/mod.rs index 9f23cbde2..021b78a5b 100644 --- a/crates/ui-canvas/src/canvas/scrollbars/mod.rs +++ b/crates/ui-canvas/src/canvas/scrollbars/mod.rs @@ -1,6 +1,6 @@ //! `CanvasScrollbars`: the scroll bars of a canvas (20.6): a horizontal bar along the bottom of the view and a vertical -//! one along the right, always shown, in the floating look every scroll area has (`ScrollBarLook`): a thin line at rest -//! over the view's edge, the whole bar under the pointer. The thumb is the visible fraction of +//! one along the right, always shown, in the docked look (`ScrollBarKind::Docked`): the thumb has the track's whole +//! thickness at rest and under the pointer. The thumb is the visible fraction of //! the scrollable extent (the document, plus wherever the view has been scrolled past it); drag it to scroll, or press //! the track to page by one screenful. With overscroll on, a document smaller than the window can also be scrolled from //! one edge of the window to the other. With overscroll off the app clamps the view before it draws @@ -20,7 +20,7 @@ use crate::contract::{ use crate::runtime::access::Numeric; use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; -use crate::style::{ComponentStyle, ScrollBarLook, StyleCx}; +use crate::style::{ComponentStyle, ScrollBarKind, ScrollBarLook, StyleCx}; use craft_behavior::kurbo::{Point, Rect as DocRect}; use craft_behavior::scroll::ScrollSpan; use craft_behavior::{Axis, CanvasView, Metrics, PartKey, PartRef, PressPhase}; @@ -242,7 +242,7 @@ impl Component for CanvasScrollbars<'_> { type Output = CanvasScrollbarsOutput; fn style(cx: &StyleCx<'_>, _: CanvasScrollbarsStyleKey) -> ScrollbarsStyle { - ScrollbarsStyle { metrics: Metrics::new(), look: cx.scroll_bar() } + ScrollbarsStyle { metrics: Metrics::new(), look: cx.scroll_bar_of(ScrollBarKind::Docked) } } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { diff --git a/crates/ui-canvas/tests/it/canvas/navigator.rs b/crates/ui-canvas/tests/it/canvas/navigator.rs index 6c0b86657..b6b82f14b 100644 --- a/crates/ui-canvas/tests/it/canvas/navigator.rs +++ b/crates/ui-canvas/tests/it/canvas/navigator.rs @@ -4,7 +4,7 @@ use craft_behavior::CanvasView; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::{Point, Size}; use craft_ui::canvas::navigator_panel::NavigatorPanel; -use craft_ui::canvas::{Canvas, CanvasSpace, NavigationOptions, Navigator}; +use craft_ui::canvas::{AppPaint, Canvas, CanvasSpace, NavigationOptions, Navigator, NavigatorPreview}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::runtime::env::Env; use craft_ui::testing::{Fixture, trial}; @@ -104,3 +104,34 @@ fn a_typed_zoom_lands_exactly_after_its_ease() { } } } + +/// The fitted rect the panel's preview paints the document into, in a room of `room`. +fn fitted_in(room: egui::Vec2) -> Rect { + let fitted = Rc::new(Cell::new(Rect::NOTHING)); + let seen = Rc::clone(&fitted); + let view = Rc::new(Cell::new(CanvasView::new(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)), Point::new(1000.0, 750.0), 1.0))); + let mut fixture = Fixture::new(move |ui| { + let mut given = view.get(); + let seen = Rc::clone(&seen); + let paint = AppPaint::new(move |_, rect: Rect| seen.set(rect)); + let _ = NavigatorPanel::new("Navigator", Bind::bound(&mut given), DOCUMENT).preview(NavigatorPreview::Paint(paint)).show(ui); + view.set(given); + }); + fixture.room(room); + fixture.settle(); + fitted.get() +} + +#[trial] +fn panel_preview_grows_with_the_room_and_keeps_the_document_aspect() { + let aspect = DOCUMENT.width as f32 / DOCUMENT.height as f32; + let small = fitted_in(vec2(200.0, 260.0)); + let large = fitted_in(vec2(400.0, 700.0)); + assert!(large.width() > small.width() && large.height() > small.height(), "the preview grows with the panel: {small:?} -> {large:?}"); + for fitted in [small, large] { + assert!((fitted.width() / fitted.height() - aspect).abs() < 0.02, "the document keeps its aspect: {fitted:?}"); + } + let tall = fitted_in(vec2(200.0, 700.0)); + assert!(tall.height() > small.height() || tall.width() <= small.width() + 0.5, "extra height alone never widens the fit: {small:?} {tall:?}"); + assert!(fitted_in(vec2(200.0, 260.0)).width() <= small.width() + 0.5, "the preview shrinks back with the panel"); +} diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index e5d94a6f3..d420f42cb 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -672,7 +672,7 @@ impl ShapeHooks for BodyHooks<'_> { if (band || matches!(props.mount, Mount::Viewport { .. } | Mount::Window { .. })) && let Some(viewport) = os_window(props, cx.core.memory.ctx(), cx.core.id, &cx.core.env) { - self.window_os(viewport, cx); + self.window_os(viewport, props, cx); self.window_movable(viewport, cx); } self.pane_drag(props, cx); diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 9fd863124..ffe88ce16 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -97,6 +97,7 @@ pub(super) struct WindowMode { restore: Placement, began: Option, moving: Option, + sizing: Option, /// The index in `GRIPS` of the grip a drag holds, from its `DragStart` to its release: `move_parts` keeps it /// declared when the drag flips the layer to a side whose placement holds its edge, so the drag keeps its result. held: Option, @@ -126,6 +127,20 @@ struct WindowMove { begun: bool, } +/// A resize of a viewport mount's OS window that its caller sizes ([`Resize::by_caller`](crate::contract::overlay::Resize::by_caller)), +/// which the app runs, from its Begin to its Commit or Cancel. Rects are the window's outer rect in desktop points. +#[derive(Clone, Copy, PartialEq)] +struct WindowSize { + /// The index in `GRIPS` of the grip the drag holds. + grip: usize, + /// The pressed point in desktop points. + pressed: Pos2, + /// Where the window was when the resize began; a cancel reports it again. + start: Rect, + /// The rect the resize reported last. + at: Rect, +} + /// The outer rect of a viewport mount's OS window as the container last learnt it: the window's placement, which the /// container keeps as a layer keeps its own. #[derive(Clone, Default)] @@ -334,7 +349,14 @@ impl BodyHooks<'_> { if mode.kind == Some(kind) { mode = WindowMode::default(); } else { - mode = WindowMode { kind: Some(kind), restore: current.clone(), began: Some(current.rect_over(rect)), moving: None, held: None }; + mode = WindowMode { + kind: Some(kind), + restore: current.clone(), + began: Some(current.rect_over(rect)), + moving: None, + sizing: None, + held: None, + }; self.reports.push(step(current.rect_over(rect), GesturePhase::Begin)); } } @@ -392,7 +414,7 @@ impl BodyHooks<'_> { // A band that moves the window below starts the OS move of the window the layer is shown in. if overlay.moves_window { let viewport = pass::current_viewport(&cx.core.ctx); - self.window_os(viewport, cx); + self.window_os(viewport, props, cx); return; } let id = cx.core.id; @@ -452,9 +474,18 @@ impl BodyHooks<'_> { } /// A press on the move band or a grip of a container in an OS window starts the OS move or resize; the band of a - /// window whose move the app runs starts that move instead ([`Self::window_move`]). Where the platform answers the - /// hit test (`answered_by_platform`), the parts stand for its sink only. - pub(super) fn window_os(&mut self, viewport: ViewportId, cx: &mut Cx<'_, C>) { + /// window whose move the app runs starts that move instead ([`Self::window_move`]), and a grip of a window its + /// caller sizes that resize ([`Self::window_resize`]). Where the platform answers the hit test + /// (`answered_by_platform`), the parts it takes stand for its sink only; the grips of a window its caller sizes + /// are never its. + pub(super) fn window_os(&mut self, viewport: ViewportId, props: &ContainerProps, cx: &mut Cx<'_, C>) { + let by_caller = overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller); + if by_caller { + let limits = overlay_of(props).map(|overlay| Limits::new(overlay, window_min(props, cx.style.metrics().min_size))); + if let Some(limits) = limits { + self.window_resize(viewport, &limits, cx); + } + } if answered_by_platform(&cx.core.ctx, viewport) { return; } @@ -469,12 +500,68 @@ impl BodyHooks<'_> { windows::act(&cx.core.ctx, viewport, WindowAction::StartMove); } for (index, (dx, dy, _)) in GRIPS.into_iter().enumerate() { - if started((GRIP, Some(index as u64))) { + if !by_caller && started((GRIP, Some(index as u64))) { windows::act(&cx.core.ctx, viewport, WindowAction::StartResize(edge_of(dx, dy))); } } } + /// The resize of an OS window its caller sizes: a drag of a grip moves the edges the grip holds by the pointer's + /// travel since the press, within `limits`, and each step is reported through `placement_changed` as a layer's + /// resize is, from Begin to Commit or Cancel. The app sends the window no size: the caller places the size it + /// makes of the steps. The press holds the pointer, so its moves arrive while it is outside the window. A pointer + /// move of this pass is relative to where the window reports itself now, as in [`Self::window_move`]. + fn window_resize(&mut self, viewport: ViewportId, limits: &Limits, cx: &mut Cx<'_, C>) { + let ctx = cx.core.ctx.clone(); + let Some(facts) = windows::WindowHost::of(&ctx).facts(viewport) else { return }; + let outer = facts.outer.unwrap_or(facts.inner); + let phase = |index: usize| cx.core.results.get(&(GRIP, Some(index as u64))).map(|result| result.press.phase); + let change = |rect: Rect, phase: GesturePhase, grip: usize| { + let (dx, dy, _) = GRIPS[grip]; + PlacementChange { rect, phase, pointer: None, kind: PlacementKind::Size(edge_of(dx, dy)) } + }; + let resized = |sizing: &WindowSize, desktop: Pos2| { + let (dx, dy, _) = GRIPS[sizing.grip]; + limits.resized(sizing.start, dx, dy, desktop - sizing.pressed) + }; + let Some(mut sizing) = self.mode.sizing else { + let started = (0..GRIPS.len()).find_map(|index| match phase(index)? { + PressPhase::DragStart { start, pos, .. } => Some((index, start.origin, pos)), + _ => None, + }); + let Some((grip, origin, pos)) = started else { return }; + let sizing = WindowSize { grip, pressed: facts.inner.min + origin.to_vec2(), start: outer, at: outer }; + self.reports.push(change(outer, GesturePhase::Begin, grip)); + let at = resized(&sizing, facts.inner.min + pos.to_vec2()); + self.reports.push(change(at, GesturePhase::Update, grip)); + self.mode.sizing = Some(WindowSize { at, ..sizing }); + self.mode.held = Some(grip); + return; + }; + let ended = match phase(sizing.grip) { + Some(PressPhase::Cancel { .. }) => Some(GesturePhase::Cancel), + Some(PressPhase::Down { .. } | PressPhase::Drag { .. } | PressPhase::Held { .. } | PressPhase::DragStart { .. }) => None, + // A release, or a press that ended in a pass the container did not run. + _ => Some(GesturePhase::Commit), + }; + if let Some(ended) = ended { + let rect = if ended == GesturePhase::Cancel { sizing.start } else { sizing.at }; + self.reports.push(change(rect, ended, sizing.grip)); + self.mode.sizing = None; + self.mode.held = None; + return; + } + let moved = pointer::pass_pointer(&ctx) + .events + .iter() + .rev() + .find_map(|event| if let PointerEvent::Moved { at, .. } = event { Some(*at) } else { None }); + let Some(at) = moved.map(|at| resized(&sizing, facts.inner.min + at.to_vec2())).filter(|at| *at != sizing.at) else { return }; + sizing.at = at; + self.reports.push(change(at, GesturePhase::Update, sizing.grip)); + self.mode.sizing = Some(sizing); + } + /// The move of an OS window whose app runs it ([`windows::keeps_app_drag`]): a drag of the move band keeps the /// pressed point under the pointer, and each step is reported through `placement_changed` as a layer's move is, /// from Begin to Commit or Cancel. Where the platform tracks the OS's moves ([`Caps::OS_MOVES_TRACKED`]) the OS @@ -577,11 +664,15 @@ impl BodyHooks<'_> { let now = facts.outer.unwrap_or(facts.inner); let placed = &mut cx.core.memory.shown::(sub(sub(cx.core.id, "body"), "window_placed")).0; let before = placed.replace(now); - if self.mode.moving.is_some() { + if self.mode.moving.is_some() || self.mode.sizing.is_some() { return; } let Some(before) = before.filter(|before| *before != now) else { return }; let kind = resized_edge(before, now).map_or(PlacementKind::Move, PlacementKind::Size); + // The size of a window its caller sizes is the caller's own: the window reports only its moves. + if matches!(kind, PlacementKind::Size(_)) && overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller) { + return; + } self.reports.push(PlacementChange { rect: now, phase: GesturePhase::Commit, pointer: None, kind }); } @@ -635,6 +726,7 @@ impl BodyHooks<'_> { return; } let pinned = overlay_of(props).map_or(Pinned::NONE, |overlay| Pinned::of(overlay, &ctx, pcx.id, pcx.env.direction().is_rtl())); + let caller_sizes = overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller); for (index, (dx, dy, cursor)) in GRIPS.into_iter().enumerate() { if held != Some(index) && !grip_stands(edges, pinned, dx, dy) { continue; @@ -654,7 +746,8 @@ impl BodyHooks<'_> { .cursor(cursor) .pointer_only(reason) .over(); - if let Some(hit) = exclusive(WindowHit::Resize(edge_of(dx, dy))) { + // The grips of a window its caller sizes are the app's (`window_resize`), never the platform's. + if let Some(hit) = exclusive(WindowHit::Resize(edge_of(dx, dy))).filter(|_| !caller_sizes) { part.exclusive(hit); } } diff --git a/crates/ui-contract/src/contract/ghost.rs b/crates/ui-contract/src/contract/ghost.rs index 08c027b89..7a30d1267 100644 --- a/crates/ui-contract/src/contract/ghost.rs +++ b/crates/ui-contract/src/contract/ghost.rs @@ -150,18 +150,24 @@ fn paint_drag_badge(draw: &Draw<'_>, env: &Env, at: Pos2, text: &str) { } /// The drop mark: bands of the drop rule on a halo of the panel surface one thin stroke wide, so the mark reads over -/// any content. An area mark is the same band along the inside of its rect. +/// any content. An area mark is the same band along the inside of its rect; a region is also washed with the rule's +/// colour, so the area the payload takes reads as one piece, and carries its line band. fn paint_mark(painter: &egui::Painter, env: &Env, mark: DropMark) { let look = rule_look(&env.tokens, RuleKind::DropMark); let ppp = painter.ctx().pixels_per_point(); let width = look.width.points(ppp); let halo = RuleWidth::Points(env.tokens.stroke.thin).points(ppp); + let outline = |rect: Rect| { + let inside = rect.shrink(width / 2.0 + halo); + let corners = [inside.left_top(), inside.right_top(), inside.right_bottom(), inside.left_bottom()]; + (0..corners.len()).map(move |at| (corners[at], corners[(at + 1) % corners.len()])) + }; let segments: Vec<(Pos2, Pos2)> = match mark { DropMark::Line { from, to } => vec![(from, to)], - DropMark::Into(rect) | DropMark::Split(rect) => { - let inside = rect.shrink(width / 2.0 + halo); - let corners = [inside.left_top(), inside.right_top(), inside.right_bottom(), inside.left_bottom()]; - (0..corners.len()).map(|at| (corners[at], corners[(at + 1) % corners.len()])).collect() + DropMark::Into(rect) => outline(rect).collect(), + DropMark::Region { area, line } => { + painter.rect_filled(area, CornerRadius::ZERO, look.color.gamma_multiply(craft_theme::Opacity::WASH)); + outline(area).chain(line.map(|[from, to]| (from, to))).collect() } }; let band = |(from, to): (Pos2, Pos2), half: f32| Rect::from_two_pos(from, to).expand(half); diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index 0abbea9a6..fe80781be 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -356,11 +356,12 @@ impl Host for ViewportHost { let open = ViewportOpen { id, title: title.as_str(), - // A placed rect is the caller's size for the window, then a resizable fallback's default size, as the layer - // takes it; the measured size is for a window sized by content: what its body took in the window, recorded - // once the window reported its place (`steps::record_body_size`). + // A placed rect is the caller's size for the window, within the window's limits, which the OS would clamp it + // to; then a resizable fallback's default size, as the layer takes it; the measured size is for a window + // sized by content: what its body took in the window, recorded once the window reported its place + // (`steps::record_body_size`). size: placed - .map(|rect| rect.size()) + .map(|rect| self.overlay.size_limits.clamp(rect.size())) .or(self.overlay.size.filter(|_| self.overlay.fit == overlay::OverlayFit::Resizable)) .or_else(measured), // A resizable window takes its default or content size to open; from then on its size is the user's. @@ -369,8 +370,9 @@ impl Host for ViewportHost { spec: &spec, limits: (Some(self.overlay.size_limits.min), self.overlay.size_limits.max), position: placed.map(|rect| rect.min), - // The full-window overlay has no grips (it covers the window), but its OS window is one the user sizes. - resizable: full_window || self.overlay.resize.edges != ResizeEdges::NONE, + // The full-window overlay has no grips (it covers the window), but its OS window is one the user sizes. A + // window its caller sizes takes no resize from the OS: the app runs its grips. + resizable: full_window || (self.overlay.resize.edges != ResizeEdges::NONE && !self.overlay.resize.by_caller), }; let dismissed = &mut self.dismissed; windows::show_viewport(&ctx, &open, |ui| { diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index 700b14911..ac085d4ec 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -112,17 +112,21 @@ pub struct Resize { /// The edges whose grips resize the layer; a corner grip needs both its edges. A placement that holds an edge /// still keeps its grip away. pub edges: ResizeEdges, + /// The caller turns each resize into a size of its own (a window as large as its content in whole steps). In an + /// OS window the app runs the grips' drag, reports each step, and the OS offers no resize of its own; the window + /// takes the size the caller places. A layer resizes as any other and reports the same steps. + pub by_caller: bool, } impl Resize { /// The layer keeps its size. - pub const NONE: Resize = Resize { edges: ResizeEdges::NONE }; + pub const NONE: Resize = Resize { edges: ResizeEdges::NONE, by_caller: false }; /// Grips on every free edge and corner. - pub const GRIPS: Resize = Resize { edges: ResizeEdges::ALL }; + pub const GRIPS: Resize = Resize { edges: ResizeEdges::ALL, by_caller: false }; /// Grips on the given edges only. pub fn edges(edges: ResizeEdges) -> Resize { - Resize { edges } + Resize { edges, by_caller: false } } } @@ -192,6 +196,11 @@ impl SizeLimits { SizeLimits { min: self.min + extra, max: self.max.map(|max| max + extra) } } + /// `size` within these limits; the minimum wins over a smaller maximum. + pub fn clamp(self, size: Vec2) -> Vec2 { + size.min(self.max.unwrap_or(Vec2::INFINITY)).max(self.min) + } + /// Whether every value is finite and non-negative, the maximum is no less than the minimum and no value is /// above [`Self::BOUND`]. pub fn valid(self) -> bool { diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 2dfc1b999..5f1f18842 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -319,6 +319,12 @@ impl Overlay { self } + /// The caller sizes the layer or OS window from the resizes its grips report ([`Resize::by_caller`]). + pub fn sized_by_caller(mut self) -> Overlay { + self.resize.by_caller = true; + self + } + /// Rank `Window` and no backdrop. pub fn modeless(mut self) -> Overlay { self.rank = Rank::Window; diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index a4d18bf78..8257570d5 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -21,6 +21,9 @@ pub enum Wrap { Line, /// Wraps at the room's width. Wrap, + /// One line, cut at the room's edge with no ellipsis, as many characters as fit: tabs that shrink to their first + /// letters. The full text is the tooltip and accessible name, as for an elided run. + Clip, /// One line, cut with an ellipsis at the end: names, titles, labels beside fixed controls. Elide, /// One line, cut with an ellipsis at the start: anything whose end says the most. @@ -267,14 +270,16 @@ impl TextRun<'_> { fn job<'s>(&self, env: &TextEnv<'_>, parts: impl Iterator, &'s str)>, max_width: f32) -> LayoutJob { let elide = self.wrap.cuts(); + let clip = self.wrap == Wrap::Clip; let wrap = TextWrapping { max_width: if self.wrap == Wrap::Line { f32::INFINITY } else { max_width }, max_rows: match self.wrap { Wrap::Clamp(lines) => usize::from(lines.max(1)), - _ if elide => 1, + _ if elide || clip => 1, _ => usize::MAX, }, - break_anywhere: elide, + break_anywhere: elide || clip, + overflow_character: if clip { None } else { TextWrapping::default().overflow_character }, ..TextWrapping::default() }; let mut job = paragraph_job(env.direction, self.ltr, wrap); diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index 54f178798..01f86fa21 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -60,8 +60,14 @@ pub enum DropMark { }, /// The payload goes into this rect. Into(Rect), - /// This rect is split, the payload taking one side. - Split(Rect), + /// The payload will occupy this area once dropped, such as the rect a docked panel takes beside a group. + #[non_exhaustive] + Region { + /// The rect the payload takes. + area: Rect, + /// Where in it the payload goes in, such as the tab position of a panel joining a group. + line: Option<[Pos2; 2]>, + }, } impl DropMark { @@ -70,13 +76,23 @@ impl DropMark { DropMark::Line { from, to } } + /// The payload will occupy `area`. + pub const fn region(area: Rect) -> Self { + DropMark::Region { area, line: None } + } + + /// The payload will occupy `area` and goes in at the line from `from` to `to`. + pub const fn region_at(area: Rect, from: Pos2, to: Pos2) -> Self { + DropMark::Region { area, line: Some([from, to]) } + } + /// The mark with every point passed through `map`. pub(crate) fn mapped(self, map: impl Fn(Pos2) -> Pos2) -> Self { let rect = |rect: Rect| Rect::from_two_pos(map(rect.min), map(rect.max)); match self { DropMark::Line { from, to } => DropMark::Line { from: map(from), to: map(to) }, DropMark::Into(target) => DropMark::Into(rect(target)), - DropMark::Split(target) => DropMark::Split(rect(target)), + DropMark::Region { area, line } => DropMark::Region { area: rect(area), line: line.map(|line| line.map(&map)) }, } } } @@ -399,12 +415,17 @@ fn source_viewport(ctx: &Context) -> Option { board(ctx, |board| board.session.as_ref().map(|session| session.viewport)) } +/// Whether the running session started in a window other than `viewport`. That window holds the pointer while its +/// button is down, so `viewport` gets no pointer events of its own and still holds the place it saw the pointer last. +pub(crate) fn runs_elsewhere(ctx: &Context, viewport: ViewportId) -> bool { + source_viewport(ctx).is_some_and(|source| source != viewport) +} + /// The pointer in `viewport` for a drag that started in another window: the desktop pointer mapped into this /// window, when it lies inside. `None` without a session, in the source window, or outside this window. #[doc(hidden)] pub fn cross_window_pointer(ctx: &Context, viewport: ViewportId) -> Option { - let source = source_viewport(ctx)?; - (source != viewport).then(|| WindowHost::of(ctx).pointer_in(viewport)).flatten() + runs_elsewhere(ctx, viewport).then(|| WindowHost::of(ctx).pointer_in(viewport)).flatten() } /// The running session's payload whose type is `payload` and the pointer in screen space. For files the OS drags, the diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index b6ac63a55..de412613f 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -149,6 +149,7 @@ pub(crate) fn show_body_layer(ctx: &Context, body_layer: BodyLayer, body: imp ctx.set_transform_layer(layer, transform); ctx.set_sublayer(parent, layer); egui::Area::new(layer.id) + .fade_in(false) .order(layer.order) .pivot(egui::Align2::LEFT_TOP) .fixed_pos(at) @@ -220,9 +221,11 @@ pub(crate) struct LayerShown { pub layer: LayerId, } -/// Shows an overlay layer: an `Area` with its left-top pivot at `spec.at`, never egui's default pivot. +/// Shows an overlay layer: an `Area` with its left-top pivot at `spec.at`, never egui's default pivot. The motion +/// service fades a layer in (`motion::layer_presence`), so egui's own fade-in of a new `Area` is off. pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut egui::Ui)) -> LayerShown { let shown = egui::Area::new(spec.id) + .fade_in(false) .order(spec.tier.order()) .pivot(egui::Align2::LEFT_TOP) .fixed_pos(spec.at) @@ -256,6 +259,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { None => vec![screen], }; egui::Area::new(id) + .fade_in(false) .order(tier.order()) .pivot(egui::Align2::LEFT_TOP) .fixed_pos(screen.min) diff --git a/crates/ui-contract/src/runtime/egui/viewports.rs b/crates/ui-contract/src/runtime/egui/viewports.rs index bd009c5d0..65f0231d6 100644 --- a/crates/ui-contract/src/runtime/egui/viewports.rs +++ b/crates/ui-contract/src/runtime/egui/viewports.rs @@ -27,7 +27,7 @@ pub(crate) struct Spec<'a> { pub os_buttons: bool, /// The smallest inner size. pub min_size: Option, - /// The largest inner size. + /// The largest inner size; `Vec2::INFINITY` lifts an earlier one. pub max_size: Option, /// The window level. pub level: WindowLevel, diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index f94ead91c..3f5076ad0 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -163,8 +163,9 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { // Every pass reads its own input and the frame's latches, so a second pass of a frame builds the same // modifiers from its own (event-free) input and counts no press twice. let mods = with_latched(read.mods, latched); - // A drag that started in another window reaches this one through the desktop pointer (8.4). - if read.pos.is_none() { + // A drag that started in another window reaches this one through the desktop pointer (8.4), never at the place + // this window saw the pointer last: the source window holds the pointer, and the window may have had no exit. + if drag::runs_elsewhere(ctx, viewport) { read.pos = drag::cross_window_pointer(ctx, viewport); } let wheel = input::wheel_read(ctx, WHEEL_LINE_POINTS, WHEEL_PAGE_POINTS); @@ -685,6 +686,19 @@ pub(crate) fn with_hover(ctx: &Context, viewport: ViewportId, f: impl FnOnce( PerViewport::::with(ctx, viewport, |record| f(record.hover.as_ref().map(|(_, _, under)| under), record.captured)) } +/// Whether a shape the component `id` registered shows hover in the running pass, by the pass's one resolution of +/// what lies under the pointer ([`Under`]): it takes the press there, or it is the topmost shape and takes none. A +/// container reads it for the components in its body before they run. While a press is open it holds for none: only +/// the press's target hovers, and that target reads it from its press. +pub fn hovers(ctx: &Context, id: Id) -> bool { + with_hover(ctx, pass::current_viewport(ctx), |under, captured| { + !captured + && under.is_some_and(|under| { + [under.press.click, under.press.drag, under.hover_top].into_iter().flatten().any(|(winner, _)| winner.owner == id) + }) + }) +} + /// The resolutions of what lies under a point the running viewport's latest pass made. #[cfg(feature = "testing")] pub(crate) fn resolutions(ctx: &Context) -> u32 { diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index f3ec67e21..9a1d90744 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -235,7 +235,8 @@ pub(crate) fn set_input(ctx: &Context) { /// or resize [`act`] handed the OS, when the input brings no release of its own (where the OS sends one, a second /// would turn into a click), once the system tells the button is up, or where it does not tell, on the first input /// after the hand-off; and, where the OS resizes undecorated windows from their edges -/// ([`Caps::OS_RESIZES_UNDECORATED`]), a size change under a held primary press. While the OS runs a tracked move +/// ([`Caps::OS_RESIZES_UNDECORATED`]), a size change of a window the OS may resize under a held primary press (the +/// size of a window that is not resizable is the app's own). While the OS runs a tracked move /// ([`Caps::OS_MOVES_TRACKED`]) it sends no key events, so every window's modifiers are the system's command modifier /// alone. Reads only the raw input, the system's button and modifier state and the viewport's record. Returns whether /// it added an event. @@ -257,7 +258,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool { input.events.push(egui::Event::ModifiersChanged(modifiers)); } let (released, handed_off) = PerViewport::::with(ctx, viewport, |record| { - let resized = matches!((record.last_inner_size, size), (Some(before), Some(now)) if before != now); + let resized = record.resizable != Some(false) && matches!((record.last_inner_size, size), (Some(before), Some(now)) if before != now); record.last_inner_size = size.or(record.last_inner_size); let handed_off = record.handoff.is_some_and(|handoff| handoff.released.is_none() && handoff.pass < pass) && held != Some(true); if handed_off { @@ -309,11 +310,17 @@ pub(crate) fn blocking_modal(ctx: &Context) -> Option { /// It reads only this pass's facts, so the mount, the body (which runs inside the child's pass) and the window steps /// agree within a pass. pub(crate) fn mount_window(ctx: &Context, id: Id) -> bool { + let current = pass::current_viewport(ctx); + let opener = if current == viewports::viewport_id(id) { viewports::parent(ctx) } else { current }; + opens_over(ctx, opener) +} + +/// Whether a viewport mount opened from `opener`'s window shows in an OS window of its own: the rule of +/// [`mount_window`]. +fn opens_over(ctx: &Context, opener: ViewportId) -> bool { if !WindowHost::of(ctx).viewports_available() { return false; } - let current = pass::current_viewport(ctx); - let opener = if current == viewports::viewport_id(id) { viewports::parent(ctx) } else { current }; let shell = shell_of(ctx, opener); let covers = match shell.window.state { WindowState::Fullscreen => true, diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index b6be02411..5ce81ebda 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -77,6 +77,13 @@ impl WindowHost { base_shell(&self.ctx).caps.contains(Caps::VIEWPORTS) && viewports::available(&self.ctx) } + /// Whether a viewport mount opened in the running viewport's pass shows in an OS window of its own, and not in + /// its fallback layer: OS viewports are available and the running window is neither full screen nor, on Wayland, + /// maximized. + pub fn opens_windows(&self) -> bool { + super::opens_over(&self.ctx, pass::current_viewport(&self.ctx)) + } + /// Whether the platform reports where windows are on the desktop and moves them there; false on Wayland. pub fn positions_reported(&self) -> bool { base_shell(&self.ctx).window_positions() diff --git a/crates/ui-contract/src/runtime/windows/viewport.rs b/crates/ui-contract/src/runtime/windows/viewport.rs index 55af6c762..62cc36634 100644 --- a/crates/ui-contract/src/runtime/windows/viewport.rs +++ b/crates/ui-contract/src/runtime/windows/viewport.rs @@ -83,7 +83,9 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im // A tool window has no OS caption buttons; its panel's title row carries a close action. os_buttons: !(spec.kind == WindowKind::Tool && captions.is_none() && chrome != WindowChrome::Native), min_size: open.limits.0, - max_size: open.limits.1, + // egui sends a limit only when it has one: an open window always carries its maximum, unbounded when the + // caller has none, so a lifted maximum reaches the OS. + max_size: open.limits.1.or(opened.then_some(Vec2::INFINITY)), level, resizable: open.resizable, taskbar: spec.taskbar, diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index 31e4cb647..bdc0c8ff8 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -3,7 +3,8 @@ use super::key::{EnvKey, Ink}; use super::look::{DataColor, FocusLook, StyleColor, SurfaceKind, SurfaceLook, TrackLook}; use super::paint::{ - HandleLook, MarkerLook, ResetMarkLook, RuleKind, RuleLook, ScrollBarLook, handle_look, marker_look, reset_mark_look, rule_look, scroll_bar_look, + HandleLook, MarkerLook, ResetMarkLook, RuleKind, RuleLook, ScrollBarKind, ScrollBarLook, handle_look, marker_look, reset_mark_look, rule_look, + scroll_bar_look_of, }; use super::surface::{SurfaceStyle, surface_style}; use super::tokens::UiTokens; @@ -430,7 +431,12 @@ impl<'a> StyleCx<'a> { /// The look of a scroll bar. pub fn scroll_bar(&self) -> ScrollBarLook { - scroll_bar_look(self.tokens) + self.scroll_bar_of(ScrollBarKind::Floating) + } + + /// The look of a scroll bar of `kind`. + pub fn scroll_bar_of(&self, kind: ScrollBarKind) -> ScrollBarLook { + scroll_bar_look_of(self.tokens, kind) } /// The state layer: the theme's hover and press fills, clear at rest and while disabled. A part declared diff --git a/crates/ui-contract/src/style/mod.rs b/crates/ui-contract/src/style/mod.rs index 9d2f53ae8..cfde3b625 100644 --- a/crates/ui-contract/src/style/mod.rs +++ b/crates/ui-contract/src/style/mod.rs @@ -25,7 +25,7 @@ pub use cx::{GlyphRole, StyleCx, VariantParts}; pub use key::{EnvKey, Ink, StyleKey}; pub(crate) use look::StyleView; pub use look::{ComponentStyle, Corners, DataColor, FocusLook, IconLook, StyleColor, SurfaceKind, SurfaceLook, TextLook, TrackLook}; -pub use paint::{HandleLook, MarkerLook, ResetMarkLook, ResizeLineLook, RuleKind, RuleLook, RuleWidth, ScrollBarLook, resize_line_look}; +pub use paint::{HandleLook, MarkerLook, ResetMarkLook, ResizeLineLook, RuleKind, RuleLook, RuleWidth, ScrollBarKind, ScrollBarLook, resize_line_look}; pub(crate) use paint::{min_thumb, scroll_bar_look}; pub use replacements::{DuplicateStyle, StyleReplacements}; pub use span::Span; diff --git a/crates/ui-contract/src/style/paint.rs b/crates/ui-contract/src/style/paint.rs index c4ac3e795..73db34566 100644 --- a/crates/ui-contract/src/style/paint.rs +++ b/crates/ui-contract/src/style/paint.rs @@ -170,9 +170,21 @@ pub(crate) fn marker_look(tokens: &UiTokens) -> MarkerLook { } } -/// A scroll bar's track and thumb: one floating indicator for every scroll area, over the content at its edge. At rest -/// the thumb is a thin dim line along the track's outer edge and the track is clear; under the pointer or while pressed -/// the thumb takes the track's whole thickness over a tinted track. +/// Which of the two scroll bar looks a bar has. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum ScrollBarKind { + /// The indicator of a scroll area, over the content at its edge. At rest the thumb is a thin dim line along the + /// track's outer edge and the track is clear; under the pointer or while pressed the thumb takes the track's whole + /// thickness over a tinted track. + #[default] + Floating, + /// The bar beside a canvas view, always shown: the thumb has the track's whole thickness in every state, on a + /// `surface.chrome` track, quiet at rest (`line.control_edge`). + Docked, +} + +/// A scroll bar's track and thumb, of a [`ScrollBarKind`]. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct ScrollBarLook { @@ -197,17 +209,36 @@ pub(crate) fn min_thumb(tokens: &UiTokens) -> f32 { } pub(crate) fn scroll_bar_look(tokens: &UiTokens) -> ScrollBarLook { + scroll_bar_look_of(tokens, ScrollBarKind::Floating) +} + +pub(crate) fn scroll_bar_look_of(tokens: &UiTokens, kind: ScrollBarKind) -> ScrollBarLook { let c = &tokens.color; let clear = style_color(Rgba::TRANSPARENT); - let thumb = Stateful::new(style_color(c.text.faint)).off(craft_theme::States::new( - style_color(c.text.faint), - style_color(c.text.muted), - style_color(c.text.normal), - style_color(c.state.disabled_fill), - )); + let disabled = style_color(c.state.disabled_fill); + let thumb = match kind { + ScrollBarKind::Floating => Stateful::new(style_color(c.text.faint)).off(craft_theme::States::new( + style_color(c.text.faint), + style_color(c.text.muted), + style_color(c.text.normal), + disabled, + )), + ScrollBarKind::Docked => Stateful::new(style_color(c.line.control_edge)).off(craft_theme::States::new( + style_color(c.line.control_edge), + style_color(c.text.faint), + style_color(c.text.muted), + disabled, + )), + }; let hover = style_color(c.state.hover); - let track = Stateful::new(clear).off(craft_theme::States::new(clear, hover, hover, clear)); - let (thickness, rest) = (tokens.size.handle.sm, tokens.stroke.thick); + let (thickness, thin) = (tokens.size.handle.sm, tokens.stroke.thick); + let (track, rest) = match kind { + ScrollBarKind::Floating => (Stateful::new(clear).off(craft_theme::States::new(clear, hover, hover, clear)), thin), + ScrollBarKind::Docked => { + let chrome = style_color(c.surface.chrome); + (Stateful::new(chrome).off(craft_theme::States::new(chrome, hover, hover, chrome)), thickness) + } + }; ScrollBarLook { track, thumb, diff --git a/crates/ui-contract/tests/it/paint/painters.rs b/crates/ui-contract/tests/it/paint/painters.rs index 16347fe03..a5ba01714 100644 --- a/crates/ui-contract/tests/it/paint/painters.rs +++ b/crates/ui-contract/tests/it/paint/painters.rs @@ -185,6 +185,50 @@ fn ant_edges_are_whole_device_pixels_at_a_fractional_scale() { } } +/// A docked scroll bar (the canvas's) has the same thumb across the track at rest and under the pointer, on a +/// `surface.chrome` track. +#[trial] +fn a_docked_scroll_bar_keeps_its_width_at_rest_and_under_the_pointer() { + use craft_behavior::{Axis, ScrollSpan}; + use craft_theme::{Contrast, ControlSize, Mode, Variant}; + use craft_ui::primitives::ScrollBar; + use craft_ui::style::{Flags, ScrollBarKind, State, StateMix, StateSet}; + use egui::{Rect, Shape}; + + let tokens = craft_ui::testing::style::tokens(Mode::Dark, Contrast::Standard); + let look = craft_ui::testing::style::with_cx(&egui::Context::default(), &tokens, Variant::SECONDARY, ControlSize::Md, |cx| { + cx.scroll_bar_of(ScrollBarKind::Docked) + }); + let span = ScrollSpan::new(0.0..400.0, 100.0..300.0); + for (axis, rtl) in [(Axis::Y, false), (Axis::Y, true), (Axis::X, false)] { + let track = match axis { + Axis::X => Rect::from_min_max(pos2(0.0, 100.0), pos2(200.0, 100.0 + look.thickness)), + _ => Rect::from_min_max(pos2(100.0, 0.0), pos2(100.0 + look.thickness, 200.0)), + }; + let thumb = |state: State, mix: StateMix| { + let shapes = ScrollBar::shapes(&look, track, axis, rtl, &span, &StateSet::new(state, Flags::empty(), mix)); + match shapes.last() { + Some(Shape::Rect(shape)) => shape.rect, + other => panic!("the thumb is a rect: {other:?}"), + } + }; + let (rest, hover) = (thumb(State::Rest, StateMix::REST), thumb(State::Hover, StateMix::new(1.0, 0.0, 0.0))); + assert_eq!(rest, hover, "{axis:?} rtl {rtl}: the thumb is the same at rest and under the pointer"); + let across = |rect: Rect| if axis == Axis::X { rect.height() } else { rect.width() }; + assert!((across(rest) - across(track)).abs() < EPS, "{axis:?}: the thumb fills the track"); + let fill = |state: State, mix: StateMix| match ScrollBar::shapes(&look, track, axis, rtl, &span, &StateSet::new(state, Flags::empty(), mix)) + .as_slice() + { + [Shape::Rect(track), Shape::Rect(thumb)] => (track.fill, thumb.fill), + other => panic!("a track and a thumb: {other:?}"), + }; + let (track_fill, thumb_fill) = fill(State::Rest, StateMix::REST); + let (_, hover_fill) = fill(State::Hover, StateMix::new(1.0, 0.0, 0.0)); + assert_ne!(thumb_fill, track_fill, "{axis:?}: the resting thumb shows on its track"); + assert_ne!(thumb_fill, hover_fill, "{axis:?}: the thumb takes a stronger colour under the pointer"); + } +} + /// Every scroll bar rests as a thin line along its track's outer edge and shows its thumb across the whole track under /// the pointer, at the same place along the bar. #[trial] diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 7ac1e5752..3206baa71 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -32,7 +32,7 @@ use bar::panel_names; pub(super) use bar::{BarRecord, CHEVRON, bar_band, bar_name, bar_slots, describe_chevron, paint_chevron, show_bar}; use sizing::group_sizes; -pub use sizing::{GroupSize, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds}; +pub use sizing::{GroupSize, column_cells, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds}; const DIVIDER: PartKey = PartKey::new("divider"); const EDGE: PartKey = PartKey::new("edge"); @@ -293,10 +293,16 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { } } +/// Where the groups of `column` sit in `rect`, the column's rect with its bar `bar`, as the column lays them out while +/// no divider between them is dragged. +pub fn group_rects

(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, rect: Rect, bar: ColumnBar, sizes: &DockSizes) -> Vec { + column_plan(column, spec, rect, bar, sizes, |_, _| None).groups +} + /// The bar and body of the column in `rect`, and the groups stacked in the body, with the drags `drags` makes of /// the dividers between open groups (the divider's part index and the divider as laid out before the drag). A /// column in a floating window has an empty bar on top. -fn column_plan( +fn column_plan

( column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, rect: Rect, @@ -310,7 +316,7 @@ fn column_plan( } /// [`column_plan`] for a column whose `bar` and `body` rects are known. -fn body_plan( +fn body_plan

( column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, bar: Rect, diff --git a/crates/ui-panels/src/docking/dock_column/sizing.rs b/crates/ui-panels/src/docking/dock_column/sizing.rs index 879a7afce..31bdba43a 100644 --- a/crates/ui-panels/src/docking/dock_column/sizing.rs +++ b/crates/ui-panels/src/docking/dock_column/sizing.rs @@ -2,7 +2,8 @@ use crate::contract::SizeLimits; use crate::docking::{DockGrid, DockHeights, DockSizes, PanelSpec}; -use craft_behavior::dock::Column; +use craft_behavior::Flow; +use craft_behavior::dock::{Column, DockEdge}; use egui::{Pos2, Rect}; /// The width bounds of an expanded column: no narrower than `least` or the widest minimum of its panels, no wider @@ -29,6 +30,31 @@ pub fn fit_widths(columns: &[(f32, Option)], room: f32) -> Vec { scale_widths(&bounded, room) } +/// The cells of a dock's columns in the dock's `rect`, from its window edge `edge` inwards, each the dock's full +/// height: the columns' natural widths ([`DockSizes::natural`]) fitted into the dock's width ([`fit_widths`]). `flow` +/// is the flow of the area the dock is in, which mirrors the edges for right-to-left. +pub fn column_cells

( + columns: &[Column

], + rect: Rect, + edge: DockEdge, + flow: Flow, + sizes: &DockSizes, + spec: &dyn Fn(&P) -> PanelSpec, +) -> Vec { + let widths = fit_widths(&sizes.natural(columns, spec), rect.width()); + let reading = flow.to_physical(rect); + let start = edge == DockEdge::Start; + let mut cursor = if start { reading.left() } else { reading.right() }; + widths + .into_iter() + .map(|width| { + let span = if start { (cursor, cursor + width) } else { (cursor - width, cursor) }; + cursor = if start { span.1 } else { span.0 }; + flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range())) + }) + .collect() +} + /// The grid and steps of a stepped column: its [`Column::steps`] and the [`DockGrid`] of its first panel that /// declares a valid one. `None` for a column without steps or whose panels declare none, which sizes as any other. pub fn stepped

(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> Option<(DockGrid, u16)> { diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index abfa15fcb..2936b673d 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -6,7 +6,7 @@ //! windows, and returns the mark the ghost paints. Every drag of a group, a window or a column starts through //! [`start_group_drag`], or [`start_icon_drag`] out of a collapsed column. -use super::{DockSpot, DockTargets, FloatSpace, GroupDrag, PanelDrag, PanelKey, WindowColumn}; +use super::{DockSpot, DockTargets, FloatSpace, GroupDrag, PanelDrag, PanelKey, Placing, WindowColumn, placed_rect}; use crate::contract::{Component, Cx, DropMark, DropOperation, DropTarget, Pointer as _}; use crate::runtime::drag::{self, DragPreview}; use crate::runtime::env::{AppValues, EnvValue, EnvView, Label}; @@ -145,23 +145,29 @@ pub(crate) fn to_target(unit: &DragUnit

, target: Target

) -> Acti } } -/// Whether the model takes `action` and changes the arrangement by it: a dry run on a copy, so no mark shows for a -/// drop that `Layout::apply_with_permissions` would refuse or that moves nothing. -pub(crate) fn takes(layout: &Layout

, action: &Action

, permissions: &dyn Fn(&P) -> Permissions) -> bool { +/// The layout after `action`, when the model takes it and it changes the arrangement: a dry run on a copy, so no mark +/// shows for a drop that `Layout::apply_with_permissions` would refuse or that moves nothing. +pub(crate) fn applied(layout: &Layout

, action: &Action

, permissions: &dyn Fn(&P) -> Permissions) -> Option> { let mut copy = layout.clone(); - copy.apply_with_permissions(action.clone(), permissions).is_ok() && !copy.same_arrangement(layout) + (copy.apply_with_permissions(action.clone(), permissions).is_ok() && !copy.same_arrangement(layout)).then_some(copy) } -/// The action a drop of `unit` on `spot` makes, or `None` when the unit cannot move there: the permissions refuse, -/// the destination is the unit itself, the spot has no placement, or the model refuses the action. +/// Whether the model takes `action` and changes the arrangement by it ([`applied`]). +pub(crate) fn takes(layout: &Layout

, action: &Action

, permissions: &dyn Fn(&P) -> Permissions) -> bool { + applied(layout, action, permissions).is_some() +} + +/// The action a drop of `unit` on `spot` makes and the layout after it, or `None` when the unit cannot move there: the +/// permissions refuse, the destination is the unit itself, the spot has no placement, or the model refuses the action. fn action_for( layout: &Layout

, spot: &DockSpot

, unit: &DragUnit

, permissions: &dyn Fn(&P) -> Permissions, -) -> Option> { +) -> Option<(Action

, Layout

)> { let action = spot_action(layout, spot, unit, permissions)?; - takes(layout, &action, permissions).then_some(action) + let after = applied(layout, &action, permissions)?; + Some((action, after)) } fn spot_action( @@ -275,12 +281,15 @@ where { let unit = drag.unit(layout)?; let (spot, _) = DockTargets::

::resolve(ctx, dock, at)?; - action_for(layout, &spot, &unit, permissions) + action_for(layout, &spot, &unit, permissions).map(|(action, _)| action) } /// The drop target of one dock over one layout, for a tab drag ([`PanelDrag`]) and a group drag ([`GroupDrag`]). /// -/// It accepts a move only. A release over a spot docks the unit there. Ctrl or Cmd held at the release floats it +/// It accepts a move only. A release over a spot docks the unit there. With `placing`, the mark over a spot is the +/// region the unit takes once dropped, laid out in the room the dock registered ([`placed_rect`]), with the tab line +/// of a tab insertion; a reorder inside the unit's own group, and a drop whose panels get no rect of their own, mark +/// the spot ([`DockSpot::mark`]). Ctrl or Cmd held at the release floats it /// instead (Photoshop: the key prevents docking), and with `float_on_empty` a release that no spot takes floats it; /// both float it into `space` under the pointer. A floating window dragged by its title bar moves itself and never /// floats into another window. Fields are assigned by the dock after [`Self::new`]. @@ -299,12 +308,14 @@ pub struct DockDropTarget<'a, P> { pub float_on_empty: bool, /// A floating window dragged by its title bar docks on a spot (`DockConfig::title_bar_docks`). Off: it only moves. pub title_bar_docks: bool, + /// How the dock lays out its panels, for the region a drop gives them. Without it every mark is the spot's. + pub placing: Option>, } impl<'a, P> DockDropTarget<'a, P> { /// The target of `dock` over `layout`: it docks on spots and floats nothing until `space` is set. pub fn new(ctx: &'a Context, dock: Id, layout: &'a Layout

, permissions: &'a dyn Fn(&P) -> Permissions) -> Self { - DockDropTarget { ctx, dock, layout, permissions, rtl: false, space: None, float_on_empty: false, title_bar_docks: true } + DockDropTarget { ctx, dock, layout, permissions, rtl: false, space: None, float_on_empty: false, title_bar_docks: true, placing: None } } } @@ -322,8 +333,14 @@ impl DockDropTarget<'_, P> { return None; } if let Some((spot, applies)) = DockTargets::

::resolve(self.ctx, self.dock, at) { - if let Some(action) = action_for(self.layout, &spot, &unit, self.permissions) { - let mark = spot.mark(applies, self.rtl)?; + if let Some((action, after)) = action_for(self.layout, &spot, &unit, self.permissions) { + let mark = match self.region(&spot, &unit, &after) { + Some(area) => match spot.tab_line(applies, self.rtl) { + Some([from, to]) => DropMark::region_at(area, from, to), + None => DropMark::region(area), + }, + None => spot.mark(applies, self.rtl)?, + }; return Some(DockDropped { action, mark }); } if on_unit(self.layout, &spot, &unit) { @@ -336,6 +353,18 @@ impl DockDropTarget<'_, P> { self.float(&unit, at, drag.source(), drag.strip()) } + /// The rect the panels of `unit` take in `after`, the layout once dropped on `spot`; `None` without `placing` or + /// a registered room, for a reorder inside the unit's own group, which marks only its tab line, and where the + /// panels get no rect of their own. + fn region(&self, spot: &DockSpot

, unit: &DragUnit

, after: &Layout

) -> Option { + let placing = self.placing.as_ref()?; + if matches!(spot, DockSpot::Tab { .. }) && on_unit(self.layout, spot, unit) { + return None; + } + let room = DockTargets::

::room(self.ctx, self.dock)?; + placed_rect(after, &moving_panels(self.layout, unit), room, placing, self.rtl) + } + /// The unit floated under `at`, when it may float and the model takes it; `source` is its size where the drag /// started, `strip` the size of the icons it started on ([`float_drop`]). fn float(&self, unit: &DragUnit

, at: Pos2, source: Option, strip: Option) -> Option> { diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index fee1675aa..7bbd47ba4 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -2,8 +2,9 @@ //! //! The group is a movable, resizable container on a layer (or in an OS window) whose rect the caller owns: the //! caller places it with the rect the dock model keeps and takes the rect the output reports after each step of -//! a gesture. The title row carries the active panel's title and the Menu, Float and Close actions; the Menu action -//! opens the `menu` rows. The body step supplies the move band, the edge grips and the keyboard Move and Size modes. +//! a gesture. The title row carries the Close action; a context request on its band opens the `menu` rows, as the +//! Menu action does where `actions` asks for one. The body step supplies the move band, the edge grips and the +//! keyboard Move and Size modes. //! A dock window's title row is also the bar of the column the window holds, with the column's double arrow. use super::dock_column::{CHEVRON, ColumnArrow, describe_chevron, paint_chevron}; @@ -38,8 +39,9 @@ pub(crate) fn title_row(tokens: &UiTokens) -> f32 { tokens.size.panel_header } -/// The actions a floating group's title row shows unless `actions` says otherwise. -const ACTIONS: [HeaderAction; 3] = [HeaderAction::Menu, HeaderAction::Float, HeaderAction::Close]; +/// The actions a floating group's title row shows unless `actions` says otherwise: Close alone, as a floating panel's +/// title bar has beside its double arrow; the menu opens from the band. +const ACTIONS: [HeaderAction; 1] = [HeaderAction::Close]; /// The style of a floating group: the surface and padding come from the container. #[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] @@ -90,6 +92,21 @@ impl WindowColumn { self } + /// Where a window that keeps `rect` shows while its column is collapsed: the collapsed column under a title row + /// `header` tall, at the top of `rect` and against the edge the window keeps to. `None` while the column is + /// expanded. + pub fn shown(self, rect: Rect, header: f32, rtl: bool) -> Option { + let size = self.collapsed? + Vec2::new(0.0, header); + let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x }; + Some(Rect::from_min_size(Pos2::new(left, rect.top()), size)) + } + + /// The rect a window that keeps `rect` keeps when it shows at `shown`: while collapsed, `rect` moved with the + /// collapsed column ([`Self::shown`]), so it keeps its expanded size; while expanded, `shown`. + pub fn kept(self, shown: Rect, rect: Rect, header: f32, rtl: bool) -> Rect { + self.shown(rect, header, rtl).map_or(shown, |at| rect.translate(shown.min - at.min)) + } + /// The edge of `bounds`, in reading order, nearer the window at `rect`: the start edge when the window's centre is /// in the half of the bounds there or `bounds` is empty. pub fn nearer_edge(rect: Rect, bounds: Rect, rtl: bool) -> DockEdge { @@ -167,7 +184,8 @@ impl Outcome for FloatingGroupOutput { /// collapsed size against that edge of the rect, its title row shows no actions (the band and the double arrow; /// a context request on the band opens the menu), the edges do not resize, and a move keeps the rect's size. A /// column its content sizes ([`WindowColumn::fitted`]) shows at that size at the rect's place; its resizes are -/// reported as the user makes them. +/// reported as the user makes them, and in an OS window the app runs them, so the window takes only the size the +/// host gives it. /// - Docking: with [`window_of`](FloatingGroup::window_of) set, a move by the title starts a window-unit drag /// (`GroupDrag`) for the dock's `DockDropTarget`, which shows the drop mark and docks the window on release. /// - Window: with `native` set the group opens in an OS window of that kind, with the layer as the fallback where @@ -204,7 +222,7 @@ pub struct FloatingGroup<'a> { /// Opens the group in an OS window of this kind. #[prop] native: Option, - /// The rows of the menu the Menu action opens. + /// The rows of the menu a context request on the title row, or the Menu action, opens. #[prop(func = "FnMut(&mut Ui, &mut BodyCx<'_>)")] menu: Option>, actions: Vec, @@ -235,7 +253,7 @@ type StartDrag<'a> = Box FnOnce(&'b mut Cx<'c, FloatingGroup<'a> type TakeDrop<'a> = Box FnMut(&'b mut Cx<'c, FloatingGroup<'a>>) + 'a>; impl<'a> FloatingGroup<'a> { - /// A floating group titled `title` at `rect`, with the Menu, Float and Close actions. + /// A floating group titled `title` at `rect`, with the Close action. pub fn new(title: impl Into

(ctx: &Context, config: &DockConfig, window: &Floating

, spec } /// The action that records where the OS put the native window `window`, shown in `viewport`: its placement, as an -/// app window's is recorded. `None` while the model already holds what the OS reports, so a window at rest costs no -/// action. +/// app window's is recorded, with the rect `kept` gives for the rect the OS shows the window at (outer top-left corner +/// and inner size, in desktop points), so a collapsed window keeps its expanded rect +/// ([`WindowColumn::kept`](super::WindowColumn::kept)). `None` while the model already holds what the OS reports, so a +/// window at rest costs no action. #[doc(hidden)] -pub fn reported(ctx: &Context, window: &Floating

, viewport: ViewportId) -> Option> { +pub fn reported(ctx: &Context, window: &Floating

, viewport: ViewportId, kept: impl FnOnce(Rect) -> Rect) -> Option> { let panel = window.panels().next()?; - let next = WindowHost::of(ctx).placement(viewport, window.native.clone())?; + let mut next = WindowHost::of(ctx).placement(viewport, window.native.clone())?; + if let (false, false, Some(at)) = (next.maximized, next.fullscreen, next.position()) { + let rect = kept(Rect::from_min_size(Pos2::from(at), Vec2::from(next.normal.size))); + next.normal.size = rect.size().into(); + next.normal.pos = rect.min.into(); + next.position_px = Some([(rect.min.x * next.scale).round() as i32, (rect.min.y * next.scale).round() as i32]); + } let settled = window.native.as_ref().is_some_and(|saved| { let near = (0..2).all(|i| (saved.normal.size[i] - next.normal.size[i]).abs() <= SETTLED); let mut next = next.clone(); @@ -94,6 +111,21 @@ pub fn reported(ctx: &Context, window: &Floating

, viewport: Viewpor (!settled).then(|| Action::set_native(panel.clone(), Some(next))) } +/// Sends the native window shown in `viewport`, which the dock model records at `recorded` (its outer top-left +/// corner and inner size), to `rect` where it differs by more than rounding: the place the dock gives a window it +/// sizes itself (a column with steps). The window's next report is that place, which [`reported`] records. +#[doc(hidden)] +pub fn send_to(ctx: &Context, viewport: ViewportId, recorded: Rect, rect: Rect) { + let differs = |delta: Vec2| delta.x.abs() > SETTLED || delta.y.abs() > SETTLED; + let host = WindowHost::of(ctx); + if differs(rect.min - recorded.min) { + host.act(viewport, WindowAction::SetOuterPosition(rect.min)); + } + if differs(rect.size() - recorded.size()) { + host.act(viewport, WindowAction::SetInnerSize(rect.size())); + } +} + /// Raises the window of the native group that `output` reports on when the user began moving or resizing it this /// pass, so a palette comes to the front of the windows it overlaps. False when nothing was raised. pub(crate) fn raise(ctx: &Context, output: &FloatingGroupOutput) -> bool { diff --git a/crates/ui-panels/src/docking/placed.rs b/crates/ui-panels/src/docking/placed.rs new file mode 100644 index 000000000..c276de59b --- /dev/null +++ b/crates/ui-panels/src/docking/placed.rs @@ -0,0 +1,122 @@ +//! Where a drop puts the panels it moves: the layout after the drop, pruned as the dock area shows it and laid out by +//! the functions the dock draws with, so a drop's mark is the rect the moved panels take once dropped. + +use super::frame::maximize; +use super::tree::{self, FrameRules}; +use super::{ColumnBar, DockSizes, HidePanels, PanelSpec, column_cells, group_rects, stepped}; +use craft_behavior::Flow; +use craft_behavior::dock::{Column, Layout, Node}; +use egui::Rect; +use std::hash::Hash; + +/// How a dock lays out its panels, which its drop target reads to mark where a drop puts them +/// (`DockDropTarget::placing`). +#[non_exhaustive] +pub struct Placing<'a, P> { + /// The dock's sizes. + pub sizes: DockSizes, + /// Each panel's spec: its limits, heights and whether it is a canvas. + pub spec: &'a dyn Fn(&P) -> PanelSpec, + /// The panels that always show, such as a canvas. + pub protected: &'a dyn Fn(&P) -> bool, + /// The panels the area hides, as the shell's visibility leaves them. + pub hide: HidePanels<'a, P>, + /// The panel whose frame the area shows maximized. + pub maximized: Option<&'a P>, + /// The floating window whose column the dock lays out, by its id; `None` for a dock area's docked tree. + pub window: Option, +} + +impl<'a, P> Placing<'a, P> { + /// The placing of a dock area's docked tree that hides nothing. + pub fn new(sizes: DockSizes, spec: &'a dyn Fn(&P) -> PanelSpec, protected: &'a dyn Fn(&P) -> bool) -> Self { + Placing { sizes, spec, protected, hide: HidePanels::None, maximized: None, window: None } + } + + /// The area hides `hide` and shows the frame of `maximized` alone. + #[must_use] + pub fn shown(mut self, hide: HidePanels<'a, P>, maximized: Option<&'a P>) -> Self { + self.hide = hide; + self.maximized = maximized; + self + } + + /// The placing of the floating window `window` instead of the docked tree. + #[must_use] + pub fn window(mut self, window: u64) -> Self { + self.window = Some(window); + self + } +} + +/// Runs `f` with the rules a dock area lays its docked tree out by: each panel's limits from `spec`, a dock as wide as +/// its columns' natural widths ([`DockSizes::natural`]), and no strip on a canvas alone in its group. +pub fn with_area_rules(sizes: &DockSizes, spec: &dyn Fn(&P) -> PanelSpec, f: impl FnOnce(FrameRules<'_, P>) -> R) -> R { + let limits = |panel: &P| spec(panel).limits; + let dock_width = |columns: &[Column

]| sizes.natural(columns, spec).iter().map(|(width, _)| *width).sum::(); + let stripless = |panel: &P| spec(panel).canvas; + f(FrameRules::new(&limits).dock_width(&dock_width).stripless(&stripless)) +} + +/// The rect the panels `moved` take in `layout`, the layout after a drop, laid out in `room` (the room the dock +/// registered, `DockTargets::room`) as the dock lays it out, pruned as the area shows it: the union of the rects of the +/// groups that hold them, or the cell of a dock column they make up alone. `None` where one of them lands where the +/// layout gives it no rect of its own: hidden, in a collapsed column (icons) or in a stepped column (sized by its +/// content as it shows). +pub fn placed_rect(layout: &Layout

, moved: &[P], room: Rect, placing: &Placing<'_, P>, rtl: bool) -> Option { + let view = maximize(layout, placing.maximized, placing.hide, placing.protected); + let layout: &Layout

= &view.layout; + let mut rects = Vec::new(); + match placing.window { + Some(id) => { + let window = layout.floating.iter().find(|window| window.id == id)?; + column_rects(&window.column, room, ColumnBar::Window, placing, moved, &mut rects)?; + } + None => { + let root = layout.root.as_ref()?; + let flow = Flow::new(room, rtl); + with_area_rules(&placing.sizes, placing.spec, |rules| { + for frame in tree::frames(root, room, &placing.sizes, &rules, rtl).groups { + match frame.node { + Node::Dock { side, columns, .. } => { + for (column, cell) in columns.iter().zip(column_cells(columns, frame.rect, *side, flow, &placing.sizes, placing.spec)) { + column_rects(column, cell, ColumnBar::Own, placing, moved, &mut rects)?; + } + } + Node::Tabs { panels, .. } if panels.iter().any(|panel| moved.contains(panel)) => rects.push(frame.rect), + Node::Stack { entries, .. } if entries.iter().any(|entry| moved.contains(&entry.panel)) => rects.push(frame.rect), + _ => {} + } + } + Some(()) + })?; + } + } + rects.into_iter().reduce(Rect::union) +} + +/// Adds the rects the moved panels take in `column` at `cell` to `rects`: the cell when they make up the column, else +/// the rects of its groups that hold them. `None` when one lands in a collapsed or stepped column. +fn column_rects( + column: &Column

, + cell: Rect, + bar: ColumnBar, + placing: &Placing<'_, P>, + moved: &[P], + rects: &mut Vec, +) -> Option<()> { + let moves = |panel: &P| moved.contains(panel); + if !column.panels().any(moves) { + return Some(()); + } + if column.iconic || stepped(column, placing.spec).is_some() { + return None; + } + if column.panels().all(moves) { + rects.push(cell); + return Some(()); + } + let groups = column.groups.iter().zip(group_rects(column, placing.spec, cell, bar, &placing.sizes)); + rects.extend(groups.filter(|(group, _)| group.panels.iter().any(moves)).map(|(_, rect)| rect)); + Some(()) +} diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 44a86f34f..c84c396f0 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -8,8 +8,8 @@ use super::{DragUnit, PanelKey, PanelSpec, scale_widths, stepped, width_bounds}; use crate::contract::DropMark; use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored}; use crate::style::StyleCx; +use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Layout, Node, ZoneSize, node_at, zones}; -use craft_behavior::{DockSide, Flow}; use egui::{Context, Id, Pos2, Rect, Vec2}; pub use craft_behavior::dock::{SIDE_ZONE_DEPTH_SHARE, SIDE_ZONE_FRACTION}; @@ -268,31 +268,40 @@ impl

DockSpot

{ } } - /// What the drag ghost paints for a drop on this spot; `None` for [`DockSpot::Blocked`], which takes no drop. + /// What the drag ghost paints for a drop on this spot when the dock cannot say where the moved panels land + /// (`DockDropTarget::placing`); `None` for [`DockSpot::Blocked`], which takes no drop. /// - /// `rect` is the rect the spot applies to: the group's rect for [`DockSpot::Group`], whose side marks the half - /// of it a docked panel would take (mirrored under `rtl`); the rect it registered with (`DockTargets::register_in`, else its hit rect) for the others. A tab - /// insertion marks a line across the hit rect's start edge. A band (edge, seam, column, new dock) marks a line - /// along its middle. + /// `rect` is the rect the spot applies to: the group's rect for [`DockSpot::Group`]; the rect it registered with + /// (`DockTargets::register_in`, else its hit rect) for the others. A group's middle marks the group as the region + /// the panels join; a side of it marks a line along that edge of the group (mirrored under `rtl`). A tab insertion + /// marks a line across the hit rect's start edge. A band (edge, seam, column, new dock) marks a line along its + /// middle. pub fn mark(&self, rect: Rect, rtl: bool) -> Option { + let (start, end) = if rtl { (rect.right(), rect.left()) } else { (rect.left(), rect.right()) }; + let across = |x: f32| DropMark::line(Pos2::new(x, rect.top()), Pos2::new(x, rect.bottom())); + let along = |y: f32| DropMark::line(Pos2::new(rect.left(), y), Pos2::new(rect.right(), y)); match self { DockSpot::Blocked => None, - DockSpot::Group { side: DockSide::Center, .. } => Some(DropMark::Into(rect)), - DockSpot::Group { side, .. } => Some(DropMark::Split(Flow::new(rect, rtl).to_physical(side.area(rect)))), - DockSpot::Tab { .. } => { - let x = if rtl { rect.right() } else { rect.left() }; - Some(DropMark::line(Pos2::new(x, rect.top()), Pos2::new(x, rect.bottom()))) - } + DockSpot::Group { side, .. } => Some(match side { + DockSide::Start => across(start), + DockSide::End => across(end), + DockSide::Top => along(rect.top()), + DockSide::Bottom => along(rect.bottom()), + _ => DropMark::region(rect), + }), + DockSpot::Tab { .. } => self.tab_line(rect, rtl).map(|[from, to]| DropMark::line(from, to)), DockSpot::Edge(_) | DockSpot::Seam { .. } | DockSpot::Column { .. } | DockSpot::NewDock(_) => { let centre = rect.center(); - Some(if rect.width() <= rect.height() { - DropMark::line(Pos2::new(centre.x, rect.top()), Pos2::new(centre.x, rect.bottom())) - } else { - DropMark::line(Pos2::new(rect.left(), centre.y), Pos2::new(rect.right(), centre.y)) - }) + Some(if rect.width() <= rect.height() { across(centre.x) } else { along(centre.y) }) } } } + + /// The tab line of a [`DockSpot::Tab`] at `rect`, the rect it registered with: across its start edge. + pub(crate) fn tab_line(&self, rect: Rect, rtl: bool) -> Option<[Pos2; 2]> { + let x = if rtl { rect.right() } else { rect.left() }; + matches!(self, DockSpot::Tab { .. }).then(|| [Pos2::new(x, rect.top()), Pos2::new(x, rect.bottom())]) + } } /// How a group's body divides into side zones. @@ -326,15 +335,17 @@ struct Target

{ applies: Rect, } -/// The spots of one dock in one pass with their hit rects. Spots are added back to front. +/// The spots of one dock in one pass with their hit rects, and the room the dock laid its panels out in. Spots are +/// added back to front. #[derive(Clone, Debug, PartialEq)] pub struct DockTargets

{ targets: Vec>, + room: Option, } impl

Default for DockTargets

{ fn default() -> Self { - DockTargets { targets: Vec::new() } + DockTargets { targets: Vec::new(), room: None } } } @@ -414,6 +425,21 @@ impl DockTargets

{ if !crate::runtime::measure::effect(ctx, "dock::register_target") { return; } + Self::with_dock(ctx, dock, |targets| targets.add(spot, hit, applies)); + } + + /// Registers `room`, the rect the dock `dock` lays its panels out in this pass: the docked tree's rect for a dock + /// area, the column's rect for a floating window. A drop's mark lays the panels out in it as they land + /// ([`placed_rect`](super::placed_rect)). + pub fn register_room(ctx: &Context, dock: Id, room: Rect) { + if !crate::runtime::measure::effect(ctx, "dock::register_room") { + return; + } + Self::with_dock(ctx, dock, |targets| targets.room = Some(room)); + } + + /// Runs `f` on the registry of `dock` in the running pass, made empty the first time. + fn with_dock(ctx: &Context, dock: Id, f: impl FnOnce(&mut DockTargets

)) { Self::with_pass(ctx, |pass| { let at = match pass.now.iter().position(|(id, _)| *id == dock) { Some(at) => at, @@ -422,10 +448,16 @@ impl DockTargets

{ pass.now.len() - 1 } }; - pass.now[at].1.add(spot, hit, applies); + f(&mut pass.now[at].1); }); } + /// The room the dock `dock` laid its panels out in the previous pass ([`Self::register_room`]); `None` outside a + /// pass and where the dock registered none. + pub fn room(ctx: &Context, dock: Id) -> Option { + Self::with_pass(ctx, |pass| pass.before.iter().find(|(id, _)| *id == dock).and_then(|(_, targets)| targets.room)).flatten() + } + /// The spot a drop at `at` lands on in the dock `dock`, by the spots of the previous pass, with the rect its /// mark applies to (`DockSpot::mark` takes it); `None` outside a pass. /// diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index d975f6f37..7d27eb17c 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -8,13 +8,12 @@ use crate::contract::{ }; use crate::docking::SplitFramesCx as _; use crate::docking::stack::{StackSection, StackSections, section_heights}; -use crate::docking::tree::FrameRules; use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests}; use crate::docking::{ ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, - IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, SplitArea, WindowColumn, actions, dock_states, fit_widths, frame, - move_actions, stepped, + IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, Placing, SplitArea, WindowColumn, actions, column_cells, dock_states, + frame, move_actions, stepped, with_area_rules, }; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandRef, CommandSet as _, Commands as _, focus_within}; @@ -185,13 +184,16 @@ impl

Default for AreaMemory

{ } } -/// What the root's drop taker reads: the dock, the layout it shows, the rights and where a floating drop lands. +/// What the root's drop taker reads: the dock, the layout it shows, the rights, where a floating drop lands and what +/// the host hides. struct Drops<'a, P> { dock: Id, layout: &'a Layout

, permissions: &'a dyn Fn(&P) -> Permissions, config: &'a DockConfig, specs: &'a HashMap, + hide: HidePanels<'a, P>, + maximized: Option<&'a P>, rtl: bool, } @@ -200,13 +202,18 @@ impl Drops<'_, P> { fn take(&self, cx: &mut Cx<'_, DockRoot<'_, DockDropped

>>) -> Option> { let ctx = cx.core.ctx.clone(); let sizes = *cx.style.sizes(); - let bounds = cx.env.get::().0.as_ref().map_or(cx.rect, ShellCx::float_bounds); + let shell = cx.env.get::().0; + let bounds = shell.as_ref().map_or(cx.rect, ShellCx::float_bounds); let space = float_space(bounds, &sizes, self.config, self.specs); + let spec = |panel: &P| spec_in(self.specs, panel); + let protected = |panel: &P| (self.permissions)(panel).is_protected(); + let (hide, _) = hide::resolved(self.hide, shell.as_ref()); let mut target = DockDropTarget::new(&ctx, self.dock, self.layout, self.permissions); target.rtl = self.rtl; target.space = Some(&space); target.float_on_empty = self.config.float_on_empty_drop; target.title_bar_docks = self.config.title_bar_docks; + target.placing = Some(Placing::new(sizes, &spec, &protected).shown(hide, self.maximized)); cx.drop_target::, _>(&target).or_else(|| cx.drop_target::(&target)) } } @@ -242,9 +249,14 @@ struct Scene<'s, P> { floated: &'s [(P, Location

)], } +/// The spec of `panel` in `specs`, or an unnamed one. +fn spec_in(specs: &HashMap, panel: &P) -> PanelSpec { + specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())) +} + impl Scene<'_, P> { fn spec(&self, panel: &P) -> PanelSpec { - self.specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())) + spec_in(self.specs, panel) } fn permissions(&self, panel: &P) -> Permissions { @@ -352,7 +364,16 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { .collect(); let policy = |panel: &P| rights.get(panel).copied().unwrap_or(Permissions::ALL); let specs: HashMap = current.layout.panels().into_iter().map(|panel| (panel.clone(), panels.spec(panel))).collect(); - let drops = Drops { dock: id, layout: ¤t.layout, permissions: &policy, config: &config, specs: &specs, rtl }; + let drops = Drops { + dock: id, + layout: ¤t.layout, + permissions: &policy, + config: &config, + specs: &specs, + hide, + maximized: maximized.as_ref(), + rtl, + }; let shows = Arrangement { dock: id, revision: current.revision() }; end_replaced_drags::

(&ctx, shows); let dropped: RefCell>> = RefCell::new(None); @@ -542,31 +563,30 @@ fn show_area( }; let spec_of = |panel: &P| scene.spec(panel); - let limits = |panel: &P| scene.spec(panel).limits; - let dock_width = |columns: &[Column

]| scene.sizes.natural(columns, &spec_of).iter().map(|(width, _)| *width).sum::(); - let stripless = |panel: &P| scene.spec(panel).canvas; - let rules = FrameRules::new(&limits).dock_width(&dock_width).stripless(&stripless); let label = Label::from(body.words::().panels.as_str().to_owned()); let mut leaves: Vec<(Vec, Rect)> = Vec::new(); - let area = SplitArea::new(label, Bind::given(layout.clone()), rules).show(ui, |ui, split| { - for (anchor, rect) in split.group_frames::

() { - let Some(place) = scene.layout.place(&anchor) else { continue }; - let Some(node) = scene.layout.node_of(&place) else { continue }; - if let PanelPlace::Node(path) = &place { + let area = with_area_rules(&scene.sizes, &spec_of, |rules| { + SplitArea::new(label, Bind::given(layout.clone()), rules).show(ui, |ui, split| { + DockTargets::

::register_room(ctx, id, split.rect); + for (anchor, rect) in split.group_frames::

() { + let Some(place) = scene.layout.place(&anchor) else { continue }; + let Some(node) = scene.layout.node_of(&place) else { continue }; + if let PanelPlace::Node(path) = &place { + leaves.push((path.clone(), rect)); + } + pass.leaf(ui, split, node, rect); + } + let flow = Flow::new(split.rect, rtl); + for (edge, rect) in split.dock_frames() { + let Some(path) = scene.layout.dock_path(edge) else { continue }; + let Some(Node::Dock { columns, .. }) = scene.layout.root.as_ref().and_then(|root| node_at(root, &path)) else { continue }; leaves.push((path.clone(), rect)); + if let Some(shell) = shell.as_ref().filter(|shell| shell.revealed() && crate::runtime::measure::effect(ctx, "shell::reveal_rect")) { + shell.reveal_rect(if edge == DockEdge::Start { RevealEdge::Start } else { RevealEdge::End }, rect); + } + pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() }); } - pass.leaf(ui, split, node, rect); - } - let flow = Flow::new(split.rect, rtl); - for (edge, rect) in split.dock_frames() { - let Some(path) = scene.layout.dock_path(edge) else { continue }; - let Some(Node::Dock { columns, .. }) = scene.layout.root.as_ref().and_then(|root| node_at(root, &path)) else { continue }; - leaves.push((path.clone(), rect)); - if let Some(shell) = shell.as_ref().filter(|shell| shell.revealed() && crate::runtime::measure::effect(ctx, "shell::reveal_rect")) { - shell.reveal_rect(if edge == DockEdge::Start { RevealEdge::Start } else { RevealEdge::End }, rect); - } - pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() }); - } + }) }); let mut edit = area.output.edit.events.map(|edited| { let mut next = current.clone(); @@ -922,14 +942,8 @@ impl Pass<'_, P> { fn dock(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, plan: DockPlan<'_, P>) { let scene = self.scene; let spec = |panel: &P| scene.spec(panel); - let widths = fit_widths(&scene.sizes.natural(plan.columns, &spec), plan.rect.width()); - 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) { - let span = if start { (cursor, cursor + width) } else { (cursor - width, cursor) }; - cursor = if start { span.1 } else { span.0 }; - let mut cell = plan.flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range())); + let cells = column_cells(plan.columns, plan.rect, plan.edge, plan.flow, &scene.sizes, &spec); + for (column, mut cell) in plan.columns.iter().zip(cells) { let Some(first) = column.groups.first().and_then(|group| group.panels.first()) else { continue }; // A stepped column is as tall as its bar and content, from the top of the dock; content taller than the // dock gets the dock's height and scrolls inside. The rest of its slot is the dock's empty room. @@ -942,6 +956,50 @@ impl Pass<'_, P> { } } + /// The steps a resize `change` of the floating window of the stepped `column`, whose first panel is `first`, sets, + /// and the window's rect at them: as wide as its steps and as tall as its title row and its content at that width. + /// `fitted` is the content's size under the title row before the change. A grip on the top or bottom edge sets the + /// steps by height (the fewest whose content fits), any other grip by width (the most that fit); keyboard Size + /// mode, which names no grip, by the side it changed. The window keeps its place: a grip on the left keeps the + /// right edge where it is and one on the top the bottom edge, so the window grows or shrinks that way. Reports + /// the steps when they change. `None` for a column without steps. + fn stepped_resize( + &mut self, + ui: &mut Ui, + body: &mut BodyCx<'_>, + column: &Column

, + first: &P, + change: &PlacementChange, + fitted: Vec2, + ) -> Option { + let scene = self.scene; + let spec_of = |panel: &P| scene.spec(panel); + let (grid, steps) = stepped(column, &spec_of)?; + let by_height = match change.kind { + PlacementKind::Size(grip) => matches!(grip, ResizeEdge::Top | ResizeEdge::Bottom), + _ => (change.rect.width() - fitted.x).abs() <= 0.5, + }; + let to = if by_height { + let room = change.rect.height() - scene.sizes.title_row; + grid.steps_for_height(room, |width| self.stepped_height(ui, body, column, width, true).unwrap_or(0.0)) + } else { + grid.steps_within(change.rect.width()) + }; + if to != steps { + self.report.actions.push(Action::set_column_steps(first.clone(), to)); + } + let size = Vec2::new(grid.width(to), scene.sizes.title_row + self.stepped_height(ui, body, column, grid.width(to), true).unwrap_or(0.0)); + let left = match change.kind { + PlacementKind::Size(ResizeEdge::Left | ResizeEdge::TopLeft | ResizeEdge::BottomLeft) => change.rect.right() - size.x, + _ => change.rect.left(), + }; + let top = match change.kind { + PlacementKind::Size(ResizeEdge::Top | ResizeEdge::TopLeft | ResizeEdge::TopRight) => change.rect.bottom() - size.y, + _ => change.rect.top(), + }; + Some(Rect::from_min_size(Pos2::new(left, top), size)) + } + /// The height of the groups of an expanded stepped column ([`stepped`]) measured at `width`, the width of its /// steps: what the column shows under its bar. `None` for any other column. fn stepped_height(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, column: &Column

, width: f32, in_window: bool) -> Option { @@ -987,6 +1045,9 @@ impl Pass<'_, P> { let dock = self.dock; let ColumnAt { cell, edge, bar, within, open } = at; let in_window = bar == ColumnBar::Window; + if in_window { + DockTargets::

::register_room(ui.ctx(), dock, cell); + } let opens = if edge == DockEdge::Start { Side::End } else { Side::Start }; let work = if column.iconic { let output = IconicColumn::new(name, dock, column, Bind::given(open), &spec) @@ -1069,12 +1130,15 @@ impl Pass<'_, P> { /// double arrow sits at that end, and its collapsed column shows against that edge of its rect. A move or resize /// keeps the edge the window had when it began, so nothing jumps while the window crosses the middle. A collapsed /// window's move ends at the edge nearer the strip where it was dropped, with the rect that shows the strip there - /// ([`WindowColumn::dropped`]); an expanded window's move leaves its edge to its rect. + /// ([`WindowColumn::dropped`]); an expanded window's move leaves its edge to its rect. An OS window is measured + /// where it would sit in the app window ([`native::in_app`]), and the end of each of its moves and resizes records + /// that rect and edge; its placement keeps its expanded rect while its column is collapsed ([`WindowColumn::kept`]). /// /// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that /// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or /// bottom the fewest whose content fits the height, and the window keeps its place; a drag of its left side keeps - /// its right edge. + /// its right edge. An OS window takes that rect at once ([`native::place`]); the app runs its grips, so the OS + /// sizes it no other way. fn windows( &mut self, ui: &mut Ui, @@ -1085,6 +1149,7 @@ impl Pass<'_, P> { let scene = self.scene; let ctx = ui.ctx().clone(); let policy = |panel: &P| scene.permissions(panel); + let protected = |panel: &P| scene.permissions(panel).is_protected(); let spec_of = |panel: &P| scene.spec(panel); let mut moved = None; for window in &scene.layout.floating { @@ -1096,10 +1161,10 @@ impl Pass<'_, P> { let dock = scene.dock.with(("floating", window.id)); let group_id = dock.with("window"); let opening = native::opening(&ctx, scene.config, window, &specs, group_id); - let mut actions = vec![HeaderAction::Menu]; - if rights.iter().all(|rights| rights.movable) { - actions.push(HeaderAction::Float); - } + let movable = rights.iter().all(|rights| rights.movable); + // The title row is the column's bar: its double arrow and Close; the menu opens from a context request on + // its band. + let mut actions = Vec::new(); if scene.config.close_button && rights.iter().all(|rights| rights.closable) { actions.push(HeaderAction::Close); } @@ -1111,13 +1176,17 @@ impl Pass<'_, P> { target.space = Some(scene.space); target.float_on_empty = scene.config.float_on_empty_drop; target.title_bar_docks = scene.config.title_bar_docks; + // The scene's layout is the pruned view the windows show, so the placing hides nothing more. + target.placing = Some(Placing::new(scene.sizes, &spec_of, &protected).window(window.id)); // The window is an instance of the group scope: its menu's command rows reach it, and run on its active // panel through the same path as a docked group's. let states = dock_states(&DockScene::new(scene.layout, scene.space, false, &policy).floated(scene.floated), &active); let mut commands = Vec::new(); let spec = scene.spec(&active); let began = started.and_then(|layout| layout.floating.iter().find(|began| began.id == window.id)); - let (began_rect, began_edge) = began.map_or((opening.rect, window.edge), |began| (began.rect, began.edge)); + // The window's rect in the app window: for an OS window, where it would sit there. + let in_app = opening.spec.as_ref().and_then(|_| native::in_app(&ctx, opening.rect)).unwrap_or(opening.rect); + let (began_rect, began_edge) = began.map_or((in_app, window.edge), |began| (began.rect, began.edge)); let edge = began_edge.unwrap_or_else(|| WindowColumn::nearer_edge(began_rect, scene.bounds, scene.rtl)); let width = scene.sizes.expanded_width(&window.column, &spec_of); let shape = if window.column.iconic { @@ -1168,10 +1237,35 @@ impl Pass<'_, P> { cross_window::accept_cross_window(&ctx); self.report.actions.push(dropped.action); } + // A resize of a window whose column has steps: the steps it sets, and the window's rect at them. + let resized = output + .placed + .filter(|change| !matches!(change.kind, PlacementKind::Move)) + .zip(shape.fitted) + .and_then(|(change, fitted)| self.stepped_resize(ui, body, &window.column, &anchor, &change, fitted)); if opening.spec.is_some() { if let Some(viewport) = WindowHost::of(&ctx).viewport_of(output.response.id) { + // The OS window takes the rect of its steps at once, so the place recorded below is that rect. + if let Some(rect) = resized { + native::send_to(&ctx, viewport, opening.rect, rect); + } self.report.windows.push((anchor.clone(), viewport)); - self.report.actions.extend(native::reported(&ctx, window, viewport)); + // A move or resize that ends records where the window would sit in the app window, and the edge it + // keeps to: a collapsed window's the edge nearer its strip where it was dropped, as for a window + // in the app window ([`WindowColumn::dropped`]). The window's placement keeps the rect the + // collapsed column shows against that edge. + let mut kept = shape; + if movable + && let Some(change) = output.placed.filter(|change| change.phase == GesturePhase::Commit) + && let Some(rect) = native::in_app(&ctx, change.rect) + { + let (rect, keeps) = shape.dropped(rect, scene.bounds, scene.rtl); + kept.edge = keeps.unwrap_or(kept.edge); + self.report.actions.push(Action::move_floating_with_edge(anchor.clone(), rect, keeps)); + } + let title_row = scene.sizes.title_row; + let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, title_row, scene.rtl)); + self.report.actions.extend(reported); } } else if let Some(mut change) = output.placed { // A collapsed window keeps the edge its move began with until the move ends where its strip was dropped. @@ -1179,58 +1273,18 @@ impl Pass<'_, P> { if change.phase == GesturePhase::Commit { (change.rect, keeps) = shape.dropped(change.rect, scene.bounds, scene.rtl); } - if !matches!(change.kind, PlacementKind::Move) - && let Some(fitted) = shape.fitted - && let Some((grid, steps)) = stepped(&window.column, &spec_of) - { - let column = &window.column; - // A grip on the top or bottom edge sets the steps by height, any other grip by width; keyboard Size - // mode, which names no grip, by the side it changed. - let by_height = match change.kind { - PlacementKind::Size(grip) => matches!(grip, ResizeEdge::Top | ResizeEdge::Bottom), - _ => (change.rect.width() - fitted.x).abs() <= 0.5, - }; - let to = if by_height { - let room = change.rect.height() - scene.sizes.title_row; - grid.steps_for_height(room, |width| self.stepped_height(ui, body, column, width, true).unwrap_or(0.0)) - } else { - grid.steps_within(change.rect.width()) - }; - if to != steps { - self.report.actions.push(Action::set_column_steps(anchor.clone(), to)); - } - // The window keeps its place and its steps set its size. A grip on the left keeps the right edge - // where it is, and one on the top the bottom edge, so the window grows or shrinks that way. - let left = match change.kind { - PlacementKind::Size(ResizeEdge::Left | ResizeEdge::TopLeft | ResizeEdge::BottomLeft) => change.rect.right() - grid.width(to), - _ => change.rect.left(), - }; - let top = match change.kind { - PlacementKind::Size(ResizeEdge::Top | ResizeEdge::TopLeft | ResizeEdge::TopRight) => { - let content = self.stepped_height(ui, body, column, grid.width(to), true).unwrap_or(0.0); - change.rect.bottom() - scene.sizes.title_row - content - } - _ => change.rect.top(), - }; - change.rect = Rect::from_min_size(Pos2::new(left, top), opening.rect.size()); + // The window keeps the place of its steps; its size is the steps' own, whatever the rect keeps. + if let Some(rect) = resized { + change.rect = Rect::from_min_size(rect.min, opening.rect.size()); } if change.phase == GesturePhase::Commit { self.report.events.push(DockEvent::FloatPlaced { panel: anchor.clone(), rect: change.rect }); } moved = Some((anchor.clone(), change, keeps)); } - match output.action { - // The OS close of a native window arrives here as well, also where the title row offers no Close. - Some(HeaderAction::Close) if rights.iter().all(|rights| rights.closable) => { - self.report.actions.push(Action::close_window(anchor.clone())); - } - Some(HeaderAction::Float) => { - let commands = DockScene::new(scene.layout, scene.space, false, &policy).floated(scene.floated); - if let Ok(docked) = move_actions(&commands, &DragUnit::Window(anchor.clone()), DockTo::Docked) { - self.report.actions.extend(docked); - } - } - _ => {} + // The OS close of a native window arrives here as well, also where the title row offers no Close. + if output.action == Some(HeaderAction::Close) && rights.iter().all(|rights| rights.closable) { + self.report.actions.push(Action::close_window(anchor.clone())); } if let Some(item) = picked.get() { self.pick(&active, item); diff --git a/crates/ui-patterns/src/patterns/dock/hide.rs b/crates/ui-patterns/src/patterns/dock/hide.rs index e6ca0e421..7ea931261 100644 --- a/crates/ui-patterns/src/patterns/dock/hide.rs +++ b/crates/ui-patterns/src/patterns/dock/hide.rs @@ -27,10 +27,16 @@ pub(super) fn shown<'a, P: Clone + Eq + Hash>( shell: Option<&ShellCx>, protected: &dyn Fn(&P) -> bool, ) -> Shown<'a, P> { - let (hide, floating) = match shell { + let (hide, floating) = resolved(hide, shell); + Shown { view: maximize(layout, maximized, hide, protected), floating } +} + +/// The panels the area hides, the host's `hide` with the shell's panel visibility applied, and whether floating windows +/// show (see [`shown`]). +pub(super) fn resolved<'h, P>(hide: HidePanels<'h, P>, shell: Option<&ShellCx>) -> (HidePanels<'h, P>, bool) { + match shell { None => (hide, true), Some(shell) if shell.panels_hidden() => (if let HidePanels::Except(keep) = hide { HidePanels::Except(keep) } else { HidePanels::All }, true), Some(shell) => (if shell.dock_visible() { hide } else { HidePanels::All }, shell.floating_visible()), - }; - Shown { view: maximize(layout, maximized, hide, protected), floating } + } } diff --git a/crates/ui-patterns/tests/it/docking/drop_preview.rs b/crates/ui-patterns/tests/it/docking/drop_preview.rs new file mode 100644 index 000000000..e5081239d --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/drop_preview.rs @@ -0,0 +1,130 @@ +//! A dock drop's mark is the region the dragged panel takes once dropped: the rect the area then gives its group. + +use craft_behavior::Axis; +use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; +use craft_ui::contract::{Bind, BodyCx, Role}; +use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::runtime::drag::{self, DropMark}; +use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +const ROOM: Vec2 = Vec2::new(800.0, 500.0); +const SLACK: f32 = 0.5; + +/// Each group's rect as the area last showed it, by the group's panels. +type Shown = Rc, Rect>>>; + +/// Records the rect of every group the area shows and leaves the group to the dock. +struct Panels { + shown: Shown, +} + +impl DockPanels for Panels { + fn spec(&self, panel: &usize) -> PanelSpec { + PanelSpec::new(format!("Panel {panel}")) + } + + fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} + + fn group_view(&mut self, panels: &[usize], _: usize, _: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { + if let GroupAt::Show(rect) = at { + self.shown.borrow_mut().insert(panels.to_vec(), rect); + } + None + } +} + +struct Bed { + fixture: Fixture, + workspace: Rc>>, + shown: Shown, +} + +/// `[1, 2]` beside `[3]`, under `[4]`, so their strips lie clear of the band along the layout's top edge, where a drop +/// adds a full-width row. +fn bed() -> Bed { + let row = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![1, 2], 0), Node::tabs(vec![3], 0)); + let root = Node::split(Axis::Y, SplitSize::Ratio(0.3), Node::tabs(vec![4], 0), row); + let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(root), Vec::new())))); + let shown: Shown = Rc::default(); + let (held, seen) = (Rc::clone(&workspace), Rc::clone(&shown)); + let mut fixture = Fixture::new(move |ui| { + let mut workspace = held.borrow().clone(); + let mut panels = Panels { shown: Rc::clone(&seen) }; + DockArea::new("Dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); + *held.borrow_mut() = workspace; + }); + fixture.room(ROOM).settle(); + Bed { fixture, workspace, shown } +} + +fn tab(bed: &Bed, panel: usize) -> Rect { + let tree = bed.fixture.tree(); + let name = format!("Panel {panel}"); + bed.fixture + .by_role(Role::TAB) + .into_iter() + .find(|tab| craft_ui::testing::access::name(tree, tab.node) == Some(name.as_str())) + .map(|tab| tab.rect) + .unwrap_or_else(|| panic!("the tab of panel {panel} shows")) +} + +/// Drags the tab of `panel` to `to` and returns the mark shown there, then releases it. +fn drop_tab(bed: &mut Bed, panel: usize, to: Pos2) -> DropMark { + let from = tab(bed, panel).center(); + bed.fixture.frame(vec![moved(from)]); + bed.fixture.frame(vec![press(from)]); + for step in 1..=4 { + bed.fixture.frame(vec![moved(from + (to - from) * (step as f32 / 4.0))]); + } + bed.fixture.frame(Vec::new()); + let mark = drag::mark(bed.fixture.ctx()).expect("the dock takes the drop"); + bed.fixture.frame(vec![release(to)]); + bed.fixture.settle(); + mark +} + +/// The rect the area shows the group of `panel` in. +fn group_rect(bed: &Bed, panel: usize) -> Rect { + let layout = bed.workspace.borrow().layout.clone(); + let place = layout.place(&panel).expect("the panel is docked"); + let Some(Node::Tabs { panels, .. }) = layout.node_of(&place) else { panic!("panel {panel} is in a tab group") }; + *bed.shown.borrow().get(panels).unwrap_or_else(|| panic!("the group {panels:?} was shown")) +} + +fn same(a: Rect, b: Rect) -> bool { + (a.min - b.min).length() <= SLACK && (a.max - b.max).length() <= SLACK +} + +#[trial] +fn a_tab_dropped_beside_a_group_marks_the_rect_its_group_takes() { + let mut bed = bed(); + let right = group_rect(&bed, 3); + // In the bottom third of the right group's body, clear of the layout's bottom edge band. + let to = Pos2::new(right.center().x, right.bottom() - right.height() * 0.2); + let mark = drop_tab(&mut bed, 2, to); + let DropMark::Region { area, line: None, .. } = mark else { panic!("a side drop marks a region without a line: {mark:?}") }; + let placed = group_rect(&bed, 2); + assert!(placed.top() > right.top(), "the tab went below the right group: {placed:?}"); + assert!(same(area, placed), "the mark {area:?} is the rect the dropped panel's group took: {placed:?}"); +} + +#[trial] +fn a_tab_joining_a_group_marks_the_group_and_its_tab_line_and_a_reorder_marks_the_line_only() { + let mut bed = bed(); + let target = tab(&bed, 3); + let mark = drop_tab(&mut bed, 2, Pos2::new(target.right() + 20.0, target.center().y)); + let DropMark::Region { area, line: Some(_), .. } = mark else { panic!("a tab join marks a region with its tab line: {mark:?}") }; + let joined = group_rect(&bed, 2); + assert_eq!(joined, group_rect(&bed, 3), "the tab joined the right group"); + assert!(same(area, joined), "the mark {area:?} is the rect of the group it joined: {joined:?}"); + + let after = tab(&bed, 2); + let mark = drop_tab(&mut bed, 3, Pos2::new(after.right() + 10.0, after.center().y)); + assert!(matches!(mark, DropMark::Line { .. }), "a reorder inside its own strip marks its line only: {mark:?}"); +} diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 4d94e4682..4ea3299d4 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -133,7 +133,7 @@ fn a_tab_dragged_over_a_floating_window_marks_and_joins_the_window() { let mark = drag::mark(bed.fixture.ctx()).expect("the window takes the drop"); let points = match mark { DropMark::Line { from, to, .. } => vec![from, to], - DropMark::Into(rect) | DropMark::Split(rect) => vec![rect.center()], + DropMark::Into(rect) | DropMark::Region { area: rect, .. } => vec![rect.center()], _ => Vec::new(), }; assert!(!points.is_empty() && points.iter().all(|point| WINDOW_AT.expand(SLACK).contains(*point)), "the mark is the window's: {mark:?}"); @@ -437,26 +437,32 @@ fn a_double_click_on_a_floating_windows_band_collapses_and_expands_its_column() assert!(!bed.workspace.borrow().layout.floating[0].column.iconic, "a second double click expanded it: {:?}", bed.actions.borrow()); } -/// A collapsed floating window's title row is its column's bar alone: a context request on its band opens the -/// window's menu, whose Close entry closes the window. +/// A floating window's title row is its column's bar, with the double arrow and Close and no menu button: a context +/// request on its band opens the window's menu, collapsed or expanded, and the menu's Close entry closes the window. #[trial] -fn a_context_request_on_a_collapsed_windows_band_opens_its_menu_and_close_closes_it() { - let mut bed = bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL); - let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); - let band = Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0); - bed.fixture.frame(vec![moved(band)]); - bed.fixture.frame(vec![secondary(band, true)]); - bed.fixture.frame(vec![secondary(band, false)]); - bed.fixture.settle(); - let tree = bed.fixture.tree(); - let items: Vec<_> = - bed.fixture.by_role(Role::MENU_ITEM).into_iter().map(|item| (craft_ui::testing::access::name(tree, item.node), item)).collect(); - let names: Vec<_> = items.iter().map(|(name, _)| *name).collect(); - let close = items.iter().find(|(name, _)| name.is_some_and(|name| name.starts_with("Close"))).map(|(_, item)| *item); - let close = close.unwrap_or_else(|| panic!("the band's context request opens the window's menu with a Close entry: {names:?}")); - bed.fixture.click(&close); - bed.fixture.settle(); - assert!(bed.workspace.borrow().layout.floating.is_empty(), "Close closed the window: {:?}", bed.actions.borrow()); +fn a_context_request_on_a_windows_band_opens_its_menu_and_close_closes_it() { + for collapsed in [true, false] { + let mut bed = if collapsed { bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL) } else { bed(with_window(None), |_| Permissions::ALL) }; + let band = if collapsed { + let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); + Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0) + } else { + window_title() + }; + bed.fixture.frame(vec![moved(band)]); + bed.fixture.frame(vec![secondary(band, true)]); + bed.fixture.frame(vec![secondary(band, false)]); + bed.fixture.settle(); + let tree = bed.fixture.tree(); + let items: Vec<_> = + bed.fixture.by_role(Role::MENU_ITEM).into_iter().map(|item| (craft_ui::testing::access::name(tree, item.node), item)).collect(); + let names: Vec<_> = items.iter().map(|(name, _)| *name).collect(); + let close = items.iter().find(|(name, _)| name.is_some_and(|name| name.starts_with("Close"))).map(|(_, item)| *item); + let close = close.unwrap_or_else(|| panic!("collapsed {collapsed}: the band's context request opens the window's menu: {names:?}")); + bed.fixture.click(&close); + bed.fixture.settle(); + assert!(bed.workspace.borrow().layout.floating.is_empty(), "collapsed {collapsed}: Close closed the window: {:?}", bed.actions.borrow()); + } } /// Nothing goes beside a floating window: a tab dragged over the start side of its group marks the join of the @@ -475,7 +481,7 @@ fn a_drag_over_a_floating_window_joins_or_stacks_and_never_splits() { press_and_move(&mut expanded.fixture, tab.center(), side - tab.center()); expanded.fixture.frame(Vec::new()); let mark = drag::mark(expanded.fixture.ctx()).expect("the window takes the drop"); - assert!(matches!(mark, DropMark::Into(_)), "the start side of a floating group joins it: {mark:?}"); + assert!(matches!(mark, DropMark::Region { .. }), "the start side of a floating group joins it: {mark:?}"); expanded.fixture.frame(vec![release(side)]).settle(); let mut window = Floating::single(vec![WINDOW], 0, WINDOW_AT); diff --git a/crates/ui-patterns/tests/it/docking/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index 61631da3e..2243f997e 100644 --- a/crates/ui-patterns/tests/it/docking/mod.rs +++ b/crates/ui-patterns/tests/it/docking/mod.rs @@ -12,6 +12,7 @@ mod runs; mod split; mod drop; +mod drop_preview; mod drop_session; mod floating; diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 9820aa276..a2e7b6d73 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -1,11 +1,12 @@ //! Native dock windows: when a float gets an OS window, what the dock records when the OS moves it, the OS close, and //! docking the whole window by dragging its title row. -use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, Workspace}; +use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, Workspace}; use craft_behavior::placement::Placement; use craft_host::target::{Backend, Caps, Os, ShellInfo}; -use craft_ui::contract::{Bind, BodyCx, ShowContainer as _}; -use craft_ui::docking::{DockConfig, DockPanels, PanelSpec}; +use craft_ui::contract::{Bind, BodyCx, DropMark, Show as _, ShowContainer as _, SizeLimits}; +use craft_ui::display::Text; +use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec}; use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; use craft_ui::runtime::InstallSpec; @@ -15,7 +16,7 @@ use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::trial; use craft_ui::testing::windows::FakeSystem; use craft_ui_test_kit::windows::Windows; -use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; +use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; use std::sync::Arc; /// The root window and the palette overlap; the palette is the larger. @@ -172,20 +173,60 @@ const ROW_AT: Pos2 = Pos2::new(150.0, 10.0); /// A desktop point over the middle of the main window's group. const OVER_GROUP: Pos2 = Pos2::new(550.0, 400.0); +/// The grid of the stepped palette's content, as a toolbar's. +fn tools_grid() -> DockGrid { + DockGrid::new(40.0, 32.0, 6) +} + +/// A palette whose content lays out in a grid (a toolbar): its column has steps and its window fits its content. +struct SteppedPalette; + +impl DockPanels for SteppedPalette { + fn spec(&self, panel: &u32) -> PanelSpec { + if *panel == 1 { PanelSpec::new(PALETTE_TITLE).grid(tools_grid()) } else { PanelSpec::new("Canvas") } + } + + fn permissions(&self, _: &u32) -> Permissions { + Permissions::ALL.collapses(false) + } + + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + if *panel == 1 { + Text::new("One").show(ui); + Text::new("Two").show(ui); + } + } +} + /// A dock of one docked group and one native palette. struct NativeDock { windows: Windows, workspace: Workspace, + stepped: bool, + /// The palette window's builder as the integration keeps it: each frame's builder patched onto it, which sends the + /// window only the limits a builder carries. + builder: Option, } impl NativeDock { fn on(os: Os, system: Arc) -> Self { + let palette = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); + Self::with(os, system, palette, false) + } + + /// The dock with a stepped palette of one step ([`SteppedPalette`]). + fn stepped(os: Os, system: Arc) -> Self { + let column = Column::new(vec![Group::new(vec![1], 0)]).with_steps(1); + Self::with(os, system, Floating::new(column, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())), true) + } + + fn with(os: Os, system: Arc, palette: Floating, stepped: bool) -> Self { let shell = ShellInfo::default().os(os).caps(Caps::native(os)); let windows = Windows::with(InstallSpec::new(shell, system)); windows.root_info(info(true, MAIN_AT)); windows.child_info(info(true, FLOAT_AT)); - let palette = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); - let mut dock = NativeDock { windows, workspace: Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])) }; + let workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])); + let mut dock = NativeDock { windows, workspace, stepped, builder: None }; for _ in 0..3 { dock.frame(vec![]); } @@ -194,13 +235,26 @@ impl NativeDock { /// One frame with `child` events for the palette's window: the dock's actions and the palette's window commands. fn frame(&mut self, child: Vec) -> (Vec>, Vec) { + self.frame_with(vec![], child) + } + + /// One frame with `root` events for the main window and `child` events for the palette's window. + fn frame_with(&mut self, root: Vec, child: Vec) -> (Vec>, Vec) { let mut actions = Vec::new(); let workspace = &mut self.workspace; - let out = self.windows.frame(vec![], child, |ui| { - actions.extend( - DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui).actions, - ); + let (mut palettes, mut stepped) = (Palettes(Permissions::ALL), SteppedPalette); + let panels: &mut dyn DockPanels = if self.stepped { &mut stepped } else { &mut palettes }; + let out = self.windows.frame(root, child, |ui| { + actions.extend(DockArea::new("Native dock", Bind::bound(workspace), &mut *panels, DockConfig::default()).show(ui).actions); }); + for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT) { + match self.builder.as_mut() { + Some(kept) => { + let _ = kept.patch(builder); + } + None => self.builder = Some(builder), + } + } let commands = out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect(); (actions, commands) } @@ -303,6 +357,100 @@ fn dragging_a_native_palette_by_its_title_row_docks_it_where_the_os_moves_window assert!(docked, "the button's release docks the whole window"); } +/// A point near the main window's start edge, in its own coordinates: away from the middle of its group. +const STALE: Pos2 = Pos2::new(5.0, 300.0); + +/// The main window keeps the place it saw the pointer last when the palette over it takes the pointer, and may never +/// learn that the pointer left: AppKit sends no exit for a window of the app laid over it, and the press holds the +/// pointer in the palette's window. A drag of the palette resolves the main window's drops at the system pointer all +/// the same, never at that place. +#[trial] +fn a_palette_drag_resolves_the_main_windows_drops_at_the_system_pointer_not_where_it_saw_the_pointer_last() { + let system = Arc::new(FakeSystem::new()); + let mut dock = NativeDock::on(Os::Mac, system.clone()); + dock.frame_with(vec![moved(STALE)], vec![]); + let pressed_at = FLOAT_AT.min + ROW_AT.to_vec2(); + system.set_pointer(Some([pressed_at.x, pressed_at.y])); + system.set_primary_held(Some(true)); + dock.frame(vec![moved(ROW_AT)]); + dock.frame(vec![press(ROW_AT)]); + dock.frame(vec![]); + system.set_pointer(Some([OVER_GROUP.x, OVER_GROUP.y])); + let mut docked = false; + for _ in 0..3 { + docked |= docks_window(&dock.frame(vec![]).0); + } + let mark = drag::mark(&dock.windows.ctx); + assert!(matches!(mark, Some(DropMark::Into(_))), "the middle of the group under the system pointer is marked: {mark:?}"); + system.set_primary_held(Some(false)); + for _ in 0..3 { + docked |= docks_window(&dock.frame(vec![]).0); + } + assert!(docked, "the release docks the whole window"); +} + +/// The steps of the stepped palette's column. +fn palette_steps(dock: &NativeDock) -> Option { + dock.workspace.layout.floating[0].column.steps +} + +/// One frame of `dock` with `child` events, after which the palette's window is where the app sent it, as the OS +/// puts it: its commands, with `at` the window's rect. +fn placed_frame(dock: &mut NativeDock, child: Vec, at: &mut Rect) -> Vec { + let (_, commands) = dock.frame(child); + for command in &commands { + match command { + ViewportCommand::OuterPosition(to) => *at = Rect::from_min_size(*to, at.size()), + ViewportCommand::InnerSize(size) => *at = Rect::from_min_size(at.min, *size), + _ => {} + } + } + dock.windows.child_info(info(true, *at)); + commands +} + +/// A native palette whose column has steps (a toolbar) is sized by the app, not the OS: a drag of its side sets whole +/// steps and the window takes their width at once, a drag of its left side keeps its right edge, and the OS is never +/// asked to resize it. The drag holds on where the OS resizes undecorated windows (Windows): a size change the app +/// makes under the held press ends no press. +#[trial] +fn a_native_stepped_palette_resizes_in_whole_steps_that_the_app_runs() { + let grid = tools_grid(); + for os in [Os::Mac, Os::Windows] { + let mut dock = NativeDock::stepped(os, Arc::new(FakeSystem::new())); + let mut at = FLOAT_AT; + let mut sent = Vec::new(); + for _ in 0..3 { + sent.extend(placed_frame(&mut dock, vec![], &mut at)); + } + assert_eq!(at.width(), grid.width(1), "{os:?}: the window is as wide as its one step"); + + // The right grip straddles the window's right edge. + let grip = Pos2::new(at.width() - 1.0, at.height() / 2.0); + for events in [vec![moved(grip)], vec![press(grip)], vec![moved(grip + Vec2::new(1.6 * grid.step, 0.0))], vec![]] { + sent.extend(placed_frame(&mut dock, events, &mut at)); + } + assert_eq!(palette_steps(&dock), Some(2), "{os:?}: a drag of 1.6 steps sets the whole step it reached"); + assert_eq!(at.width(), grid.width(2), "{os:?}: the window takes the width of its steps while the drag runs"); + let end = grip + Vec2::new(1.6 * grid.step, 0.0); + for events in [vec![release(end)], vec![], vec![]] { + sent.extend(placed_frame(&mut dock, events, &mut at)); + } + assert_eq!(palette_steps(&dock), Some(2), "{os:?}: the release keeps the steps"); + + let right = at.right(); + let grip = Pos2::new(1.0, at.height() / 2.0); + let end = grip - Vec2::new(1.6 * grid.step, 0.0); + for events in [vec![moved(grip)], vec![press(grip)], vec![moved(end)], vec![], vec![release(end)], vec![], vec![]] { + sent.extend(placed_frame(&mut dock, events, &mut at)); + } + assert_eq!(palette_steps(&dock), Some(3), "{os:?}: a drag of the left side sets whole steps too"); + assert_eq!(at.width(), grid.width(3), "{os:?}: the window takes the width of its steps"); + assert!((at.right() - right).abs() <= 0.5, "{os:?}: the right edge stays: {right} then {at:?}"); + assert!(!sent.iter().any(|command| matches!(command, ViewportCommand::BeginResize(_))), "{os:?}: the OS never resizes the window"); + } +} + fn placing(commands: &[ViewportCommand]) -> Vec<&ViewportCommand> { commands.iter().filter(|command| matches!(command, ViewportCommand::OuterPosition(_) | ViewportCommand::InnerSize(_))).collect() } @@ -350,6 +498,145 @@ fn an_app_change_of_a_native_floats_place_moves_its_window_once() { assert_eq!(placing, [&ViewportCommand::OuterPosition(to.min), &ViewportCommand::InnerSize(to.size())], "one move and one size"); } +/// The size and place an OS window takes from `commands`, starting at `at`. +fn placed_by(commands: &[ViewportCommand], at: Rect) -> Rect { + commands.iter().fold(at, |at, command| match command { + ViewportCommand::OuterPosition(to) => Rect::from_min_size(*to, at.size()), + ViewportCommand::InnerSize(size) => Rect::from_min_size(at.min, *size), + _ => at, + }) +} + +/// A native palette collapsed to icons keeps its expanded size in the model while its OS window shows the strip of +/// icons. Moved across the main window, the strip stays where it was dropped and keeps to the edge nearer it. Expanded +/// again, the window takes its expanded size back and the OS lets it: the strip's size limits are lifted. +#[trial] +fn a_native_palette_collapsed_moved_and_expanded_comes_back_at_its_size() { + let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new())); + let expanded = FLOAT_AT.size(); + // The OS follows the window commands of each frame, and the window reports where it is. + let follow = |dock: &mut NativeDock, at: &mut Rect, frames: usize| { + let mut sent = Vec::new(); + for _ in 0..frames { + let commands = dock.frame(vec![]).1; + *at = placed_by(&commands, *at); + dock.windows.child_info(info(true, *at)); + sent.extend(commands); + } + sent + }; + let mut at = FLOAT_AT; + dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + follow(&mut dock, &mut at, 3); + let strip = at; + assert!(strip.width() < expanded.x, "the OS window shows the strip: {strip:?}"); + let recorded = |dock: &NativeDock| dock.workspace.layout.floating[0].native.clone().expect("the model records the window"); + assert_eq!(Vec2::from(recorded(&dock).normal.size), expanded, "collapsed, the model keeps the expanded size"); + + // The OS moves the strip over the start half of the main window. + let dropped = Rect::from_min_size(Pos2::new(MAIN_AT.min.x + 50.0, strip.min.y), strip.size()); + at = dropped; + dock.windows.child_info(info(true, at)); + let sent = follow(&mut dock, &mut at, 4); + assert!(placing(&sent).is_empty(), "the strip stays where it was dropped: {:?}", placing(&sent)); + assert_eq!(at, dropped); + assert_eq!(dock.workspace.layout.floating[0].edge, Some(DockEdge::Start), "it keeps to the edge nearer the strip"); + assert_eq!(Vec2::from(recorded(&dock).normal.size), expanded, "moved, the model keeps the expanded size"); + + dock.workspace.apply(Action::set_iconic(1, false), false, |_| Permissions::ALL).expect("the column expands"); + let sent = follow(&mut dock, &mut at, 3); + assert!(sent.contains(&ViewportCommand::InnerSize(expanded)), "the window takes its expanded size back: {:?}", placing(&sent)); + assert_eq!(at.min, dropped.min, "it opens from the strip's place, against the start edge"); + let max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size); + assert!(max.is_none_or(|max| max.x >= expanded.x && max.y >= expanded.y), "the OS lets it take that size: max {max:?}"); +} + +/// Palettes no smaller than `PALETTE_LEAST`. +struct Least; + +const PALETTE_LEAST: Vec2 = Vec2::new(240.0, 160.0); + +impl DockPanels for Least { + fn spec(&self, _: &u32) -> PanelSpec { + PanelSpec::new(PALETTE_TITLE).limits(SizeLimits::at_least(PALETTE_LEAST)) + } + + fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {} +} + +/// A model place smaller than the palette's limits sizes its OS window within them: the window is never asked for a +/// size the OS would clamp, so the size the model records is the one the window has. +#[trial] +fn a_native_palette_is_never_sized_below_its_limits() { + let windows = Windows::new(); + windows.root_info(info(true, MAIN_AT)); + windows.child_info(info(true, FLOAT_AT)); + let mut window = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); + let mut saved = Placement::new(FLOAT_AT.size().into(), 1.0); + saved.position_px = Some([FLOAT_AT.min.x as i32, FLOAT_AT.min.y as i32]); + window.native = Some(saved); + let mut workspace = Workspace::new(Layout::new(None, vec![window])); + let mut run = |workspace: &mut Workspace| { + let out = windows.frame(vec![], vec![], |ui| { + let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut Least, DockConfig::default().native_windows(true)).show(ui); + }); + out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect::>() + }; + for _ in 0..3 { + run(&mut workspace); + } + let mut small = Placement::new([80.0, 60.0], 1.0); + small.position_px = Some([FLOAT_AT.min.x as i32, FLOAT_AT.min.y as i32]); + workspace.apply(Action::set_native(1, Some(small)), false, |_| Permissions::ALL).expect("the model takes the place"); + let mut sent = Vec::new(); + for _ in 0..3 { + sent.extend(run(&mut workspace)); + } + let sizes: Vec = + sent.iter().filter_map(|command| if let ViewportCommand::InnerSize(size) = command { Some(*size) } else { None }).collect(); + assert!(!sizes.is_empty(), "the window is sized to the model's place"); + assert!(sizes.iter().all(|size| size.x >= PALETTE_LEAST.x && size.y >= PALETTE_LEAST.y), "within the limits: {sizes:?}"); +} + +/// While the main window is full screen, an OS window opened over it would cover it, so a float shows in the app +/// window instead, at its own rect there, and a drag of its title row moves it. +#[trial] +fn a_float_shows_and_moves_in_the_app_window_while_the_main_window_is_full_screen() { + let windows = Windows::new(); + windows.root_info(ViewportInfo { fullscreen: Some(true), ..info(true, MAIN_AT) }); + windows.child_info(info(true, FLOAT_AT)); + let start = float().rect; + let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let mut child = false; + let mut run = |workspace: &mut Workspace, events: Vec| { + let out = windows.frame(events, vec![], |ui| { + let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui); + }); + child |= out.builders.iter().any(|(viewport, _)| *viewport != ViewportId::ROOT); + }; + for _ in 0..3 { + run(&mut workspace, vec![]); + } + let row = start.min + ROW_AT.to_vec2(); + let by = Vec2::new(60.0, 40.0); + run(&mut workspace, vec![moved(row)]); + run(&mut workspace, vec![press(row)]); + for step in 1..=3 { + run(&mut workspace, vec![moved(row + by * step as f32 / 3.0)]); + } + run(&mut workspace, vec![release(row + by)]); + for _ in 0..2 { + run(&mut workspace, vec![]); + } + assert!(!child, "no OS window opens over the full-screen window"); + let moved_to = workspace.layout.floating[0].rect.min; + assert!( + (moved_to - (start.min + by)).length() <= by.length() / 2.0, + "the drag moved the float with the pointer: {moved_to:?} from {:?}", + start.min + ); +} + /// Palettes whose body is a veil over the window: a target inside the window that takes dropped files. struct Veiled; diff --git a/crates/ui-widgets/src/menu/item.rs b/crates/ui-widgets/src/menu/item.rs index a89b29e9c..806feca88 100644 --- a/crates/ui-widgets/src/menu/item.rs +++ b/crates/ui-widgets/src/menu/item.rs @@ -89,6 +89,9 @@ pub struct MenuItemOutput { pub opens_submenu: bool, /// A submenu row's submenu is the open one of its level: show the `Menu` after the row. pub submenu_open: bool, + /// The row is its level's active row and paints with the row fill: the pointer moved onto it, or the keyboard + /// moved to it. + pub active: bool, /// The row's rect grown by the menu's padding: where a submenu hangs from, so its first row is level with this one /// and it starts at the popup's edge. pub(crate) frame: Rect, @@ -149,7 +152,8 @@ fn label_line(area: Rect, detail: f32) -> Rect { /// - [`keep_open`](MenuItem::keep_open) keeps the menus open when the row runs (a check row that toggles). /// - The mnemonic is the `&` letter of the label, else the first letter no earlier row of the level uses. The /// underline sits under that letter while Alt is held or the keyboard drives the menu, never on macOS. -/// - The pointer moves the level's active row; the row under it paints with the shared row fill. +/// - The level's active row paints with the shared row fill: the row the pointer moved onto (its `Menu` sets it +/// before the rows run), or the one the keyboard moved to. /// - A [`tint`](MenuItem::tint) (a user label colour) fills the row behind its content at a strength the theme keeps /// the text readable on (`MenuTint`); the active, open and disabled looks win over it. The row keeps its text, so the /// colour is never the only cue. @@ -453,7 +457,7 @@ impl Component for MenuItem<'_> { let takes_over = hovered && (!heading || rested >= AIM_REST); // The focused row of a menu that the pointer opened is not active: the keyboard makes it so when focus lands on // it or the keyboard starts driving the menu. - if enabled && ((hovered && moving) || (focused && keyboard && (focus_gained || key_started))) && level.activate_row(cx.id) { + if enabled && focused && keyboard && (focus_gained || key_started) && level.activate_row(cx.id) { frame::request_repaint(&ctx); } // A disabled row is never active. @@ -607,7 +611,16 @@ impl Component for MenuItem<'_> { // The frame is where a submenu hangs: the row with the popup padding, widened by `gap.tight` on both sides so a // submenu that flips to the other side keeps the gap. let frame = cx.response.rect.expand(level.pad()).expand2(egui::vec2(cx.style.submenu_gap, 0.0)); - MenuItemOutput { response: cx.response.clone(), ran: self.ran, opens_submenu: self.opens, submenu_open: self.open, frame, level, id: cx.id } + MenuItemOutput { + response: cx.response.clone(), + ran: self.ran, + opens_submenu: self.opens, + submenu_open: self.open, + active: self.active, + frame, + level, + id: cx.id, + } } } diff --git a/crates/ui-widgets/src/menu/level.rs b/crates/ui-widgets/src/menu/level.rs index 3a01df9c0..2cdaa99da 100644 --- a/crates/ui-widgets/src/menu/level.rs +++ b/crates/ui-widgets/src/menu/level.rs @@ -281,6 +281,17 @@ impl MenuLevel { }) } + /// Makes the enabled row `under` names, among the rows as the user last saw them, the active row: the row the + /// pointer moved onto. Returns whether that changed it. + pub(super) fn follow_pointer(&self, under: impl Fn(Id) -> bool) -> bool { + self.with(|state| { + let Some(row) = state.shown.iter().find(|row| row.enabled && under(row.id)).map(|row| row.id) else { return false }; + let changed = state.active != Some(row); + state.active = Some(row); + changed + }) + } + pub(crate) fn active(&self) -> Option { self.with(|state| state.active) } diff --git a/crates/ui-widgets/src/menu/popup.rs b/crates/ui-widgets/src/menu/popup.rs index dd451a818..393472a4f 100644 --- a/crates/ui-widgets/src/menu/popup.rs +++ b/crates/ui-widgets/src/menu/popup.rs @@ -298,7 +298,8 @@ impl Component for Menu<'_> { Sense::empty() } - /// A row of a submenu level that took Back closes the menu. A typed letter runs the row its mnemonic names; the + /// A pointer move onto an enabled row of the level makes it the active row, before the rows run. A row of a + /// submenu level that took Back closes the menu. A typed letter runs the row its mnemonic names; the /// container claims the letters, so a letter works whichever row is focused. A level the pointer opened with no active row has no lead: /// the first key enters it at an end. The active row is the lead, so the first key after the pointer lit a row /// moves from that row; a row lit in this pass leads from the next, so only a key in the same frame as the pointer @@ -323,6 +324,12 @@ impl Component for Menu<'_> { level.run(row); frame::request_repaint(&cx.core.ctx); } + // The rows run after this, so the pass that moved the pointer onto a row paints it, and the row it left, as the + // level now has them. + if crate::runtime::pointer::frame(&cx.core.ctx).delta != egui::Vec2::ZERO { + let ctx = cx.core.ctx.clone(); + level.follow_pointer(|row| crate::runtime::pointer::hovers(&ctx, row)); + } let keyboard = crate::runtime::focus::keyboard_in_menu(&cx.core.ctx); self.props.roving = self.props.roving.map(|roving| roving.no_lead(!keyboard && !level.has_active())); if let Some(row) = level.active() { diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index 7c36a791e..f6f5bb7ad 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -23,8 +23,12 @@ pub enum TabKind { pub enum FitMode { /// Whole widths; only an active tab wider than the strip is cut. Whole, - /// The widest tabs shrink to the minimum width, then the rest overflow. - Shrink, + /// The widest tabs shrink to the minimum width, then the rest overflow. With `keep_selected` the selected tab is + /// not among the tabs that shrink, and the overflow takes the last tabs first. + Shrink { + /// Whether the selected tab keeps its natural width. + keep_selected: bool, + }, } impl FitMode { @@ -33,7 +37,7 @@ impl FitMode { pub fn fit(self, natural: &[f32], selected: usize, available: f32, minimum: f32, overflow: f32) -> TabFit { match self { FitMode::Whole => fit_whole(natural, selected, available, overflow), - FitMode::Shrink => fit(natural, selected, available, minimum, overflow), + FitMode::Shrink { keep_selected } => fit(natural, selected, available, minimum, overflow, keep_selected), } } } @@ -63,10 +67,21 @@ impl TabKind { pub fn fit_mode(self) -> FitMode { match self { Self::Document | Self::Text => FitMode::Whole, - Self::Panel => FitMode::Shrink, + Self::Panel => FitMode::Shrink { keep_selected: self.keeps_active_width() }, } } + /// Whether the shown tab keeps its whole title while the other tabs shrink: panel tabs. + pub fn keeps_active_width(self) -> bool { + self == Self::Panel + } + + /// Whether a label too long for its tab is clipped at the tab's edge (panel tabs, which shrink to their first + /// letters) instead of ending in an ellipsis. + pub fn clips_label(self) -> bool { + self == Self::Panel + } + /// Where the overflow button sits: at the strip's end for document and text tabs, after the last tab for panel /// tabs. pub fn overflow_place(self) -> OverflowPlace { diff --git a/crates/ui-widgets/src/tabs/strip/stories.rs b/crates/ui-widgets/src/tabs/strip/stories.rs index 483774186..95830e1bf 100644 --- a/crates/ui-widgets/src/tabs/strip/stories.rs +++ b/crates/ui-widgets/src/tabs/strip/stories.rs @@ -92,3 +92,14 @@ fn tab_strip_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn tab_strip_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { strip(ui, data, TabStrip::new("Panels").shown(1), &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; + +#[story(TabStrip<'static, usize>, covers = [], drive = Drive::Never)] +fn tab_strip_panel_narrow(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + crate::testing::memory::scoped(ui, |ui| { + ui.set_max_width(NARROW_ROOM); + strip(ui, data, TabStrip::new("Panels").shown(1), &TITLES, TITLES.len(), TabKind::Panel) + }) +} diff --git a/crates/ui-widgets/src/tabs/tab.rs b/crates/ui-widgets/src/tabs/tab.rs index ecaac48c4..2909a2577 100644 --- a/crates/ui-widgets/src/tabs/tab.rs +++ b/crates/ui-widgets/src/tabs/tab.rs @@ -2,7 +2,7 @@ //! //! Selection, the lead, the focus ring and the drag ghost belong to the collection that shows the tab; the tab draws //! the look the item step gives it and reports what its own parts do. The strip gives the tab a rect: the tab's -//! measure is its natural width (`Proposal::Min` the narrowest it shrinks to), and a narrower rect cuts the label +//! 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}; @@ -13,7 +13,7 @@ use crate::contract::{ Styled as _, WordSetCx as _, }; use crate::display::Progress; -use crate::primitives::{IconSpec, PaintShape, RectSide, StrokeWidth, TextRun}; +use crate::primitives::{IconSpec, PaintShape, RectSide, StrokeWidth, TextRun, Wrap}; use crate::runtime::env::Label; use crate::style::{ComponentStyle, Flags, IconLook, RuleKind, StyleColor, StyleCx, SurfaceLook, TextLook}; use craft_behavior::{Flow, IconId, Insets, Metrics, PartKey, PointerButton, PressPhase, Proposal, Sense}; @@ -59,6 +59,9 @@ const TEXT: PartKey = PartKey::new("text"); const CLOSE: PartKey = PartKey::new("close"); const PROGRESS: PartKey = PartKey::new("progress"); +/// How many of a title's first letters a shrunk tab still shows. +const MIN_LETTERS: usize = 3; + /// The modified mark. const MARK: &str = "*"; @@ -72,8 +75,6 @@ struct Sizes { close_box: f32, /// Room after a text tab's contents. tail: f32, - /// The narrowest content width: what a shrinking tab keeps. - min_content: f32, label_line: f32, detail_line: f32, underline_gap: f32, @@ -252,7 +253,6 @@ impl Component for Tab<'_> { icon: size.icon.sm, close_box: size.icon.md, tail: if text_only { space.gap.section } else { 0.0 }, - min_content: size.icon.md, label_line: line(role), detail_line: line(TypeRole::Caption), underline_gap: space.gap.tight, @@ -276,7 +276,9 @@ impl Component for Tab<'_> { fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { let sizes = &cx.style.sizes; if cx.proposal == Proposal::Min { - return Vec2::new(sizes.min_content, sizes.label_line); + let first: String = cx.resolved.label.chars().take(MIN_LETTERS).collect(); + let letters = cx.layout_at(&self.label_run(cx.style, &first), f32::INFINITY).size().x; + return Vec2::new(letters, sizes.label_line); } let width = |run: &TextRun<'_>| cx.layout_at(run, f32::INFINITY).size().x; let mut natural = sizes.tail + width(&self.label_run(cx.style, cx.resolved.label)); @@ -415,8 +417,8 @@ impl Component for Tab<'_> { let line = PaintShape::Path(vec![Pos2::new(placed.label.left(), y), Pos2::new(placed.label.right(), y)]); draw.stroke(&line, StrokeWidth::Thick, style.underline); } - let label = self.label_run(style, cx.resolved.label).color(cx.resolve(&style.label.color)).elide(); - draw.text(placed.label, &label); + let label = self.label_run(style, cx.resolved.label).color(cx.resolve(&style.label.color)); + draw.text(placed.label, &if self.kind.clips_label() { label.wrap(Wrap::Clip) } else { label.elide() }); if let (Some(at), Some(detail)) = (placed.detail, self.detail_text()) { draw.text(at, &TextRun::new(detail).role(style.detail.role).color(cx.resolve(&style.detail.color)).elide()); } diff --git a/crates/ui-widgets/src/text/hex.rs b/crates/ui-widgets/src/text/hex.rs index 0c5d6aa8a..08d6fbb6a 100644 --- a/crates/ui-widgets/src/text/hex.rs +++ b/crates/ui-widgets/src/text/hex.rs @@ -119,9 +119,12 @@ impl<'a> TextField<'a, HexCodec> { field } + /// The text before a hex field. + pub const HASH: &'static str = "#"; + /// The `#` before a hex field: the glyph side label of the `Field` that holds it, in every place a hex field shows. pub fn hash_label() -> SideLabel { - SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text("#"))) + SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(Self::HASH))) } /// Digits per channel: 2 (`RRGGBB`, the default) or 1 (`RGB`, a web colour). diff --git a/crates/ui-widgets/tests/it/menu/bar.rs b/crates/ui-widgets/tests/it/menu/bar.rs index c1571c088..be86bf637 100644 --- a/crates/ui-widgets/tests/it/menu/bar.rs +++ b/crates/ui-widgets/tests/it/menu/bar.rs @@ -93,3 +93,56 @@ fn a_letter_runs_the_row_it_marks_in_a_menu_a_title_click_opened() { assert_eq!(saved.get(), 1, "the letter runs the row it marks"); assert!(fixture.by_label("Save").is_none(), "and the run closes the menu"); } + +/// The pass a pointer move over a menu's rows runs paints the row under the pointer as the active row and no other, +/// moving down or up, at 1x and at a fractional scale. The two frames egui runs after any frame with input change +/// nothing, and then the menu asks for none. +#[trial] +fn a_pointer_move_over_menu_rows_lights_the_row_under_it_in_that_frame() { + use craft_behavior::MotionMode; + use craft_ui::runtime::env::Scale; + use craft_ui::testing::pointer; + use std::cell::RefCell; + use std::collections::HashMap; + use std::rc::Rc; + const ROWS: usize = 8; + let names: Vec = (1..=ROWS).map(|at| format!("Item {at:02}")).collect(); + for scale in [1.0, 1.5] { + let lit: Rc>> = Rc::default(); + let seen = lit.clone(); + let rows = names.clone(); + let mut fixture = Fixture::new(move |ui| { + let seen = seen.clone(); + let rows = rows.clone(); + let titles = vec![MenuTitle::new("&File", move |ui| { + for name in &rows { + let active = MenuItem::new(name.clone()).show(ui).active; + // The last run of the frame is the one that paints. + seen.borrow_mut().insert(name.clone(), active); + } + })]; + MenuBar::new("Main menu", titles).show(ui); + }); + fixture.room(egui::vec2(480.0, 320.0)).scale(Scale::new(scale)).motion(MotionMode::Off).settle(); + let file = fixture.by_label("File").expect("the File title"); + fixture.click(&file); + fixture.settle(); + let shown: Vec<(String, egui::Pos2)> = + names.iter().map(|name| (name.clone(), fixture.by_label(name).expect("the File menu shows every row").center())).collect(); + let downward = shown.iter(); + let upward = shown.iter().rev().skip(1); + for (name, center) in downward.chain(upward) { + lit.borrow_mut().clear(); + fixture.frame(vec![pointer::moved(*center)]); + let active: Vec = lit.borrow().iter().filter(|(_, on)| **on).map(|(row, _)| row.clone()).collect(); + assert_eq!(active, vec![name.clone()], "at {scale}x the move frame onto {name} lights it and no other row"); + // egui repaints twice for a frame with input; the menu asks for nothing beyond that. + for _ in 0..2 { + lit.borrow_mut().clear(); + fixture.frame(Vec::new()); + assert_eq!(lit.borrow().get(name), Some(&true), "at {scale}x {name} stays lit with the pointer at rest"); + } + assert!(!fixture.repaint_requested(), "at {scale}x a pointer at rest on {name} asks for no frame"); + } + } +} diff --git a/crates/ui-widgets/tests/it/tabs.rs b/crates/ui-widgets/tests/it/tabs.rs index e48239e9a..3ab12a907 100644 --- a/crates/ui-widgets/tests/it/tabs.rs +++ b/crates/ui-widgets/tests/it/tabs.rs @@ -321,3 +321,46 @@ fn the_strip_reports_the_tab_under_the_pointer_while_another_root_holds_the_pres fixture.frame(vec![]); assert_eq!(*seen.borrow(), None, "the empty room has no tab"); } + +const PANELS: [&str; 6] = ["Layers", "Channels", "Properties", "Adjustments", "History", "Navigator"]; + +/// The widths of the panel tabs a strip shows in a room `room` wide, by title, with the second panel shown. +fn panel_widths(room: f32) -> Vec<(&'static str, f32)> { + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + ui.set_max_width(room); + let keys = [0_usize, 1, 2, 3, 4, 5]; + let source = keyed(&keys, |key: &usize| *key); + TabStrip::new("Panels").kind(TabKind::Panel).shown(1).show_items(ui, &source, &mut |key, _| Tab::new(PANELS[*key])); + }; + frames.idle(3, &mut show); + let tree = frames.tree(); + PANELS.iter().filter_map(|name| tab_rects(&tree, name).first().map(|rect| (*name, rect.width()))).collect() +} + +/// Panel tabs shrink around the shown tab: it keeps its whole title while the others keep their first letters, and +/// tabs overflow from the end only when even those do not fit. +#[trial] +fn panel_tabs_keep_the_shown_tab_whole_and_overflow_from_the_end() { + let wide = panel_widths(2000.0); + assert_eq!(wide.len(), PANELS.len(), "every tab fits in a wide room"); + let natural_shown = wide[1].1; + let mut fewer = wide.len(); + for room in [700.0, 500.0, 400.0, 300.0, 220.0] { + let shown = panel_widths(room); + assert!(!shown.is_empty() && shown.len() <= fewer, "rooms below shrink tabs, never add them: {room} {shown:?}"); + fewer = shown.len(); + let active = shown.iter().find(|(name, _)| *name == PANELS[1]).expect("the shown tab stays"); + assert!((active.1 - natural_shown).abs() < 1.0, "the shown tab keeps its width in {room}: {shown:?}"); + let others: Vec = shown.iter().filter(|(name, _)| *name != PANELS[1]).map(|&(_, w)| w).collect(); + let least = others.iter().copied().fold(f32::INFINITY, f32::min); + assert!(least > 0.0, "every shown tab keeps room for letters in {room}: {shown:?}"); + let hidden: Vec<&str> = PANELS.iter().copied().filter(|name| shown.iter().all(|(shown, _)| shown != name)).collect(); + let first = PANELS.iter().position(|name| hidden.contains(name)); + if let Some(first) = first { + let after = PANELS[first..].iter().filter(|name| **name != PANELS[1]); + assert!(after.into_iter().all(|name| hidden.contains(name)), "overflow takes the last tabs: {hidden:?}"); + } + } + assert!(fewer < PANELS.len(), "the narrowest room overflows"); +}