diff --git a/crates/automation/src/ui/actions/panel.rs b/crates/automation/src/ui/actions/panel.rs index 8429d5025..179ff8a17 100644 --- a/crates/automation/src/ui/actions/panel.rs +++ b/crates/automation/src/ui/actions/panel.rs @@ -60,7 +60,9 @@ impl ActionsSettings { /// The Actions panel's persisted section: Button Mode and the collapsed sets. /// Selection and expansion are not persisted. -#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, +)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ActionsSettings { @@ -72,7 +74,7 @@ pub struct ActionsSettings { /// A row of the tree: a set header, an action or one of its steps. Also the selection (one row at /// a time) and the list's key. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum ActionSelection { /// The set header of this name. @@ -89,7 +91,7 @@ pub enum ActionSelection { /// The panel remaps `selected` itself when it reports a [`Reorder`](ActionsEvent::Reorder) /// that moves a row, since it owns the selection. After a [`Delete`](ActionsEvent::Delete) the /// app clears `selected` (the panel cannot tell which rows the delete removed). -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct ActionsPanelState { /// The persisted section. diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index b640c8dd7..bdc13e7f7 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -124,6 +124,34 @@ impl Format { } } +/// Most files [`list_folder`] lists. +const MAX_FILES: usize = 500; +/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB. +const MAX_BYTES: u64 = 64 << 20; + +/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name +/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files +/// too large to be a LUT are skipped, and a symlink to a LUT file is listed. +pub fn list_folder(dir: &std::path::Path) -> Vec<(String, std::path::PathBuf)> { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut out: Vec<(String, std::path::PathBuf)> = entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().into_string().ok()?; + let extension = name.rsplit_once('.')?.1.to_ascii_lowercase(); + if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") { + return None; + } + let path = entry.path(); + let meta = std::fs::metadata(&path).ok()?; + (meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path)) + }) + .collect(); + out.sort_by_key(|(name, _)| name.to_lowercase()); + out.truncate(MAX_FILES); + out +} + /// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing). pub fn parse(file_name: &str, bytes: &[u8]) -> Result { parse_as(Format::detect(file_name, bytes), bytes) diff --git a/crates/color-ui/src/ui/lut_picker.rs b/crates/color-ui/src/ui/lut_picker.rs index afdb6a71d..2937f1207 100644 --- a/crates/color-ui/src/ui/lut_picker.rs +++ b/crates/color-ui/src/ui/lut_picker.rs @@ -4,8 +4,7 @@ //! [`Files`](craft_host::Files) and reads and parses it as a [`Jobs`](craft_host::Jobs) job. use std::path::{Path, PathBuf}; -use std::sync::{Arc, OnceLock}; -use std::time::Instant; +use std::sync::Arc; use craft_behavior::{EditEvent, EditEvents, Metrics, Mixed, Proposal, Sense}; use craft_cms::lutfile::{LutError, LutFile}; @@ -16,6 +15,7 @@ use craft_ui::contract::{ }; use craft_ui::pickers::Select; use craft_ui::runtime::env::Label; +use craft_ui::runtime::frame; use craft_ui::style::{ComponentStyle, StyleCx}; use egui::{Response, Vec2}; @@ -154,12 +154,6 @@ impl Default for Parsed { } } -/// The seconds since the first scan of the process, for the rescan interval. -fn seconds() -> u64 { - static START: OnceLock = OnceLock::new(); - START.get_or_init(Instant::now).elapsed().as_secs() -} - /// A select of LUTs. /// /// - Rows: Load 3D LUT…, None, the eight built-in looks, the LUT folder's files by name (in the language's @@ -269,9 +263,11 @@ impl Component for LutPicker<'_> { state = LutState { folder: self.folder.clone(), load: state.load, ..LutState::default() }; } if let Some(folder) = self.folder.clone() { - let key = ("lut-scan", folder.clone(), seconds() / RESCAN); + let key = ("lut-scan", folder.clone(), frame::stepped_clock(&cx.response.ctx, RESCAN as f64) as u64 / RESCAN); let started = folder.clone(); - if let Pending::Ready(found) = cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(list_folder(&started))))) { + if let Pending::Ready(found) = + cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(craft_cms::lutfile::list_folder(&started))))) + { let mut files = (**found).clone(); cx.env.collator().sort_by_key(&mut files, |(name, _)| name.as_str()); state.files = Arc::new(files); @@ -378,30 +374,3 @@ fn builtin_name(words: &LutWords, id: &str) -> Label { fn file_name(path: &Path) -> String { path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()) } -/// Most files [`list_folder`] lists. -const MAX_FILES: usize = 500; -/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB. -const MAX_BYTES: u64 = 64 << 20; - -/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name -/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files -/// too large to be a LUT are skipped, and a symlink to a LUT file is listed. -fn list_folder(dir: &Path) -> FolderFiles { - let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; - let mut out: FolderFiles = entries - .flatten() - .filter_map(|entry| { - let name = entry.file_name().into_string().ok()?; - let extension = name.rsplit_once('.')?.1.to_ascii_lowercase(); - if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") { - return None; - } - let path = entry.path(); - let meta = std::fs::metadata(&path).ok()?; - (meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path)) - }) - .collect(); - out.sort_by_key(|(name, _)| name.to_lowercase()); - out.truncate(MAX_FILES); - out -} diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 76c85e775..1326059f6 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -62,7 +62,19 @@ craft_ui::words! { /// What the panel shows: Photoshop's panel menu choices, in its order. Hue Cube is the default; /// the theme never changes it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelMode { @@ -129,7 +141,19 @@ impl ColorPanelMode { } /// The ramp under the sliders. Shift-click on the ramp cycles them in this order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelRamp { @@ -179,7 +203,9 @@ impl ColorPanelRamp { } /// The Color panel's settings, kept across runs (settings section `color_panel`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, +)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ColorPanelState { diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 7751a0f6c..20ac95787 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,7 +75,7 @@ reason = "document-space drawing" | `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` | | `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is | | `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. | -| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or later task that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | +| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or test-data cache that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui. diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 22cafcd4f..93407230a 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -138,8 +138,8 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[ ]; /// The reviewed per-item allowlist of `contract/no-global-state`: a file and what it may hold, either the identifier of -/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact or environment key that -/// covers it, or the later task of craft-libs#2336 that removes the state. A new item in these files is flagged. +/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact, environment key or test-data +/// cache that covers it. A new item in these files is flagged. const NO_GLOBAL_STATE: &[(&str, &str)] = &[ // Compile-time registry discovery reads the defining crate's source, never a view input. ("crates/ui-macros/src/registry.rs", FS), @@ -200,30 +200,8 @@ const NO_GLOBAL_STATE: &[(&str, &str)] = &[ ("crates/imaging/src/ui/layer_style/hosted.rs", "PAINT"), // Settled fact: a test fake of the font store; it writes a temporary folder. ("crates/font-manager/src/store/fake.rs", FS), - // later task of #2336: the brush trail id counter is hidden state. - ("crates/ui-canvas/src/canvas_controls/brush/trail.rs", "NEXT_ID"), - // later task of #2336: the outline hover generation counter is hidden state. - ("crates/ui-canvas/src/canvas_controls/outline/hover.rs", "GENERATIONS"), - // later task of #2336: the texture serial counter is hidden state. - ("crates/imaging/src/ui/transform_preview/textures.rs", "SERIAL"), - // later task of #2336: the mock image read cache is hidden state. + // A cache of pure test data: MockImage is used only by stories and trials. ("crates/imaging/src/ui/mock_image.rs", "READS"), - // later task of #2336: the ranking cache is hidden state. - ("crates/font-manager/src/picker/rank.rs", "CACHE"), - // later task of #2336: the face loader reads file sizes during the pass. - ("crates/font-manager/src/panel/faces.rs", FS), - // later task of #2336: the gallery's set of seen names is hidden state. - ("crates/ui-gallery/src/viewer/layout.rs", "NAMES"), - // later task of #2336: the LUT picker reads the process clock and scans folders during the pass. - ("crates/color-ui/src/ui/lut_picker.rs", "START"), - ("crates/color-ui/src/ui/lut_picker.rs", FS), -]; - -/// Files that may read a clock (`contract/motion:clock`) beyond the runtime's motion module. A file key, because -/// color-ui has no layer map. -const MOTION_CLOCK_FILES: &[&str] = &[ - // later task of #2336: the LUT picker reads the process clock during the pass. - "crates/color-ui/src/ui/lut_picker.rs", ]; /// Whether `what` (an item identifier or [`FS`]) may be declared or used in `file` for `contract/no-global-state`. @@ -405,9 +383,6 @@ impl RuleScope for WorkspaceScope { if let Some(what) = key.strip_prefix("contract/no-global-state:") { return no_global_state_allows(what, file); } - if key == "contract/motion:clock" && MOTION_CLOCK_FILES.iter().any(|f| file == Path::new(f)) { - return true; - } if key == "test/layout" { return file.starts_with(krate.dir.join("tests").join("it")); } diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index 10663e6af..a3464fed4 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -307,6 +307,7 @@ type FamilyLoad = Arc>>; /// Each family's files load once ([`Catalog::load_family`]): other threads asking for the same /// family wait for that load, other families load at the same time. pub struct Catalog { + id: u64, env: FontEnv, config: RwLock, index: RwLock>, @@ -331,7 +332,9 @@ impl Catalog { /// A catalog of the fonts installed on the system `env` describes, the font store, and the /// files the platform's font service lists (with the `system` feature). pub fn new(env: FontEnv) -> Self { + static NEXT_ID: AtomicU64 = AtomicU64::new(1); Self { + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), env, config: RwLock::new(Config { app_dirs: Vec::new(), listers: Vec::new(), font_service: cfg!(feature = "system") }), index: RwLock::new(Arc::new(Index::default())), @@ -475,6 +478,13 @@ impl Catalog { Watch { stop } } + /// The catalog's identity: unique among the catalogs of the process, fixed at construction. Clones of the `Arc` + /// share it. A holder of derived data keys it by the id and the [`generation`](Catalog::generation), which counts + /// changes of this catalog only. + pub fn id(&self) -> u64 { + self.id + } + /// Counts the catalog's changes: each scan, and each face added or removed. pub fn generation(&self) -> u64 { self.generation.load(Ordering::Acquire) diff --git a/crates/font-catalog/src/scan.rs b/crates/font-catalog/src/scan.rs index 9afd1ac88..5466024e5 100644 --- a/crates/font-catalog/src/scan.rs +++ b/crates/font-catalog/src/scan.rs @@ -98,6 +98,9 @@ pub struct FaceInfo { pub code_pages: [u32; 2], /// The file the face is in; `None` for a face added as bytes. pub path: Option, + /// The size in bytes of the file when it was scanned; `None` for a face added as bytes. A caller that draws with the + /// face checks it before loading, so no file system read happens while it paints. + pub file_bytes: Option, /// The face's number in its file: its index in a collection (0 in a single font), or for a /// Mac suitcase font the number of its `sfnt` resource. pub index: u32, @@ -329,6 +332,7 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: fs_type, code_pages, path: path.map(Path::to_path_buf), + file_bytes: None, index, source, blob: None, @@ -430,9 +434,11 @@ pub(crate) fn file_faces(path: &Path, max_read: u64, source: Source) -> Vec String { /// The bytes of `face` from `catalog`, unless its file is too large to draw with. fn load(catalog: &Catalog, face: &FaceInfo) -> Option { - let too_large = face.path.as_ref().and_then(|path| std::fs::metadata(path).ok()).is_some_and(|meta| meta.len() > MAX_FILE_BYTES); + let too_large = face.file_bytes.is_some_and(|bytes| bytes > MAX_FILE_BYTES); if too_large { return None; } diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index dea1d1d7b..1521d943b 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -28,7 +28,8 @@ use egui::{Rect, Response, Vec2}; use serde::{Deserialize, Serialize}; use crate::missing::{DocumentFont, FontStatus, MissingFontsWords, document_fonts}; -use rank::{Info, infos, shown_name}; +pub use rank::FamilyInfos; +use rank::{Info, shown_name}; craft_ui::words! { /// The picker's words, English by default. @@ -288,9 +289,11 @@ pub struct FamilyRow { /// The families `listing` would show, in list order: recents first (when the query is empty and no filter is on), /// then the matching families, the best match first and ties in the order of `language` (its code, `ja`, `pt-BR`). -/// For apps that draw their own list from the picker's filtering. +/// For apps that draw their own list from the picker's filtering. `infos` is [`FamilyInfos::of`] of `catalog`, built +/// again by the app when the catalog's generation moves. pub fn family_rows( catalog: &Arc, + infos: &FamilyInfos, query: &str, settings: Option<&FontPickerSettings>, filters: &FontFilters, @@ -299,7 +302,12 @@ pub fn family_rows( ) -> Vec { let (folder, collator) = (craft_i18n::Folder::new(language), craft_i18n::Collator::new(language)); let listing = rank::Listing { query, settings, filters, current, language, served: &[] }; - rank::list(catalog, &infos(catalog), &listing, &rank::Language { folder: &folder, collator: &collator }, true).0 + rank::list(catalog, infos, &listing, &rank::Language { folder: &folder, collator: &collator }, true).0 +} + +/// The family data of `catalog` for the component `cx`: kept across passes while the catalog and its generation are unchanged. +pub(super) fn infos_of(ctx: &egui::Context, id: egui::Id, catalog: &Catalog) -> Arc { + craft_ui::runtime::derived::derived(ctx, id, &(catalog.id(), catalog.generation()), || FamilyInfos::of(catalog)) } /// How a [`FontPicker`] lays out its list. @@ -380,7 +388,7 @@ fn text_key() -> TextKey { /// The family field's text: the family's name in the interface language, and a typed name read back as a family. #[derive(Clone)] struct FamilyCodec { - infos: Arc, + infos: Arc, language: String, /// A typed name that is no installed family is a value too (Word's font box applies it as typed). free: bool, @@ -566,13 +574,13 @@ impl<'a> FontPicker<'a> { Some(Label::from(note)) } - fn codec(&self, env: &EnvView<'_>) -> FamilyCodec { - FamilyCodec { infos: infos(self.catalog), language: ui_language(env), free: self.kind == FontPickerKind::Plain } + fn codec(&self, infos: Arc, env: &EnvView<'_>) -> FamilyCodec { + FamilyCodec { infos, language: ui_language(env), free: self.kind == FontPickerKind::Plain } } /// The families in list order without filters or recents, which the arrows and the wheel step through. fn ordered(&self, cx: &Cx<'_, Self>, settings: Option<&FontPickerSettings>) -> Vec { - let infos = infos(self.catalog); + let infos = infos_of(&cx.response.ctx, cx.id, self.catalog); let (folder, collator) = (cx.env.folder(), cx.env.collator()); let filters = FontFilters::default(); let language = ui_language(&cx.env); @@ -631,7 +639,7 @@ impl Component for FontPicker<'_> { .pointer_only("Alt+Down opens the list") .toggles(POPUP); } - let codec = self.codec(&cx.env); + let codec = self.codec(infos_of(cx.ui.ctx(), cx.id, self.catalog), &cx.env); let mut options = TextOptions::new(); options.select_on_focus = true; cx.text(text_key(), placed.text, &codec, &family, &options); diff --git a/crates/font-manager/src/picker/rank.rs b/crates/font-manager/src/picker/rank.rs index 7d6637864..fa1f3f65a 100644 --- a/crates/font-manager/src/picker/rank.rs +++ b/crates/font-manager/src/picker/rank.rs @@ -2,7 +2,7 @@ //! traits read from the faces' tables, the filtered list and its order, and the sample text of a row. use std::collections::HashMap; -use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::sync::{Arc, Mutex, PoisonError}; use craft_font_catalog::{Catalog, FaceInfo, LocalizedName, Outlines}; use craft_i18n::matcher::{Matcher, Rank}; @@ -53,8 +53,10 @@ impl Traits { } } -/// The families of one catalog generation with their traits and sample texts, filled on first use. -pub(super) struct Infos { +/// The families of one catalog generation with their traits and sample texts, filled on first use. Built by +/// [`FamilyInfos::of`] and held by the one that lists with it: the picker keeps it in a derived value keyed by the +/// catalog's generation, and an app that calls [`family_rows`](super::family_rows) keeps its own while the catalog is unchanged. +pub struct FamilyInfos { pub(super) families: HashMap, traits: Mutex>>, samples: Mutex>, @@ -78,8 +80,9 @@ fn has_arabic_sample(drawn: &dyn Fn(&str) -> bool, latin: &str, arabic: &str) -> drawn(latin) && drawn(ARABIC_CORE) && drawn(arabic) } -impl Infos { - fn build(catalog: &Catalog) -> Infos { +impl FamilyInfos { + /// The family data of `catalog` as it is now; build it again when the catalog's generation moves. + pub fn of(catalog: &Catalog) -> FamilyInfos { let mut groups: HashMap> = HashMap::new(); for face in catalog.faces().iter() { groups.entry(face.family.clone()).or_default().push(face.clone()); @@ -99,7 +102,7 @@ impl Infos { Some((family, Info { localized, format, styles: faces.len(), regular })) }) .collect(); - Infos { families, traits: Mutex::new(HashMap::new()), samples: Mutex::new(HashMap::new()) } + FamilyInfos { families, traits: Mutex::new(HashMap::new()), samples: Mutex::new(HashMap::new()) } } /// The family's traits, read from its regular face on first use. @@ -147,24 +150,6 @@ fn draws(catalog: &Catalog, face: &FaceInfo, sample: &str, arabic: &str, shown: Some(Samples { latin: first, arabic: None }) } -type CacheEntry = (Weak, u64, Arc); -static CACHE: Mutex> = Mutex::new(Vec::new()); - -/// The family data of `catalog`, rebuilt when its generation moves. -pub(super) fn infos(catalog: &Arc) -> Arc { - let generation = catalog.generation(); - let same = |w: &Weak| std::ptr::eq(w.as_ptr(), Arc::as_ptr(catalog)); - let mut cache = lock(&CACHE); - cache.retain(|(w, _, _)| w.strong_count() > 0); - if let Some((_, _, infos)) = cache.iter().find(|(w, g, _)| *g == generation && same(w)) { - return Arc::clone(infos); - } - cache.retain(|(w, _, _)| !same(w)); - let infos = Arc::new(Infos::build(catalog)); - cache.push((Arc::downgrade(catalog), generation, Arc::clone(&infos))); - infos -} - /// The upright face nearest weight 400. pub(super) fn regular_face(faces: &[FaceInfo]) -> Option<&FaceInfo> { faces.iter().min_by_key(|f| (f.italic, (f.weight - 400.0).abs() as u32)) @@ -291,7 +276,13 @@ pub(super) struct Language<'a> { /// The rows the list shows for `listing` and whether Show Similar Fonts had a reference to compare with: recents /// first (when the query is empty and no filter is on), then the matching families, the best match first and ties /// in the interface language's order. A list that is not `narrowed` has no filters and no recents. -pub(super) fn list(catalog: &Arc, infos: &Infos, listing: &Listing<'_>, language: &Language<'_>, narrowed: bool) -> (Vec, bool) { +pub(super) fn list( + catalog: &Arc, + infos: &FamilyInfos, + listing: &Listing<'_>, + language: &Language<'_>, + narrowed: bool, +) -> (Vec, bool) { let default_filters = FontFilters::default(); let filters = if narrowed { listing.filters } else { &default_filters }; let settings = listing.settings; diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index bd76e0aa5..c35f4cac9 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -22,10 +22,10 @@ use craft_ui::primitives::{ContentPainterCx, IconSpec}; use craft_ui::runtime::env::Label; use egui::Rect; -use super::rank::{Infos, Language, Listing, list, shown_name}; +use super::rank::{FamilyInfos, Language, Listing, list, shown_name}; use super::{ - FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos, read, - ui_language, write, + FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos_of, + read, ui_language, write, }; use crate::panel::faces::{Owner, Shown, paint_sample, shown}; use craft_ui::style::DataColor; @@ -256,7 +256,7 @@ fn class_column(ui: &mut egui::Ui, filters: &mut FontFilters, words: &FontPicker /// A thumbnail painting `text` in the regular face of `family`; nothing for a family the catalog lacks or an empty /// text, and nothing until the face is loaded. -fn face_thumb<'a>(catalog: &'a Arc, infos: &'a Infos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a { +fn face_thumb<'a>(catalog: &'a Arc, infos: &'a FamilyInfos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a { move |cx, rect| { let Some(info) = infos.families.get(family) else { return }; if text.is_empty() { @@ -270,7 +270,7 @@ fn face_thumb<'a>(catalog: &'a Arc, infos: &'a Infos, family: &'a str, } /// The banner: `text` in the face of `family`, on one line cut at the end, in a picture as high as the large thumbnail. -fn banner(ui: &mut egui::Ui, catalog: &Arc, infos: &Infos, family: &str, shown_name: &str, text: &str) { +fn banner(ui: &mut egui::Ui, catalog: &Arc, infos: &FamilyInfos, family: &str, shown_name: &str, text: &str) { Picture::painter(shown_name.to_owned(), ThumbAspect::new(BANNER_ASPECT.0, BANNER_ASPECT.1), face_thumb(catalog, infos, family, text.to_owned())) .extent(PictureSize::Thumb(ThumbSize::Large)) .show(ui); @@ -278,7 +278,7 @@ fn banner(ui: &mut egui::Ui, catalog: &Arc, infos: &Infos, family: &str /// The name the banner shows for `family`: its row's shown name when the list holds one, else its name in the /// interface language, else the family key. -fn banner_shown_name(slots: &[Slot], infos: &Infos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String { +fn banner_shown_name(slots: &[Slot], infos: &FamilyInfos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String { let row = slots.iter().find_map(|slot| match slot { Slot::Family { row, .. } if row.family == family => Some(row.shown.clone()), _ => None, @@ -338,7 +338,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: let has_filters = filters.is_some(); let narrowing = filters.clone().unwrap_or_default(); let catalog = picker.catalog; - let infos = infos(catalog); + let infos = infos_of(&cx.response.ctx, cx.id, catalog); let language_code = ui_language(&cx.env); let (folder, collator) = (cx.env.folder(), cx.env.collator()); let listing = Listing { diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 33c4f4775..8ef2bc258 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -9,7 +9,7 @@ use craft_behavior::{PartKey, Preview}; use craft_font_manager::craft_font_catalog::{Limits, Os, Source}; use craft_font_manager::missing::MissingFontsWords; use craft_font_manager::picker::{ - FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows, + FamilyInfos, FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows, }; use craft_font_manager::{Catalog, FontEnv}; use craft_ui::buttons::ControlPlace; @@ -18,7 +18,7 @@ use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::env::{Label, with_env}; use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::pointer::moved; -use craft_ui::testing::{Fixture, Room, trial}; +use craft_ui::testing::{Fixture, Room, last_frame_derived_builds, trial}; use egui::{Event, Key, Modifiers}; const INTER_REGULAR: &[u8] = include_bytes!("../../../ui-contract/fonts/inter/Inter-Regular.ttf"); @@ -125,14 +125,15 @@ fn similar_fonts_put_the_current_family_first_and_leave_the_list_alone_without_a let catalog = catalog_of(&[epaint_default_fonts::HACK_REGULAR, epaint_default_fonts::UBUNTU_LIGHT, INTER_REGULAR]); let mut similar = FontFilters::default(); similar.similar = true; - let rows = family_rows(&catalog, "", None, &similar, "Inter", "en"); + let infos = FamilyInfos::of(&catalog); + let rows = family_rows(&catalog, &infos, "", None, &similar, "Inter", "en"); let names: Vec<&str> = rows.iter().map(|row| row.family.as_str()).collect(); assert_eq!(names.first(), Some(&"Inter"), "the current family first, though it is not first by name"); assert!(rows.len() <= SIMILAR_COUNT); // A current family the catalog lacks has no traits: the list stays as unfiltered. - let unfiltered = family_rows(&catalog, "", None, &FontFilters::default(), "", "en"); - assert_eq!(family_rows(&catalog, "", None, &similar, "Missing", "en"), unfiltered); + let unfiltered = family_rows(&catalog, &infos, "", None, &FontFilters::default(), "", "en"); + assert_eq!(family_rows(&catalog, &infos, "", None, &similar, "Missing", "en"), unfiltered); } #[trial] @@ -360,3 +361,42 @@ fn a_squeezed_ribbon_font_box_keeps_a_short_fields_name() { assert!(squeezed > short, "the squeezed font box keeps a name field {short} wide and its arrow: {squeezed}"); assert!(squeezed <= picker_width("Inter", true) + 0.5, "and is no wider than where the room allows"); } + +/// The family data builds of the last frame. +fn family_builds(fx: &Fixture) -> u32 { + last_frame_derived_builds(fx.ctx()).iter().map(|(_, builds)| builds).sum() +} + +#[trial] +fn the_family_data_builds_when_the_catalog_changes_and_not_while_it_is_idle() { + let catalog = catalog_of(&[INTER_REGULAR]); + let (mut fx, _) = rig(Arc::clone(&catalog), vec![]); + open(&mut fx); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 0, "an idle open list builds nothing"); + catalog.add_bytes(INTER_SEMIBOLD.to_vec(), Source::Bundled, &Limits::default()).expect("a font file"); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 1, "a changed catalog builds the data once, whatever reads it"); +} + +#[trial] +fn a_picker_handed_another_catalog_at_the_same_generation_builds_its_family_data_once() { + let (one, two) = (catalog_of(&[INTER_REGULAR]), catalog_of(&[INTER_REGULAR])); + assert_eq!(one.generation(), two.generation(), "the two catalogs count alike"); + assert_ne!(one.id(), two.id()); + let shown = Rc::new(RefCell::new(Arc::clone(&one))); + let held = Rc::clone(&shown); + let mut family = String::new(); + let mut fx = Fixture::new(move |ui| { + let catalog = Arc::clone(&held.borrow()); + FontPicker::new("Font family", Bind::bound(&mut family), &catalog).show(ui); + }); + fx.in_room(Room::Window); + fx.settle(); + open(&mut fx); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 0, "the first catalog's data is kept"); + *shown.borrow_mut() = Arc::clone(&two); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 1, "the second catalog builds the data once"); +} diff --git a/crates/imaging/src/ui/histogram/data.rs b/crates/imaging/src/ui/histogram/data.rs index 6588b6aa6..a8521da70 100644 --- a/crates/imaging/src/ui/histogram/data.rs +++ b/crates/imaging/src/ui/histogram/data.rs @@ -207,7 +207,7 @@ impl HistogramData { } /// A range of whole levels (bin positions) a plot has selected, both ends included. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct LevelRange { /// The first level. diff --git a/crates/imaging/src/ui/scopes/panel/settings.rs b/crates/imaging/src/ui/scopes/panel/settings.rs index 6d14f3fb4..a61305622 100644 --- a/crates/imaging/src/ui/scopes/panel/settings.rs +++ b/crates/imaging/src/ui/scopes/panel/settings.rs @@ -4,7 +4,19 @@ use crate::ui::histogram::LevelRange; use crate::ui::scopes::clipping::{ClippingDiagnostic, ClippingMode, ClippingWarnings}; /// The panel's view (its menu's Compact, Expanded and All Channels View). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ScopeView { @@ -20,7 +32,7 @@ pub enum ScopeView { /// The scope panel's persisted section: the app keeps it with its preferences (PhotoCraft's /// `histogramPanel` and `filter.cameraRaw.scope`). Unknown fields are ignored, missing ones take /// their defaults. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ScopeSettings { @@ -93,7 +105,7 @@ impl ScopeSettings { /// What the panel keeps for the app between passes: the persisted settings and the selected /// level range (not persisted). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct ScopePanelState { /// The persisted section. diff --git a/crates/imaging/src/ui/transform_preview/mod.rs b/crates/imaging/src/ui/transform_preview/mod.rs index 3c2af1c32..0834d3b6a 100644 --- a/crates/imaging/src/ui/transform_preview/mod.rs +++ b/crates/imaging/src/ui/transform_preview/mod.rs @@ -11,9 +11,11 @@ //! ```no_run //! use craft_imaging::ui::transform_preview::{PreviewMap, PreviewPixels, PreviewTextures, TransformPreview}; //! use craft_ui::contract::Show as _; +//! use craft_ui::primitives::Serials; //! # fn demo(ui: &mut egui::Ui, canvas_rect: egui::Rect, image: egui::ColorImage, quad: [kurbo::Point; 4]) { -//! // Once per session: -//! let textures = PreviewTextures::new("ft-preview", PreviewPixels::new(image, [1.0, 1.0])); +//! // Once per session, with the `Serials` the owner of the previews holds: +//! let mut serials = Serials::default(); +//! let textures = PreviewTextures::new(&mut serials, "ft-preview", PreviewPixels::new(image, [1.0, 1.0])); //! // Every pass, in the canvas body under the guides and the box: //! TransformPreview::new("Moving layer", &textures).map(PreviewMap::quad(quad)).opacity(0.8).clip([800, 600]).show_at(ui, canvas_rect); //! # } diff --git a/crates/imaging/src/ui/transform_preview/stories.rs b/crates/imaging/src/ui/transform_preview/stories.rs index 66588c15b..27ee1c2ff 100644 --- a/crates/imaging/src/ui/transform_preview/stories.rs +++ b/crates/imaging/src/ui/transform_preview/stories.rs @@ -9,6 +9,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use craft_behavior::kurbo::{Point, Rect}; use craft_ui::canvas::{PixelRect, RasterSource}; use craft_ui::contract::Show as _; +use craft_ui::primitives::Serials; use craft_ui::testing::canvas_story::StoryDocument; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::{Color32, ColorImage, Ui}; @@ -102,7 +103,7 @@ impl Document { return Arc::clone(textures); } let name = format!("transform-story-{}x{}", size[0], size[1]); - let textures = Arc::new(PreviewTextures::from_levels(name, pyramid(size), [1.0, 1.0])); + let textures = Arc::new(PreviewTextures::from_levels(&mut Serials::default(), name, pyramid(size), [1.0, 1.0])); kept.push((size, Arc::clone(&textures))); textures } diff --git a/crates/imaging/src/ui/transform_preview/textures.rs b/crates/imaging/src/ui/transform_preview/textures.rs index d39c301af..06272c396 100644 --- a/crates/imaging/src/ui/transform_preview/textures.rs +++ b/crates/imaging/src/ui/transform_preview/textures.rs @@ -1,12 +1,11 @@ //! [`PreviewPixels`] and [`PreviewTextures`]: the moving pixels of a transform, read once and //! uploaded as a mip chain built on demand, off the UI thread where a finer level can stand in. -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use craft_host::queue::Cancel; use craft_ui::primitives::{ - LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, TextureLoader, TextureState, TextureStatistics, TextureStore, + LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, Serials, TextureLoader, TextureState, TextureStatistics, TextureStore, TextureStoreOptions, }; use egui::{Color32, ColorImage, Context, TextureId, TextureOptions}; @@ -114,9 +113,6 @@ pub struct TextureChoice { /// The key of a preview's level in the shared stores: the preview's name and the level. type LevelKey = (Arc, u32); -/// Tells previews apart in the store revisions: a preview made under an old name with new pixels gets a new serial. -static SERIAL: AtomicU64 = AtomicU64::new(0); - /// The moving pixels uploaded for the preview: level 0 at once, the other mip levels (2 × 2 box filtered) and the /// nearest-filtered level 0 on first use. The CPU levels are kept for the session. /// @@ -137,21 +133,22 @@ pub struct PreviewTextures { } impl PreviewTextures { - /// The preview of `pixels`, named `name`: the store entries are keyed by it. Nothing is - /// uploaded until the preview is painted. - pub fn new(name: impl Into, pixels: PreviewPixels) -> Self { + /// The preview of `pixels`, named `name`: the store entries are keyed by it. `serials` tells this preview from an + /// earlier one of the same name (new pixels under an old name replace its textures); the previews of one owner + /// share it. Nothing is uploaded until the preview is painted. + pub fn new(serials: &mut Serials, name: impl Into, pixels: PreviewPixels) -> Self { let base_uv = pixels.base_uv; - Self::over(name, vec![Arc::new(pixels.image)], base_uv) + Self::over(serials, name, vec![Arc::new(pixels.image)], base_uv) } /// The preview over `levels` already built, level 0 first, covering the source with `base_uv`. #[cfg(feature = "screen-testing")] - pub(crate) fn from_levels(name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { - Self::over(name, levels, base_uv) + pub(crate) fn from_levels(serials: &mut Serials, name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { + Self::over(serials, name, levels, base_uv) } - fn over(name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { - let serial = SERIAL.fetch_add(1, Ordering::Relaxed); + fn over(serials: &mut Serials, name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { + let serial = serials.mint(); Self { name: Arc::from(name.into()), serial, images: Arc::new(Mutex::new(levels)), base_uv } } diff --git a/crates/imaging/tests/it/transform_preview.rs b/crates/imaging/tests/it/transform_preview.rs index 882771cb6..ff6757207 100644 --- a/crates/imaging/tests/it/transform_preview.rs +++ b/crates/imaging/tests/it/transform_preview.rs @@ -15,6 +15,7 @@ use craft_imaging::ui::transform_preview::{ use craft_imaging::ui::warp::WarpMesh; use craft_ui::canvas::{Canvas, PixelRect}; use craft_ui::contract::{MemoProps, MemoView, PlainData, Show as _, ShowContainer as _, Tracked}; +use craft_ui::primitives::Serials; use craft_ui::testing::{Fixture, trial}; use egui::{Color32, ColorImage, Shape}; @@ -31,7 +32,7 @@ fn shown(map: fn() -> PreviewMap<'static>, opacity: f32, clip: Option<[u32; 2]>, let meshes = Rc::new(RefCell::new(Vec::new())); let seen_view = Rc::new(Cell::new(None)); let (sink, view_sink) = (Rc::clone(&meshes), Rc::clone(&seen_view)); - let textures = PreviewTextures::new("t", PreviewPixels::new(solid([2, 2], Color32::from_gray(u8::MAX)), [1.0, 1.0])); + let textures = PreviewTextures::new(&mut Serials::default(), "t", PreviewPixels::new(solid([2, 2], Color32::from_gray(u8::MAX)), [1.0, 1.0])); let mut fixture = Fixture::new(move |ui| { let room = ui.available_rect_before_wrap(); let view = CanvasView::new(room, pt(100.0, 100.0), 1.0).rotation(rotation); @@ -224,7 +225,7 @@ fn a_style_plan_stays_within_its_budget_at_screen_size_and_refuses_hostile_boxes fn a_monitor_conversion_changes_only_the_shown_upload() { let ctx = egui::Context::default(); let raw = solid([2, 2], Color32::from_rgb(140, 89, 51)); - let textures = PreviewTextures::new("monitor", PreviewPixels::new(raw.clone(), [1.0, 1.0])); + let textures = PreviewTextures::new(&mut Serials::default(), "monitor", PreviewPixels::new(raw.clone(), [1.0, 1.0])); // The trial stands in for the renderer: it takes the texture deltas it reads and applies none. let uploaded = |id: egui::TextureId| { let mut delta = ctx.tex_manager().write().take_delta(); @@ -316,7 +317,7 @@ fn frame(textures: &PreviewTextures, quad: [Point; 4], zoom: f32) -> StyledFrame } fn styled_textures() -> PreviewTextures { - PreviewTextures::new("styled", PreviewPixels::new(solid([4, 4], Color32::from_rgb(200, 100, 50)), [1.0, 1.0])) + PreviewTextures::new(&mut Serials::default(), "styled", PreviewPixels::new(solid([4, 4], Color32::from_rgb(200, 100, 50)), [1.0, 1.0])) } fn context() -> (Fixture, egui::Context) { @@ -424,7 +425,7 @@ struct Mips { } fn white(name: &str) -> Rc { - Rc::new(PreviewTextures::new(name, PreviewPixels::new(solid([5, 3], Color32::WHITE), [1.0, 1.0]))) + Rc::new(PreviewTextures::new(&mut Serials::default(), name, PreviewPixels::new(solid([5, 3], Color32::WHITE), [1.0, 1.0]))) } impl Mips { @@ -597,11 +598,12 @@ fn a_new_preview_under_the_same_name_shows_its_own_pixels() { delta.clear(); texel }; - let first = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::WHITE), [1.0, 1.0])); + let mut serials = Serials::default(); + let first = PreviewTextures::new(&mut serials, "same", PreviewPixels::new(solid([2, 2], Color32::WHITE), [1.0, 1.0])); let (id, _) = first.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded"); assert_eq!(uploaded(id), Some(Color32::WHITE)); drop(first); - let second = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::BLACK), [1.0, 1.0])); + let second = PreviewTextures::new(&mut serials, "same", PreviewPixels::new(solid([2, 2], Color32::BLACK), [1.0, 1.0])); let (id, _) = second.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded"); assert_eq!(uploaded(id), Some(Color32::BLACK), "the new pixels go up"); } diff --git a/crates/layers/src/ui/panel/body/rows.rs b/crates/layers/src/ui/panel/body/rows.rs index 74e144b32..8709aba62 100644 --- a/crates/layers/src/ui/panel/body/rows.rs +++ b/crates/layers/src/ui/panel/body/rows.rs @@ -31,9 +31,10 @@ pub(in crate::ui::panel) struct DisplayRow { /// What the display order derives from: the tree's tracked revision, the filter and the groups a reveal opens. A /// change of any of them builds the rows again; nothing else does. #[derive(MemoProps)] -pub(in crate::ui::panel) struct RowsKey<'a, Id: MemoProps> { +pub(in crate::ui::panel) struct RowsKey<'a, Id> { pub(in crate::ui::panel) tree: Revision, pub(in crate::ui::panel) filter: &'a LayerFilter, + #[memo_props(hash = "tree ids are plain model ids (LayerTree::Id: PlainData); Hash covers them")] pub(in crate::ui::panel) opened: &'a [Id], } diff --git a/crates/layers/src/ui/tree.rs b/crates/layers/src/ui/tree.rs index d8f10d5cd..61218215d 100644 --- a/crates/layers/src/ui/tree.rs +++ b/crates/layers/src/ui/tree.rs @@ -11,7 +11,7 @@ use std::hash::Hash; use craft_behavior::IconId; use craft_keymap::Mods; use craft_theme::LabelColor; -use craft_ui::contract::{Entry, MemoProps, PlainData, ReorderMove}; +use craft_ui::contract::{Entry, PlainData, ReorderMove}; use craft_ui::list::ThumbTarget; use super::filter::{EffectKind, LayerFilter, SmartSource}; @@ -22,6 +22,9 @@ use super::panel::MenuTarget; /// the panel derives from the tree. /// /// ```ignore +/// #[derive(Clone, PartialEq, Eq, Hash, Debug, PlainData)] +/// struct LayerId(u64); +/// /// #[derive(PlainData)] /// struct PhotoLayers { layers: LayerIndex, open: HashSet } /// impl LayerTree for PhotoLayers { @@ -36,9 +39,12 @@ use super::panel::MenuTarget; /// [`children`](Self::children) and [`is_open`](Self::is_open) are walked to build the display order, and only when the /// tracked revision, the filter or a reveal's opens changed. pub trait LayerTree: PlainData { - /// The app's layer id: the key of a row, of its thumbnails and of every event. It feeds the memo key of the - /// display order when a reveal opens groups. - type Id: Clone + Eq + Hash + Debug + Send + Sync + MemoProps + 'static; + /// The app's layer id: the key of a row, of its thumbnails and of every event. It is plain model data + /// (`#[derive(PlainData)]`), so the panel keys it by its `Hash`, including in the memo key of the display order + /// when a reveal opens groups. Its `Hash` must tell distinct ids apart (as `#[memo_props(hash)]` requires): + /// two unequal ids that feed the same bytes would share a cached display order. Derived `Hash` on an integer or a + /// tuple of integers does. + type Id: Clone + Eq + Hash + Debug + Send + Sync + PlainData + 'static; /// Children of `parent` (`None`: the top level), topmost first. The app leaves out what the /// panel never shows: layers outside an Isolate Layers set, a Type Mask session's working text. diff --git a/crates/theme/src/lib.rs b/crates/theme/src/lib.rs index 1064277b1..766015568 100644 --- a/crates/theme/src/lib.rs +++ b/crates/theme/src/lib.rs @@ -97,10 +97,10 @@ pub use theme::{ pub use token_group::{GroupValues, TokenGroup}; pub use tokens::{ AccentColors, BarSizes, CaptionColors, ColorToken, ColorTokens, ControlSizes, DataColors, DialogSizes, DockColumnSizes, Edge, EdgeColors, - ElevationTokens, FloatSizes, FontSlot, Gaps, HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, LineColors, Motion, MotionTokens, - OverlayColors, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, RampSizes, RowSizes, ShapeTokens, SizeTokens, SpaceTokens, StateColors, Status, - StatusColors, StatusKind, StrokeTokens, SurfaceColors, TextColors, ThumbSamples, ThumbSizes, Tokens, TypeRole, TypeStyle, TypeTokens, WellShape, - WindowSizes, + ElevationTokens, FloatSizes, FontSlot, Gaps, HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, LetterCase, LineColors, Motion, + MotionTokens, OverlayColors, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, RampSizes, RowSizes, ShapeTokens, SizeTokens, SpaceTokens, + StateColors, Status, StatusColors, StatusKind, StrokeTokens, SurfaceColors, TextColors, ThumbSamples, ThumbSizes, Tokens, TypeRole, TypeStyle, + TypeTokens, WellShape, WindowSizes, }; pub use values::ColorSource; pub use variant::{CustomVariant, Emphasis, RadiusStep, Variant, VariantLook}; diff --git a/crates/theme/src/tokens/type_motion.rs b/crates/theme/src/tokens/type_motion.rs index c83a5f79a..c03244af8 100644 --- a/crates/theme/src/tokens/type_motion.rs +++ b/crates/theme/src/tokens/type_motion.rs @@ -30,6 +30,8 @@ pub struct TypeStyle { pub enum TypeRole { /// Small print, badges. Caption, + /// A heading over a group of fields or cards: the caption's size and font, set in capitals. + SectionCaption, /// Control labels. Label, /// Body text. @@ -48,6 +50,26 @@ pub enum TypeRole { Display, } +/// How a type role sets its letters. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum LetterCase { + /// As written. + #[default] + AsWritten, + /// In capitals; the stored text stays as written. + Upper, +} + +impl TypeRole { + /// How the role sets its letters. + pub fn letter_case(self) -> LetterCase { + match self { + TypeRole::SectionCaption => LetterCase::Upper, + _ => LetterCase::AsWritten, + } + } +} + /// Every type role. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct TypeTokens { @@ -75,7 +97,7 @@ impl TypeTokens { /// The style of `role`. pub fn get(&self, role: TypeRole) -> TypeStyle { match role { - TypeRole::Caption => self.caption, + TypeRole::Caption | TypeRole::SectionCaption => self.caption, TypeRole::Label => self.label, TypeRole::Body => self.body, TypeRole::BodyStrong => self.body_strong, diff --git a/crates/ui-canvas/src/canvas_controls/brush/mod.rs b/crates/ui-canvas/src/canvas_controls/brush/mod.rs index a71511bc2..02b2588b3 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/mod.rs @@ -30,6 +30,8 @@ pub(crate) mod source_marker; pub(crate) mod stories; mod tip; pub(crate) mod trail; +#[cfg(feature = "testing")] +pub(crate) mod trials; pub use cursor::{BrushCursor, BrushCursorOptions, PaintingCursor, TipCell, TipCellStyle}; pub use falloff::{FalloffPreview, FalloffPreviewStyle, TipFalloff}; diff --git a/crates/ui-canvas/src/canvas_controls/brush/stories.rs b/crates/ui-canvas/src/canvas_controls/brush/stories.rs index 36eaaac89..d2071371a 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/stories.rs @@ -11,7 +11,7 @@ use crate::canvas::testing::tool_story::{StoryHost, ToolScript, ToolStory, tool_ use crate::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; use crate::canvas_controls::CanvasControlWords; use crate::contract::Show as _; -use crate::primitives::Draw; +use crate::primitives::{Draw, Serials}; use crate::runtime::env::Env; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; @@ -56,8 +56,8 @@ fn hard_tip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { } /// A drag-shaped mask whose stroke runs at height `y`. -fn stamped(y: f64) -> CoverageMask { - let mut mask = CoverageMask::new(DocRect::new(40.0, 60.0, 160.0, 140.0), 256); +fn stamped(serials: &mut Serials, y: f64) -> CoverageMask { + let mut mask = CoverageMask::new(serials, DocRect::new(40.0, 60.0, 160.0, 140.0), 256); mask.begin_stroke(); mask.stamp_capsule(Point::new(60.0, y), Point::new(100.0, y + 6.0), 5.0); mask.stamp_capsule(Point::new(100.0, y + 6.0), Point::new(140.0, y - 4.0), 5.0); @@ -66,7 +66,8 @@ fn stamped(y: f64) -> CoverageMask { /// The footprint of one tone. The mask is kept across passes (stamped once), so the trail uploads only what changed. fn footprint_of(ui: &mut Ui, data: &mut StoryData, label: &'static str, tone: TrailTone, y: f64) -> StoryOutput { - let mask = data.note::>("footprint", None).get_or_insert_with(|| stamped(y)); + let (serials, mask) = data.note::<(Serials, Option)>("footprint", (Serials::default(), None)); + let mask = mask.get_or_insert_with(|| stamped(serials, y)); on_canvas_view(ui, brush_view, Some(&StoryDocument::STANDARD), |ui, rect, _| StrokeTrail::new(label, mask).tone(tone).show_at(ui, rect)) } diff --git a/crates/ui-canvas/src/canvas_controls/brush/trail.rs b/crates/ui-canvas/src/canvas_controls/brush/trail.rs index d4998e710..6055625bf 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/trail.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/trail.rs @@ -2,26 +2,23 @@ use crate::canvas::canvas_space; use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role}; -use crate::primitives::{Revision, TextureState, TextureStore, TextureStoreOptions}; +use crate::primitives::{Revision, Serials, TextureState, TextureStore, TextureStoreOptions}; use crate::runtime::env::Label; use crate::style::{ComponentStyle, StyleColor, StyleCx}; use craft_behavior::kurbo::{Point, Rect}; use craft_behavior::{Input, Metrics}; use egui::epaint::{Mesh, Vertex}; use egui::{Color32, ColorImage, Response, Shape, pos2}; -use std::sync::atomic::{AtomicU64, Ordering}; /// The share of the tone's colour a full-coverage texel shows; the texture holds coverage only. const LIGHT_SHARE: f32 = 0.25; const SHADE_SHARE: f32 = 0.5; const DANGER_SHARE: f32 = 0.45; -/// The texture store's salt: one store for every trail of the context, keyed by the mask's id. +/// The texture store's salt: one store for every trail of the context, keyed by the trail's component id and the +/// mask's serial (serials are unique per owner, not per context). const STORE_SALT: &str = "canvas_controls.stroke_trail"; -/// Hands out the ids that keep two masks' textures apart. -static NEXT_ID: AtomicU64 = AtomicU64::new(1); - /// A coverage raster over a document rect: one byte per texel, `scale` document units wide, stamped by the tool as the /// stroke grows and uploaded by [`StrokeTrail`] by its changed rows. #[derive(Debug)] @@ -58,8 +55,9 @@ fn byte(coverage: f32) -> u8 { } impl CoverageMask { - /// A mask over `bounds` with no side longer than `max_side` texels. - pub fn new(bounds: Rect, max_side: u32) -> Self { + /// A mask over `bounds` with no side longer than `max_side` texels. Its texture's key comes from `serials`, which + /// the masks of one owner share. + pub fn new(serials: &mut Serials, bounds: Rect, max_side: u32) -> Self { let bounds = bounds.abs(); let finite = [bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()); let bounds = if finite { bounds } else { Rect::ZERO }; @@ -68,16 +66,7 @@ impl CoverageMask { let extent = |side: f64| (side / scale).ceil().max(1.0) as u32; let size = (extent(bounds.width()), extent(bounds.height())); let len = size.0 as usize * size.1 as usize; - CoverageMask { - bounds, - scale, - size, - texels: vec![0; len], - base: vec![0; len], - dirty: None, - revision: 0, - id: NEXT_ID.fetch_add(1, Ordering::Relaxed), - } + CoverageMask { bounds, scale, size, texels: vec![0; len], base: vec![0; len], dirty: None, revision: 0, id: serials.mint() } } /// Stamps the capsule from `from` to `to` (document units) of radius `radius`, keeping the larger coverage. @@ -270,8 +259,8 @@ impl Component for StrokeTrail<'_> { } let painter = ui.content_painter(cx); let ctx = painter.painter.ctx(); - let store = TextureStore::::in_context(ctx, STORE_SALT, TextureStoreOptions::frames()); - let (key, revision) = (self.mask.id, Revision::new(self.mask.revision)); + let store = TextureStore::<(egui::Id, u64)>::in_context(ctx, STORE_SALT, TextureStoreOptions::frames()); + let (key, revision) = ((cx.id, self.mask.id), Revision::new(self.mask.revision)); // A second paint of the pass finds the entry at this revision and nothing dirty. let texture = match store.state(ctx, &key, revision) { TextureState::Ready(texture) => texture, diff --git a/crates/ui-canvas/src/canvas_controls/brush/trials.rs b/crates/ui-canvas/src/canvas_controls/brush/trials.rs new file mode 100644 index 000000000..6727e6e70 --- /dev/null +++ b/crates/ui-canvas/src/canvas_controls/brush/trials.rs @@ -0,0 +1,48 @@ +//! Trials of the stroke trail's texture keys. +#![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")] + +use super::{CoverageMask, StrokeTrail}; +use crate::canvas::testing::canvas_story::{on_canvas_view, story_view}; +use crate::contract::Show as _; +use crate::primitives::Serials; +use crate::testing::{Frames, trial}; +use craft_behavior::kurbo::{Point, Rect as DocRect}; +use egui::{Shape, Ui}; + +fn stamped(serials: &mut Serials) -> CoverageMask { + let mut mask = CoverageMask::new(serials, DocRect::new(40.0, 60.0, 160.0, 140.0), 256); + mask.stamp_capsule(Point::new(60.0, 100.0), Point::new(140.0, 100.0), 5.0); + mask +} + +/// Two owners each count from one: their masks have the same serial and revision, and the trials they show at once +/// still upload a texture each. +#[trial] +fn two_owners_masks_with_one_serial_show_two_textures() { + let (mut first, mut second) = (stamped(&mut Serials::default()), stamped(&mut Serials::default())); + let mut frames = Frames::new(); + let mut ui = |ui: &mut Ui| { + for (name, mask) in [("Trail A", &mut first), ("Trail B", &mut second)] { + crate::testing::memory::scoped_by(ui, name, |ui| { + on_canvas_view( + ui, + |room, scale| story_view(room, scale, Point::new(100.0, 100.0), 1.0), + None, + |ui, rect, _| StrokeTrail::new(name, mask).show_at(ui, rect), + ); + }); + } + }; + frames.idle(3, &mut ui); + let shapes = frames.frame_shapes(&mut ui); + let mut textures: Vec<_> = shapes + .iter() + .filter_map(|shape| match shape { + Shape::Mesh(mesh) => Some(mesh.texture_id), + _ => None, + }) + .collect(); + textures.sort_by_key(|id| format!("{id:?}")); + textures.dedup(); + assert_eq!(textures.len(), 2, "two trials with one serial each show their own texture: {textures:?}"); +} diff --git a/crates/ui-canvas/src/canvas_controls/outline/hover.rs b/crates/ui-canvas/src/canvas_controls/outline/hover.rs index fac1fb985..0c8d1b93e 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/hover.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/hover.rs @@ -1,8 +1,8 @@ //! `HoverMask`: an object's coverage, reduced for the hover tint. +use crate::primitives::Serials; use craft_behavior::kurbo::Rect; use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; /// An object's coverage reduced for the hover tint: at most [`HoverMask::MAX_TEXELS`] texels on its long side, /// sampled once when the mask is made. Cheap to clone (the texels are shared) and `Send + Sync`, so a lookup job can @@ -16,7 +16,7 @@ pub struct HoverMask { size: [usize; 2], /// Coverage 0..=255 per texel, row by row. coverage: Arc<[u8]>, - /// Unique per mask made, for the texture store. + /// Unique per mask made by one `Serials`, for the texture store. generation: u64, } @@ -35,9 +35,8 @@ impl HoverMask { /// corner of each texel's cell, with one texel per document unit until the long side passes /// [`MAX_TEXELS`](Self::MAX_TEXELS), then `ceil(long side / 768)` units per texel. Coverage outside 0..=1 is /// clamped; one that is not finite reads as 0. Empty or non-finite `bounds` give a 1 × 1 mask with no coverage. - pub fn sampled(bounds: Rect, coverage: impl Fn(f64, f64) -> f32) -> HoverMask { - static GENERATIONS: AtomicU64 = AtomicU64::new(0); - let generation = GENERATIONS.fetch_add(1, Ordering::Relaxed); + pub fn sampled(serials: &mut Serials, bounds: Rect, coverage: impl Fn(f64, f64) -> f32) -> HoverMask { + let generation = serials.mint(); let finite = bounds.x0.is_finite() && bounds.y0.is_finite() && bounds.x1.is_finite() && bounds.y1.is_finite(); if !finite || bounds.width() <= 0.0 || bounds.height() <= 0.0 { return HoverMask { bounds, size: [1, 1], coverage: Arc::from(vec![0u8]), generation }; diff --git a/crates/ui-canvas/src/canvas_controls/outline/mod.rs b/crates/ui-canvas/src/canvas_controls/outline/mod.rs index a0a71e84c..c5a13fc07 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/mod.rs @@ -179,10 +179,10 @@ fn tint(mask: &HoverMask, color: Color32) -> ColorImage { ColorImage::new([width, height], pixels) } -fn paint_mask(painter: &ContentPainterCx<'_>, view: &CanvasView, mask: &HoverMask, color: Color32) { +fn paint_mask(painter: &ContentPainterCx<'_>, id: egui::Id, view: &CanvasView, mask: &HoverMask, color: Color32) { let ctx = painter.painter.ctx(); - let store = TextureStore::::in_context(ctx, "canvas_controls.hover_mask", TextureStoreOptions::frames()); - let texture = store.get_or_put(ctx, mask.generation(), Revision::of(&color.to_array()), || tint(mask, color)); + let store = TextureStore::<(egui::Id, u64)>::in_context(ctx, "canvas_controls.hover_mask", TextureStoreOptions::frames()); + let texture = store.get_or_put(ctx, (id, mask.generation()), Revision::of(&color.to_array()), || tint(mask, color)); let uvs = [pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]; let mut mesh = Mesh::with_texture(texture.sized().id); for (pos, uv) in view.quad(mask.bounds()).into_iter().zip(uvs) { @@ -250,7 +250,7 @@ impl Component for HoverOutline { stroke_run(&painter, points, closed, self.color, style.medium); } } - HoverShape::Mask(mask) => paint_mask(&painter, &view, mask, self.color.map_or(style.line.egui(), |color| color.0)), + HoverShape::Mask(mask) => paint_mask(&painter, cx.id, &view, mask, self.color.map_or(style.line.egui(), |color| color.0)), } } diff --git a/crates/ui-canvas/src/canvas_controls/outline/stories.rs b/crates/ui-canvas/src/canvas_controls/outline/stories.rs index 8019fbb83..f52ac4ecd 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/stories.rs @@ -4,6 +4,7 @@ use super::{HoverMask, HoverOutline, HoverShape, SelectionOutline}; use crate::canvas::RasterSource as _; use crate::canvas::testing::canvas_story::{StoryDocument, StoryPicture, StoryShape, accent, on_canvas, on_picture, paint_shapes}; use crate::contract::Show as _; +use crate::primitives::Serials; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::kurbo::{self, BezPath, Circle, Point, Rect, Shape as _}; use egui::{Color32, Ui}; @@ -36,8 +37,9 @@ fn rollover(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { } #[story(HoverOutline, covers = [Default], drive = Drive::Never)] -fn coverage_tint(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - let mask = HoverMask::sampled(bounds(), |x, y| if DISC.contains(Point::new(x, y)) { 1.0 } else { 0.0 }); +fn coverage_tint(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let disc = |x, y| if DISC.contains(Point::new(x, y)) { 1.0 } else { 0.0 }; + let mask = HoverMask::sampled(data.note("serials", Serials::default()), bounds(), disc); let picture = objects(ui, &DISC); on_picture(ui, &picture, |ui, at, _| HoverOutline::new("Object", Some(HoverShape::Mask(mask.clone()))).show_at(ui, at)) } diff --git a/crates/ui-canvas/src/canvas_controls/task_bar.rs b/crates/ui-canvas/src/canvas_controls/task_bar.rs index d76711327..1e45fbeb6 100644 --- a/crates/ui-canvas/src/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/src/canvas_controls/task_bar.rs @@ -20,7 +20,7 @@ use crate::runtime::overlay::CloseReason; use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; use craft_behavior::kurbo::Point; use craft_behavior::overlay::{Align, Side}; -use craft_behavior::{EditEvent, IconId, Metrics, Mixed, Sense}; +use craft_behavior::{EditEvent, GesturePhase, IconId, Metrics, Mixed, Sense}; use egui::{Pos2, Rect, Response, Ui}; use std::sync::Arc; @@ -245,8 +245,7 @@ impl<'a> TaskBar<'a> { let rect = shown.output.response.rect; let pick = menu.pick; if shows && kind == TaskBarKind::Task { - let moved = shown.output.moved.filter(|moved| moved.min != rect.min); - let next = settled(held, rect, area, moved, pick); + let next = settled(held, rect, area, shown.output.moved, pick); if next != held { let word = match pick { Some(MenuPick::Reset) => &words.task_bar_reset, @@ -303,8 +302,8 @@ fn layer_overlay(held: &TaskBarPlace, hang: Option, area: Rect, side: Side } } -/// The place after a pass that showed the bar at `shown`. A move (`moved`, a rect other than `shown`) keeps the bar -/// where it was dropped; Reset clears the place; Pin, and a pinned bar with no place, keep the bar at `shown`. A +/// The place after a pass that showed the bar at `shown`. A move that ended (`moved`, where it was dropped) keeps the +/// bar there; Reset clears the place; Pin, and a pinned bar with no place, keep the bar at `shown`. A /// non-finite place is cleared. With no move and no pick, the place stays unchanged; the overlay host keeps the layer /// inside the area. fn settled(held: TaskBarPlace, shown: Rect, area: Rect, moved: Option, pick: Option) -> TaskBarPlace { @@ -333,7 +332,7 @@ pub struct TaskBarLayerStyle { metrics: Metrics, } -/// What the task bar's layer reports: its response, the last move of this pass and why it closed. +/// What the task bar's layer reports: its response, the move that ended in this pass and why it closed. #[derive(Debug)] struct TaskBarLayerOutput { response: Response, @@ -361,6 +360,8 @@ struct TaskBarLayer { props: ContainerProps, /// Open while the bar shows; the caller shows the bar again each pass it wants it. open: Bind<'static, bool>, + /// Where a move by the grip ended in this pass. The layer host shows the bar under the pointer while the move + /// runs, so the place is written once, on the drop. moved: Option, /// Why the layer closed, once it has. closed: Option, @@ -411,7 +412,7 @@ impl Container for TaskBarLayer { } fn placement_changed(&mut self, change: &PlacementChange) { - if change.kind == PlacementKind::Move { + if change.kind == PlacementKind::Move && change.phase == GesturePhase::Commit { self.moved = Some(change.rect); } } diff --git a/crates/ui-canvas/tests/it/canvas_controls/brush.rs b/crates/ui-canvas/tests/it/canvas_controls/brush.rs index 2ea1284ec..c0d0026b9 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/brush.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/brush.rs @@ -2,10 +2,11 @@ use craft_behavior::kurbo::{Point, Rect}; use craft_ui::canvas_controls::brush::CoverageMask; +use craft_ui::primitives::Serials; use craft_ui::testing::trial; fn mask() -> CoverageMask { - CoverageMask::new(Rect::new(0.0, 0.0, 100.0, 100.0), 100) + CoverageMask::new(&mut Serials::default(), Rect::new(0.0, 0.0, 100.0, 100.0), 100) } #[trial] @@ -44,7 +45,7 @@ fn a_restamp_keeps_earlier_strokes_and_stays_inside_its_rect() { #[trial] fn a_thin_stamp_on_a_large_document_still_shows() { - let mut mask = CoverageMask::new(Rect::new(0.0, 0.0, 20_000.0, 20_000.0), 1000); + let mut mask = CoverageMask::new(&mut Serials::default(), Rect::new(0.0, 0.0, 20_000.0, 20_000.0), 1000); assert_eq!((mask.scale(), mask.size()), (20.0, (1000, 1000))); // A one-unit line on a texel's edge, away from every texel centre. mask.restamp(Rect::new(5000.0, 5000.0, 5200.0, 5020.0), |at| if (at.y - 5000.5).abs() <= 0.5 { 1.0 } else { 0.0 }); diff --git a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs index 0fa97a336..417e2ab86 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs @@ -6,6 +6,7 @@ use craft_ui::buttons::Button; use craft_ui::canvas_controls::{TaskBar, TaskBarDismiss, TaskBarPlace}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::testing::canvas_story::on_canvas; +use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Fixture, trial}; use egui::{Rect, Vec2}; use std::cell::RefCell; @@ -272,3 +273,39 @@ fn the_grip_sits_on_the_members_line() { let dropped = seen(&scene); assert!((dropped.rect.min - (bar.min + by)).length() < 2.0 * SLACK, "a drag on the grip moves the bar: {:?}", dropped.rect); } + +/// A drag of the grip moves the bar under the pointer in the frame of each step, in one pass, and writes its place +/// once, on the drop: one edit for the whole move. +#[trial] +fn a_dragged_task_bar_stands_under_the_pointer_in_each_frame_and_writes_its_place_on_the_drop() { + let scene = Rc::new(RefCell::new(Scene { + anchor: frame(DocVec::ZERO), + place: TaskBarPlace::default(), + bounds: Rect::NOTHING, + area: Rect::NOTHING, + rect: Rect::NOTHING, + })); + let mut fixture = fixture(&scene); + fixture.settle(); + let start = seen(&scene).rect; + let from = fixture.by_label("Move bar").expect("the grip is named").center(); + fixture.frame(vec![moved(from)]); + fixture.frame(vec![press(from)]); + let step = Vec2::new(-30.0, 15.0); + for n in 1..=4 { + let to = start.min + step * n as f32; + fixture.frame(vec![moved(from + step * n as f32)]); + let now = seen(&scene); + assert!((now.rect.min - to).length() < SLACK, "step {n}: the bar stands under the pointer in its frame: {:?}, wanted {to:?}", now.rect); + assert_eq!(fixture.passes(), 1, "step {n}: the frame runs one pass"); + assert_eq!(now.place, TaskBarPlace::default(), "step {n}: the place is not written while the drag runs"); + } + let dropped_at = start.min + step * 4.0; + fixture.frame(vec![release(from + step * 4.0)]); + let dropped = seen(&scene); + assert!((dropped.rect.min - dropped_at).length() < SLACK, "the bar stays where it was dropped: {:?}", dropped.rect); + let at = dropped.place.at.map(|at| dropped.area.min + Vec2::from(at)); + assert!(at.is_some_and(|at| (at - dropped_at).length() < SLACK), "the drop writes the place: {:?}", dropped.place); + fixture.settle(); + assert!((seen(&scene).rect.min - dropped_at).length() < SLACK, "the written place keeps the bar there: {:?}", seen(&scene).rect); +} diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index 6533a5127..e03be55cb 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -166,6 +166,9 @@ pub(super) struct BodyHooks<'b> { /// The container is a row of a vertical flow, not a member of a row's line (`label::in_column`), as its parent /// flow showed it this run: its own measuring run shows its content in a flow of its own. in_column: bool, + /// The line just before the container in its flow is a rule (`layout::flow_start`), as its parent flow showed it + /// this run: a rule above its header is not drawn, so two rules never follow each other. + after_rule: bool, /// A bottom-anchored region is following the end of its content. follows_end: bool, } @@ -242,6 +245,7 @@ impl<'b> BodyHooks<'b> { held: false, across: false, in_column: true, + after_rule: false, follows_end: false, } } diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index dce04dbb3..05d3101e8 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -5,7 +5,7 @@ use super::open::open_now; use super::placement::{Placement, measure_layer, overlay_of, shown_placement}; use super::regions::{ LabelColumns, LabelsFound, RegionFrame, RegionSizes, Regions, RuleBands, end_full_height, footer_in_body, footer_in_end, footer_rule_under, - gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line, + gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_bracket, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line, }; use super::reorder::REORDER_BAND; use super::scroll::{ @@ -68,7 +68,9 @@ impl ShapeHooks for BodyHooks<'_> { } fn host(&mut self, comp: &C, at: crate::contract::run::HostCx<'_>) -> Box { - let mounted = crate::contract::mount::host(comp.props(Internal::new()), &at, self.open, at.label); + let props = comp.props(Internal::new()); + let moving = overlay_of(props).filter(|overlay| overlay.movable).and_then(|_| self.mode.running_move(at.ui.ctx(), at.id)); + let mounted = crate::contract::mount::host(props, &at, self.open, at.label, moving); if mounted.exiting { self.exiting = true; self.open = true; @@ -157,7 +159,8 @@ impl ShapeHooks for BodyHooks<'_> { self.region_gap = gap_of(&env.tokens, Gap::Tight); self.end_gap = gap_of(&env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); self.header_gap = header_gap_of(props, &env.tokens); - self.rules = RuleBands::of(props, &env.tokens, crate::runtime::egui::scale::pixels_per_point(&ctx)); + self.after_rule = layout::flow_start(&ctx, env) == Some(true); + self.rules = RuleBands::of(props, &env.tokens, crate::runtime::egui::scale::pixels_per_point(&ctx), self.after_rule); self.least_width = least_of(&env.tokens, props.least_width); let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx); if !matches!(props.mount, Mount::Inline | Mount::Pane(_)) @@ -185,7 +188,7 @@ impl ShapeHooks for BodyHooks<'_> { Mount::Layer(_) | Mount::Viewport { .. } => { let placement = overlay_of(props).map_or_else(Placement::default, |overlay| { let screen = crate::contract::overlay::screen_for(&ctx, env, overlay); - shown_placement(&ctx, id, save.as_ref(), overlay, screen, env.tokens.space.inset.screen) + shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, env.tokens.space.inset.screen) }); // A layer the user sized takes that size, at its saved position or where its anchor places it. placement.size.is_some() @@ -1305,12 +1308,12 @@ impl BodyHooks<'_> { && env.values.get::() == label::LabelScheme::Inspector; let (room, content_column, scroll, beside, label_width) = (plan.room, plan.content_column, plan.scroll, plan.regions.beside, plan.label_extra.x); - let first_body = plan.first.1; + let (first_body, layout_id) = (plan.first.1, plan.layout_id); // The slot of a footer the body places takes the size the measuring run's footer took. let footer_slot = footer_in_body(props) .then(|| FooterSlotOf { owner: id, size: if real { self.measured_footer } else { self.footer_size.unwrap_or(Vec2::ZERO) } }); plan.body_env = Some(plan.line_env.derive_local(|scoped| { - self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside }); + self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside, layout: layout_id }); scoped.inside_label = inside.map(|inside| inside as crate::runtime::env::Held); scoped.cell_fills = cell_fills; if footer_slot.is_some() { @@ -1569,6 +1572,12 @@ impl BodyHooks<'_> { /// size counts the label column. fn after_body(&mut self, ui: &mut Ui, env: &Env, plan: &mut BodyPlan<'_>) { let (props, ctx, real) = (plan.props, &plan.ctx, plan.real); + if let Some(bracket) = props.bracket { + let took = layout::take_bracket(ctx, plan.layout_id); + if let (true, crate::contract::Bracket::Linked, Some(took)) = (real, bracket, took) { + paint_bracket(ui, env, &took, plan.rtl); + } + } // A measuring run decided the label before the control reported its minimum width: it decides again // from the minimum this run recorded, so the extent it measures is the one the real run lays out. if let (false, Some(input)) = (real, plan.label_input.as_mut()) { @@ -1580,6 +1589,12 @@ impl BodyHooks<'_> { plan.label_extra = label_extra_of(plan.regions.body, plan.body_rect, plan.label_rect, plan.rtl); } if let Some(size) = &mut self.body_size { + // A labelled row of a bracketed row reports where its control lies: the bracket runs from it. + if let (Some(row), Some(_)) = (env.bracket, props.label.as_ref()) { + let body = plan.body_rect; + let left = if plan.rtl { body.max.x - size.x } else { body.min.x }; + layout::report_bracket_control(ctx, row, Rect::from_min_size(egui::pos2(left, body.min.y), *size), plan.rtl); + } let label_extra = plan.label_extra; // A body beside its label in a content-sized column of rows reports how far it reaches past the label // column, so that column's container measures its rows at the widest label. @@ -1801,7 +1816,8 @@ impl BodyHooks<'_> { self.region_gap = gap_of(&at.env.tokens, Gap::Tight); self.end_gap = gap_of(&at.env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); self.header_gap = header_gap_of(&props, &at.env.tokens); - self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx())); + self.after_rule = layout::flow_start(at.ui.ctx(), at.env) == Some(true); + self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx()), self.after_rule); self.least_width = least_of(&at.env.tokens, props.least_width); self.room = match at.width { Some(width) => Vec2::new(width, props.room_height.unwrap_or(f32::INFINITY)), diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 660e5ebc8..8669cc8f0 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -19,6 +19,8 @@ pub(super) struct BodyScope { pub(super) label_width: f32, /// The width the regions beside the body take on its line (`Regions::beside`). pub(super) beside: f32, + /// The id the body's layout runs under (`BodyPlan::layout_id`). + pub(super) layout: Id, } /// The surface a container paints under its regions: its props' surface, else its style's in its current state. @@ -96,10 +98,23 @@ impl BodyHooks<'_> { /// What the body inherits on top of the line's env: arena, transform, the room it is offered and its scroll axes. pub(super) fn scope_body(&self, scoped: &mut Scoped, props: &ContainerProps, id: Id, body: BodyScope) { - let BodyScope { room, real, content_column, scroll, label_width, beside } = body; + let BodyScope { room, real, content_column, scroll, label_width, beside, layout } = body; if props.arena { scoped.arena = Some(ArenaId::new(id)); } + // The body's flow starts after a rule when the container draws one under its header, or when the container + // draws nothing of its own (no header, surface or mount) and itself started after a rule. + scoped.after_rule = props.header.is_some_and(|header| header.rule && !header.inline) + || (props.header.is_none() && props.surface.is_none() && props.mount == Mount::Inline && self.after_rule); + scoped.flow_body = None; + scoped.column_row = + self.in_column && matches!(props.layout, crate::layout::BodyLayout::Row { wrap: false, align: crate::layout::RowAlign::Start }); + // A bracketed row's rows report to it up to the first labelled container, whose body is its own control. + if props.bracket.is_some() { + scoped.bracket = Some(layout); + } else if props.label.is_some() { + scoped.bracket = None; + } scoped.transform = props.transform; scoped.content_column = content_column; scoped.given_column = !content_column && matches!(props.layout, crate::layout::BodyLayout::Stack); diff --git a/crates/ui-contract/src/contract/body/placement.rs b/crates/ui-contract/src/contract/body/placement.rs index 4f885be80..311fe446b 100644 --- a/crates/ui-contract/src/contract/body/placement.rs +++ b/crates/ui-contract/src/contract/body/placement.rs @@ -28,8 +28,7 @@ impl Placement { /// The placement the caller of `overlay` gives, when it places the layer. fn given(overlay: &crate::contract::Overlay) -> Option { - let kept = |rect: Rect| overlay.bounds.map_or(rect, |bounds| super::window::keep_inside(rect, bounds)); - overlay.placed.map(|rect| Placement::at(kept(rect))).or_else(|| overlay.placed_at.map(Placement::at_pos)) + overlay.placed.map(|rect| Placement::at(super::window::kept_in(rect, overlay.bounds))).or_else(|| overlay.placed_at.map(Placement::at_pos)) } /// The rect it names, taking the position and size it lacks from `rect`. @@ -46,7 +45,9 @@ pub(crate) fn placement_id(id: Id) -> Id { /// is `placed` has the caller's rect instead: the slot reads it and writes nothing, since the caller owns the /// placement and learns of the user's changes from `PlacementChange` reports. A layer hung from its anchor keeps only /// its size, whether or not the user can move it: each opening places it from its anchor at that size, and a caller -/// that keeps a moved layer where it was dropped places it (`placed_at`) from the change it was told of. +/// that keeps a moved layer where it was dropped places it (`placed_at`) from the change it was told of. While the +/// user drags the move band, the layer host shows the layer at the drag's rect whatever the slot holds +/// ([`shown_placement`]), so a caller places it from the drag's `Commit` alone. pub(super) struct PlacementSlot<'s> { stage: &'s mut MemoryStage, id: Id, @@ -96,7 +97,28 @@ fn placement_of(ctx: &Context, id: Id, save: Option<&SaveKey>) -> Placement { /// floating resizable layer with a default size (`Overlay::size`) that size, within the screen less `screen_inset` on /// each side, centred or at the overlay's float position. A saved size and position win over the default. A size with /// no position places an anchored layer from its anchor at that size. +/// +/// While a drag of the layer's move band runs, `moving` is the rect it puts the layer at in this pass +/// (`WindowMode::running_move`): the layer shows there, within its bounds, at the size the placement gives. The +/// caller's place, the stored one or the anchor applies again once the drag ends. pub(crate) fn shown_placement( + ctx: &Context, + id: Id, + save: Option<&SaveKey>, + overlay: &crate::contract::Overlay, + moving: Option, + screen: Rect, + screen_inset: f32, +) -> Placement { + let mut placement = resting_placement(ctx, id, save, overlay, screen, screen_inset); + if let Some(moving) = moving { + placement.pos = Some(super::window::kept_in(moving, overlay.bounds).min.into()); + } + placement +} + +/// The placement a layer is shown at while no drag moves it ([`shown_placement`]). +fn resting_placement( ctx: &Context, id: Id, save: Option<&SaveKey>, diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 24c1ff5c3..6383347dd 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -11,7 +11,7 @@ use crate::runtime::egui::{alloc, child, style}; use crate::runtime::env::{Env, RowLine}; use crate::runtime::memory::sub; use crate::runtime::overlay::CloseReason; -use crate::style::{RuleKind, UiTokens, rule_look}; +use crate::style::{RuleKind, RuleLook, RuleWidth, UiTokens, rule_look}; use egui::{Align, Id, Layout, Pos2, Rect, Ui, UiBuilder, Vec2}; /// The slots of a container's own header parts at the edges of the header's line (`Container::header_parts`). @@ -84,12 +84,13 @@ pub(super) struct RuleBands { } impl RuleBands { - /// The bands of `props`' rules in `tokens` on a display of `pixels_per_point`. - pub(super) fn of(props: &ContainerProps, tokens: &UiTokens, pixels_per_point: f32) -> Self { + /// The bands of `props`' rules in `tokens` on a display of `pixels_per_point`. A rule above separates the + /// container from what precedes it in flow: right after a rule (`after_rule`) there is none. + pub(super) fn of(props: &ContainerProps, tokens: &UiTokens, pixels_per_point: f32, after_rule: bool) -> Self { let width = rule_look(tokens, RuleKind::Divider).width.points(pixels_per_point); let on = |rule: bool| if rule { width } else { 0.0 }; RuleBands { - above: on(props.header.is_some_and(|header| header.rule_above)), + above: on(!after_rule && props.header.is_some_and(|header| header.rule_above)), under: on(props.header.is_some_and(|header| header.rule && !header.inline)), footer: on(props.footer.is_some_and(|footer| footer.rule)), end: on(props.end.is_some_and(|end| end.rule)), @@ -217,6 +218,30 @@ pub(super) fn paint_rules(ui: &mut Ui, env: &Env, regions: &Regions) { } } +/// The bracket of a linked `Row` (`Bracket::Linked`) from what its rows reported in `took`: a tick from the end of the +/// first and the last row's controls, `space.gap.tight` past them, to the middle child's centre line, and a stroke +/// along that line from each tick to the middle child's edge. `text.muted`, `stroke.thin` wide. +pub(super) fn paint_bracket(ui: &mut Ui, env: &Env, took: &crate::layout::BracketTook, rtl: bool) { + let (Some(first), Some(last), Some(end), Some(middle)) = (took.first, took.last, took.end, took.middle) else { return }; + if last <= first { + return; + } + let tokens = &env.tokens; + let tight = tokens.tokens().space.gap.tight; + let look = RuleLook { color: crate::style::rgba_color(tokens.color.text.muted), width: RuleWidth::Points(tokens.stroke.thin) }; + let ppp = ui.ctx().pixels_per_point(); + let (start, line) = if rtl { (-end - tight, middle.center().x) } else { (end + tight, middle.center().x) }; + let painter = ui.painter(); + for (from, to) in [ + (Pos2::new(start, first), Pos2::new(line, first)), + (Pos2::new(start, last), Pos2::new(line, last)), + (Pos2::new(line, first), Pos2::new(line, middle.top().max(first))), + (Pos2::new(line, middle.bottom().min(last)), Pos2::new(line, last)), + ] { + painter.extend(Rule::shapes(&look, from, to, ppp)); + } +} + impl BodyHooks<'_> { /// The footer's rect and how far its left edge lies past the container's, under the control column of a /// label-scoped container; along an axis the room leaves unbounded, the footer follows the body and the end region. @@ -610,7 +635,11 @@ fn own_labels(ui: &mut Ui, id: Id, (room, seed): (f32, Option), foun group.offer(room); body(ui) }); - (found.extent, found.unsettled) = (scoped.extent, scoped.unsettled); + found.extent = scoped.extent; + // A later sweep of the same run may take a row's measure from the earlier sweep without reading the column again + // (a stack's sweep at the width its first sweep found): that measure is still the one taken at the narrower + // column, so the rows run again whenever any sweep found one. + found.unsettled = scoped.unsettled.or(found.unsettled.take()); result } diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index a3fa5d83d..1cb5f02c7 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -29,6 +29,9 @@ pub(super) struct MeasureKey { /// Whether the body shows, and how much of it an animated collapse shows. shows: (bool, f32), env: EnvFacts, + /// Where its parent flow showed the container: as a row of a vertical flow (`label::in_column`), and with a rule + /// just before it (a rule above its header is not drawn). + flow: (bool, bool), } /// The props a body was measured under, compared on the fields its measure reads. @@ -92,6 +95,7 @@ impl<'b> BodyHooks<'b> { width, shows: (self.open, self.presence.t), env: EnvFacts::of(env), + flow: (self.in_column, self.after_rule), } } diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 7976228fe..bc1af97e6 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -124,6 +124,9 @@ pub(super) struct WindowMode { kind: Option, restore: Placement, began: Option, + /// The rect the layer had when a press went down on its move band or a grip, until the press ends: a drag that + /// starts from the press runs from it. + pressed: 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 @@ -136,6 +139,23 @@ impl WindowMode { pub(super) fn held(&self) -> Option { self.held } + + /// The rect a drag of the move band of the layer `id` puts the layer at in this pass, before the bounds keep it: + /// the rect the layer had when the press went down, moved by the pointer's travel since. `window_drag` reports the + /// same rect for the step. `None` while no move by the band runs. The layer host shows the layer there + /// (`shown_placement`) before the container's pass runs, so the layer stands under the pointer in the frame of + /// each step, whoever owns its placement. + pub(super) fn running_move(&self, ctx: &Context, id: Id) -> Option { + if self.pressed.is_none() && self.began.is_none() { + return None; + } + let (began, start, pos) = match crate::primitives::sensing::part_press(ctx, id, MOVE_BAND.into()).press.phase { + PressPhase::DragStart { start, pos, .. } => (self.pressed?, start, pos), + PressPhase::Drag { start, pos, .. } | PressPhase::Release { start, pos, .. } => (self.began?, start, pos), + _ => return None, + }; + Some(began.translate(pos - start.origin)) + } } /// A move of a viewport mount's OS window that the app runs (`Overlay::moved_by_app`), from its Begin to its Commit @@ -200,6 +220,11 @@ pub(crate) fn keep_inside(rect: Rect, bounds: Rect) -> Rect { rect.translate(Vec2::new(keep(rect.min.x, rect.max.x, bounds.min.x, bounds.max.x), keep(rect.min.y, rect.max.y, bounds.min.y, bounds.max.y))) } +/// `rect` kept inside `bounds`, when the layer has bounds. +pub(super) fn kept_in(rect: Rect, bounds: Option) -> Rect { + bounds.map_or(rect, |bounds| keep_inside(rect, bounds)) +} + /// What every change of a layer's rect keeps to: the least and most size, and the rect it stays inside. struct Limits { min: Vec2, @@ -214,8 +239,7 @@ impl Limits { /// `rect` moved by `delta`, kept inside the bounds. fn moved(&self, rect: Rect, delta: Vec2) -> Rect { - let rect = rect.translate(delta); - self.bounds.map_or(rect, |bounds| keep_inside(rect, bounds)) + kept_in(rect.translate(delta), self.bounds) } /// `rect` with the edges `dx` and `dy` (-1: low edge, 1: high edge, 0: none) moved by `delta`, within the size @@ -377,14 +401,7 @@ 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, - sizing: None, - held: None, - }; + mode = WindowMode { kind: Some(kind), restore: current.clone(), began: Some(current.rect_over(rect)), ..WindowMode::default() }; self.reports.push(step(current.rect_over(rect), GesturePhase::Begin)); } } @@ -436,7 +453,8 @@ impl BodyHooks<'_> { } /// A drag of the move band or a grip of a layer (not an OS window): the layer follows the pointer within the - /// limits, and each step is reported. Escape, which cancels the press, restores the placement from before. + /// limits, and each step is reported. The drag runs from the rect the layer had when the press went down. Escape, + /// which cancels the press, restores the placement from before. pub(super) fn window_drag(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) { let Some(overlay) = overlay_of(props) else { return }; // A band that moves the window below starts the OS move of the window the layer is shown in. @@ -455,9 +473,11 @@ impl BodyHooks<'_> { let mut pressed = vec![(None, phase((MOVE_BAND, None)))]; pressed.extend((0..GRIPS.len()).map(|index| (Some(index), phase((GRIP, Some(index as u64)))))); let Some((grip, phase)) = pressed.into_iter().find_map(|(grip, phase)| match phase? { - phase @ (PressPhase::DragStart { .. } | PressPhase::Drag { .. } | PressPhase::Release { .. } | PressPhase::Cancel { .. }) => { - Some((grip, phase)) - } + phase @ (PressPhase::Down { .. } + | PressPhase::DragStart { .. } + | PressPhase::Drag { .. } + | PressPhase::Release { .. } + | PressPhase::Cancel { .. }) => Some((grip, phase)), _ => None, }) else { return; @@ -465,8 +485,14 @@ impl BodyHooks<'_> { let mut slot = PlacementSlot::new(&mut *cx.core.memory, id, self.save.as_ref(), overlay); let current = slot.read(); let (origin, pos, gesture) = match phase { + PressPhase::Down { .. } => { + self.mode.pressed = Some(current.rect_over(rect)); + return; + } PressPhase::DragStart { start, pos, .. } => { - self.mode.began = Some(current.rect_over(rect)); + // The layer host shows this pass at the step's rect already (`running_move`): the drag runs from where + // the layer stood at the press. + self.mode.began = Some(self.mode.pressed.unwrap_or_else(|| current.rect_over(rect))); self.mode.restore = current.clone(); self.mode.held = grip; (start.origin, Some(pos), GesturePhase::Begin) @@ -476,6 +502,9 @@ impl BodyHooks<'_> { PressPhase::Cancel { start, .. } => (start.origin, None, GesturePhase::Cancel), _ => return, }; + if matches!(gesture, GesturePhase::Commit | GesturePhase::Cancel) { + self.mode.pressed = None; + } let Some(began) = self.mode.began else { return }; let (dx, dy, _) = grip.map_or((0, 0, CursorIcon::Grab), |index| GRIPS[index]); let kind = if grip.is_some() { PlacementKind::Size(edge_of(dx, dy)) } else { PlacementKind::Move }; diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 9a89d45c2..13a48e3c9 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -727,6 +727,19 @@ impl EnvValue for InMenu { } } +/// The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and +/// height to their chain): a tick from each of the first and the last row's controls to the middle child's centre +/// line, joined along that line. The middle child sits halfway between the two controls. The value is the link's +/// state. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Bracket { + /// The rows are linked: the bracket is drawn. + Linked, + /// The rows are not linked: the middle child keeps its place, with no bracket. + Unlinked, +} + /// What a container or collection adds to `Common`. A builder added here is added to the forwarder list in /// `crates/ui-macros/src/props.rs` too. /// @@ -824,6 +837,9 @@ pub struct ContainerProps { pub label_column: bool, /// How the labelled rows under the container show their labels; `None` keeps the scheme of the scope. pub labels: Option, + /// The bracket an unwrapped `Row` placed from its start draws from its first child's labelled rows to the child + /// after them; any other body draws none. + pub bracket: Option, /// The component whose memory holds the container's shown memory and its layer's bookkeeping, when it is another: /// the body of a popup an `overlay` hook shows belongs to the component that shows it. pub(crate) owner: Option, @@ -865,6 +881,7 @@ impl ContainerProps { && self.outer_edit == other.outer_edit && self.collection_body == other.collection_body && self.labels == other.labels + && self.bracket == other.bracket } /// Props with every field at its default. @@ -907,6 +924,7 @@ impl ContainerProps { collection_body: false, label_column: false, labels: None, + bracket: None, owner: None, } } @@ -1134,6 +1152,12 @@ impl ContainerProps { self } + /// The bracket of a `Row` from its first child's labelled rows to the child after them ([`bracket`](Self::bracket)). + pub const fn bracket(mut self, bracket: Bracket) -> Self { + self.bracket = Some(bracket); + self + } + /// The labelled rows under the container show their labels in `scheme`: its regions, its body and every container /// inside, until one sets a scheme of its own. pub const fn labels(mut self, scheme: LabelScheme) -> Self { diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index e49a5c280..b2c5f1b18 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -116,6 +116,8 @@ impl LeafPlaced { pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option>) -> LeafPlaced { let scope = sub(at.id, "field"); let enabled = at.under.enabled; + // Read before the child measures: nothing it does there may count as a child placed in flow. + let in_column = in_column(ui); let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x; let input = LabelIn { scope, @@ -131,7 +133,7 @@ pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: & size: at.under.size, control_min, leaf: true, - in_column: in_column(ui), + in_column, claims: C::LABELLED_AFTER, status: false, trailing: trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size), @@ -227,9 +229,15 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option< placed } -/// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line. +/// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line. The first child of an +/// unwrapped row that is itself a row of a vertical flow (`Scoped::column_row`) starts where that flow's rows start, +/// so it counts as one of them: a check box that starts a row of a form lines up with the form's controls. pub(crate) fn in_column(flow: &Ui) -> bool { - !flow.layout().is_horizontal() + if !flow.layout().is_horizontal() { + return true; + } + let env = Env::of(flow); + env.column_row && crate::layout::at_flow_start(flow.ctx(), &env) } /// A control with its label after it that the label step moved into the control column (its `control` starts past diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index d0db84761..bb9ec4da3 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -176,6 +176,7 @@ impl Lazy { if memo { place_view(ui, rect); } else { + crate::layout::close_flow_start_in(ui); alloc::advance_past(ui, rect); } if view.is_some() || memo { @@ -268,6 +269,7 @@ fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 { /// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`. fn place_view(ui: &mut Ui, rect: Rect) -> Rect { if take_cell(ui, rect.size()).is_none() { + crate::layout::close_flow_start_in(ui); alloc::advance_past(ui, rect); } rect diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 75f800d74..7b44688d6 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -68,8 +68,9 @@ pub use container::InBar; #[doc(hidden)] pub use container::InMenu; pub use container::{ - BandFill, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, LeastWidth, - Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth, + BandFill, Bracket, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, + LeastWidth, Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, + WrapWidth, }; pub use craft_tracked::{PlainData, Revision, Tracked}; pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract}; diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index eb8b2635c..e56a51a47 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -26,7 +26,8 @@ pub(super) struct Mounted { } /// The host for `props.mount`. A layer-like mount of a closed container shows nothing once its exit fade ended. -pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label) -> Mounted { +/// `moving` is the rect a running drag of the container's move band puts its layer at in this pass. +pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label, moving: Option) -> Mounted { let ctx = at.ui.ctx(); let layer = |overlay: &Overlay| { let presence = if at.ui.is_sizing_pass() { @@ -46,7 +47,7 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: & Mount::Pane(pane) => Mounted { host: Box::new(PaneHost(*pane)), exiting: false }, Mount::Window { .. } => Mounted { host: Box::new(WindowContentHost), exiting: false }, Mount::Layer(overlay) => match layer(overlay) { - (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size)), exiting }, + (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size, moving)), exiting }, (None, _) => closed(), }, Mount::FullWindow => full_window(props.focus), @@ -57,7 +58,9 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: & full_window(fallback.focus) } else if !viewports { match layer(fallback) { - (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size)), exiting }, + (Some(fade), exiting) => { + Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size, moving)), exiting } + } (None, _) => closed(), } } else if open { @@ -196,12 +199,14 @@ struct LayerHost { fade: f32, /// The size the container measured for this pass. size: Vec2, + /// The rect a running drag of the move band puts the layer at in this pass, in screen space. + moving: Option, dismissed: Option, } impl LayerHost { - fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2) -> Self { - LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, dismissed: None } + fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2, moving: Option) -> Self { + LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, moving, dismissed: None } } } @@ -227,7 +232,7 @@ impl Host for LayerHost { overlay = mapped; } let screen = overlay::screen_for(&ctx, env, &overlay); - let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, screen, env.tokens.space.inset.screen); + let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, self.moving, screen, env.tokens.space.inset.screen); // An anchored resizable layer has no position to seed: its default size is held as its minimum until the // user resizes it. if overlay.fit == overlay::OverlayFit::Resizable diff --git a/crates/ui-contract/src/contract/overlay.rs b/crates/ui-contract/src/contract/overlay.rs index 7622c5596..215f7a0e7 100644 --- a/crates/ui-contract/src/contract/overlay.rs +++ b/crates/ui-contract/src/contract/overlay.rs @@ -23,7 +23,7 @@ pub(crate) use host::{Layer, forget_layer, host, host_window}; pub(crate) use opener::{LayerFloor, anchor_floor}; pub use opener::{Opener, Trigger}; pub use place::{Anchor, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare}; -pub use placement::PopupRegion; +pub use placement::{PopupRegion, layer_room}; pub(crate) use placement::{measuring_room, region_for, resolve_anchor, screen_for}; pub(crate) use popups::dwell; pub use popups::{HOLD, Overlays, PopupHandle}; diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index b6790cd12..8ce555ead 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -73,6 +73,27 @@ pub(super) fn dismissal( None } +/// The dismissal of a layer shown in the popup window `popup`, decided in its opener's pass, beside what the popup's +/// own pass decides: a layer that closes on outside presses closes on one in the opener outside it and its anchor +/// (absorbed or not, as its rule says), and on one in any other window of the app; a popup also closes once the app +/// has no focus. An absorbing layer can't keep a press in another OS window from reaching that window. +pub(super) fn popup_dismissal( + ctx: &Context, + layer: &Layer<'_>, + rect: Rect, + anchor: Rect, + popup: egui::ViewportId, + appears: bool, +) -> Option { + let here = match layer.overlay.dismiss.outside { + Outside::Keep => return None, + Outside::Absorb => overlay::absorbed_press(ctx).is_some(), + Outside::Close => press_outside(ctx, layer, rect, anchor), + }; + let away = layer.overlay.rank == Rank::Popup && crate::runtime::windows::app_away(ctx); + (here || away || crate::runtime::windows::pressed_elsewhere(ctx, popup, appears)).then_some(CloseReason::Outside) +} + /// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it. fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool { let Some(press) = pointer::frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index 9c2ab20fc..a37aa15b5 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -1,6 +1,6 @@ //! The overlay host: shows a layer on an egui layer, remembers it while shown and closes its family. -use super::dismissal::dismissal; +use super::dismissal::{dismissal, popup_dismissal}; use super::opener::{Opening, Trigger}; use super::place::{OverlayFit, Place}; use super::placement::{anchor_rect, opened_overlay, placement}; @@ -13,6 +13,7 @@ use crate::runtime::layout_memory; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::motion::{self, Driver}; use crate::runtime::overlay::{self, Backdrop, CloseReason, OpenEntry, Rank}; +use crate::runtime::windows::{self, PopupOpen, PopupRoom, WindowSpec}; use craft_behavior::{MotionKind, Playback}; use egui::{Context, Id, Pos2, Rect, Ui, Vec2}; @@ -90,6 +91,7 @@ pub(crate) fn forget_layer(ctx: &Context, id: Id, owner: Id) { if taken.is_some_and(|memory| !memory.family_closed) { overlay::close_descendants(ctx, id); } + windows::close_popup(ctx, id); } /// Asks the layers opened from inside `layer` to close once the layer closes or starts to fade out, in the pass that @@ -106,8 +108,14 @@ fn area_id(id: Id) -> Id { sub(id, "area") } -/// The overlay host: shows `body` on an egui layer for `layer` and decides its dismissal. +/// The overlay host: shows `body` on an egui layer for `layer` and decides its dismissal. A layer opened in a palette +/// window shows in a popup window of its own ([`host_in_popup`]); a full-window layer covers its own window. pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut Ui)) -> LayerOut { + if !layer.overlay.is_full_window() + && let Some(popup) = windows::popup_room(ctx) + { + return host_in_popup(ctx, layer, popup, body); + } // A layer that appears starts with nothing it remembered while shown before, also when it opens again during its // exit fade or its host never saw it hide: the focus that was inside it does not close it as `focus_left`. let appears = overlay::appears(ctx, layer.id, layer.exiting); @@ -248,6 +256,143 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U LayerOut { dismissed } } +/// A layer opened in a palette window, shown in a popup window of its own (`WindowSpec::popup`): placed in the +/// opener's points within the work area around it, the window at that place in desktop points. +/// +/// The layer's bookkeeping is split between the two windows. The popup's pass shows the layer at the window's origin +/// and records it in the popup's stack, with its focus scope and the dismissal its own input decides (Escape, Enter, +/// activations, focus, timeout). The opener's pass records an entry that stands for the window (`OpenEntry::popup`), +/// so its family, its anchor and the presses in the opener are judged where they happen; a press in any other window +/// of the app, and for a popup the app losing focus, close it too ([`popup_dismissal`]). +/// +/// A layer whose size its container measured is placed before the window opens. A layer without one (a tooltip) is +/// laid out in the popup's pass first, in the room its unplaced form has, and placed by the size it took there. +/// A popup that takes keys (a menu, a flyout) takes the OS focus; a tooltip takes none and lets the pointer through. +fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut dyn FnMut(&mut Ui)) -> LayerOut { + let appears = overlay::appears(ctx, layer.id, layer.exiting); + let mut memory = if appears { LayerMemory::default() } else { recall(layer, ctx) }; + let opened = opened_overlay(ctx, layer.overlay, memory.opening); + if let Some((_, opening)) = &opened { + memory.opening.get_or_insert(*opening); + } + // The popup window lies outside any region of the opener: the work area is its room. + let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), region: None, ..*layer }; + let overlay = layer.overlay; + let bounds = popup.room; + let anchor = anchor_rect(ctx, layer, bounds, &mut memory); + let min_width = overlay.least_width(anchor.width()); + let measured = layer.size.map(|size| egui::vec2(size.x.max(min_width), size.y)); + let unplaced = placement(ctx, layer, measured, bounds, anchor); + let parent = overlay::drawing_parent(ctx); + let tier = overlay::layer_tier(ctx, overlay.rank); + let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); + if overlay.rank.is_modal() && appears { + overlay::close_popups_outside(ctx, &[layer.id]); + } + // The body reports in its parent's space: the popup's points are the opener's screen less the layer's place. + let to_parent = overlay::parent_space(ctx, layer.id); + let tooltip = overlay.rank == Rank::Tooltip; + let spec = WindowSpec::popup().takes_focus(!tooltip && (scope.is_some() || overlay.rank.takes_keys())).passes_pointer(tooltip); + let known = measured.map(|size| Rect::from_min_size(unplaced.at, size)); + let open = PopupOpen { id: layer.id, spec: &spec, rect: known.map(|rect| rect.translate(popup.origin.to_vec2())) }; + let mut shown = None; + windows::show_popup(ctx, &open, |ui| { + let at = unplaced.at.to_vec2(); + overlay::note_parent_space(ui.ctx(), layer.id, egui::emath::TSTransform::from_translation(-at) * to_parent); + shown = Some(show_in_popup(ui, layer, &unplaced, min_width, scope, &mut memory, &mut *body)); + }); + let (size, dismissed) = shown.unwrap_or((measured.unwrap_or_default(), None)); + let placed = if known.is_some() { unplaced } else { placement(ctx, layer, Some(size), bounds, anchor) }; + let rect = Rect::from_min_size(placed.at, size); + if known.is_none() { + windows::place_popup(ctx, layer.id, rect.translate(popup.origin.to_vec2())); + } + let mut entry = OpenEntry::new(layer.id, overlay.rank, overlay.keys, rect, areas::layer_of(tier, area_id(layer.id))); + entry.parent = parent; + entry.anchor = matches!(overlay.place, Place::Anchored { .. }).then_some(anchor); + entry.side = placed.side; + entry.exiting = layer.exiting; + entry.scoped = scope.is_some(); + entry.absorbs = overlay.dismiss.outside == Outside::Absorb; + entry.window = true; + entry.popup = true; + overlay::record(ctx, entry); + let viewport = crate::runtime::egui::viewports::viewport_id(layer.id); + let dismissed = if layer.exiting { None } else { dismissed.or_else(|| popup_dismissal(ctx, layer, rect, anchor, viewport, appears)) }; + close_family(ctx, layer, layer.exiting || dismissed.is_some(), &mut memory); + remember(layer, ctx, memory); + LayerOut { dismissed } +} + +/// The popup window's pass of [`host_in_popup`]: the layer at the window's origin, offered the room `placed` leaves, +/// its entry in the popup's stack and the dismissal the popup's own input decides. Returns the size the layer took +/// and that dismissal. +fn show_in_popup( + ui: &mut Ui, + layer: &Layer<'_>, + placed: &super::placement::Placed, + min_width: f32, + scope: Option, + memory: &mut LayerMemory, + body: &mut dyn FnMut(&mut Ui), +) -> (Vec2, Option) { + let ctx = ui.ctx().clone(); + let overlay = layer.overlay; + let window = ctx.content_rect(); + let area = area_id(layer.id); + let tier = overlay::layer_tier(&ctx, overlay.rank); + let cover = match overlay.rank { + Rank::Modal { backdrop } => { + let scrim = match backdrop { + Backdrop::Scrim => crate::style::scrim_color(&layer.env.tokens).gamma_multiply(layer.fade), + Backdrop::None => egui::Color32::TRANSPARENT, + }; + let cover_id = sub(layer.id, "cover"); + let through = crate::runtime::sampler::through(&ctx, crate::runtime::egui::pass::current_viewport(&ctx), layer.id); + areas::show_cover_layer(&ctx, areas::CoverLayer { id: cover_id, tier, screen: window, scrim, through, absorbs: !layer.exiting }); + Some(areas::layer_of(tier, cover_id)) + } + _ => None, + }; + // The layer's content starts from its opener's env, on the popup window's own root: its scale and window facts. + let opener = layer.env.capture().env(); + let env = Env::root_of(&ctx).map_or_else(|| opener.clone(), |root| opener.rebase(&root)); + let spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting }; + overlay::begin_layer(&ctx, layer.id, tier, layer.exiting, placed.side); + let shown = areas::show_layer(&ctx, &spec, |ui| { + areas::fade(ui, layer.fade * overlay.opacity); + let installed = Env::install_for(ui, env.clone()); + let real = !ui.is_sizing_pass(); + if real && (layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. })) { + access::report_layer(&ctx, layer.id, ui.unique_id(), ui.max_rect(), overlay.rank.is_modal(), layer.exiting); + } + // The focused stop the scope returns to is in the opener's window; the opener's window takes the OS focus + // back when the popup closes (`windows::close_popup`). + if real { + let entering = !std::mem::replace(&mut memory.scope_entered, true); + focus::push_scope_from(&ctx, layer.id, overlay.focus, None, None, layer.exiting, Some(entering)); + } + areas::bound(ui, placed.room, min_width.min(placed.room.x)); + if overlay.fit == OverlayFit::Resizable { + ui.set_min_size(overlay.size_limits.min.min(placed.room)); + } + access::scope::outside(&ctx, || layout_memory::boundary(&ctx, true, || body(ui))); + if real { + focus::pop_scope(&ctx); + } + Env::restore(&ctx, installed); + }); + overlay::end_layer(&ctx); + let mut entry = OpenEntry::new(layer.id, overlay.rank, overlay.keys, shown.rect, shown.layer); + entry.side = placed.side; + entry.exiting = layer.exiting; + entry.cover = cover; + entry.scoped = scope.is_some(); + overlay::record(&ctx, entry); + let dismissed = if layer.exiting { None } else { dismissal(&ctx, layer, shown.rect, Rect::NOTHING, scope, memory) }; + (shown.rect.size(), dismissed) +} + /// The motion slot of a layer's nudge, under the layer's id. // PLAN: the decision names a `NUDGE_SPEC`; `MotionSpec::new` (`runtime/motion.rs:39`) is a private `const fn` of a file outside this set, so // the nudge runs on `spec::OPEN_FADE` (a fade, which reduced motion still runs) over the open token's duration. diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index c4100569e..526a2fdda 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -82,10 +82,16 @@ pub(crate) fn region_for(env: &Env, overlay: &Overlay) -> Option { } } -/// The screen rect a layer of `overlay` opened in `env` keeps inside: the safe rect, or the part of it a contained -/// layer's region leaves. +/// The room a layer opened in the running viewport may take, in its points: the work area around a palette window, +/// whose layers show in popup windows of their own (`windows::popup_room`), else the window's safe rect. +pub fn layer_room(ctx: &Context) -> Rect { + crate::runtime::windows::popup_room(ctx).map_or_else(|| areas::safe_rect(ctx), |popup| popup.room) +} + +/// The screen rect a layer of `overlay` opened in `env` keeps inside: the layer room ([`layer_room`]), or the part +/// of it a contained layer's region leaves. pub(crate) fn screen_for(ctx: &Context, env: &Env, overlay: &Overlay) -> Rect { - let safe = areas::safe_rect(ctx); + let safe = layer_room(ctx); region_for(env, overlay).map_or(safe, |region| region.intersect(safe)) } diff --git a/crates/ui-contract/src/contract/overlay/ui.rs b/crates/ui-contract/src/contract/overlay/ui.rs index 34728c9f3..4f428911d 100644 --- a/crates/ui-contract/src/contract/overlay/ui.rs +++ b/crates/ui-contract/src/contract/overlay/ui.rs @@ -76,10 +76,10 @@ impl<'a> OverlayUi<'a> { } /// Keeps the popups this component shows from here on, and every popup opened from them, below the component: - /// inside the safe rect less the part above the component's bottom edge. A menu bar's menus and their submenus + /// inside the layer room less the part above the component's bottom edge. A menu bar's menus and their submenus /// never cover the bar. pub fn contain_popups_below(&mut self) { - let safe = areas::safe_rect(self.ctx); + let safe = super::layer_room(self.ctx); let top = (self.to_screen * self.anchor).bottom().clamp(safe.top(), safe.bottom()); let region = Rect::from_min_max(egui::pos2(safe.left(), top), safe.max); self.env = self.env.derive(|scoped| { diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index f7e3aab2d..f495e805f 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1609,8 +1609,11 @@ fn extent_step( let (ctx, facts, shape, sizing, id) = (&begun.ctx, &begun.facts, begun.shape, begun.sizing, begun.id); let env = begun.env(); // A body root with parts steps its press machine before its measuring run, so the body reads this pass's part - // presses in both runs (`BodyCx::part_press`). Step 8 finds the outcome. A member of another arena senses at step 8. - if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && (t.arena() || facts.text() || env.arena.is_none()) { + // presses in both runs (`BodyCx::part_press`) and its host reads them before it places the body. Step 8 finds the + // outcome. A member of another arena senses at step 8. A root its host shows on a layer of its own (not in flow) + // senses in its own arena: its steps 6 to 16 run in the layer's env, which is outside its opener's arena. + let own_arena = t.arena() || facts.text() || env.arena.is_none() || !t.in_flow(); + if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && own_arena { sensing::sense_early(ctx, id, resolved.enabled); } let scx = steps::style_cx(ctx, &begun.env, &begun.step1); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index 0be4e115f..956401601 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -546,6 +546,7 @@ pub(crate) fn show_container_taking( body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R, ) -> Inner { let shown = show_container(slot, ui, ShowAt::Rect(rect), body, None); + crate::layout::close_flow_start_in(ui); crate::runtime::egui::alloc::advance_past(ui, rect); shown } diff --git a/crates/ui-contract/src/layout/arrange.rs b/crates/ui-contract/src/layout/arrange.rs index de37411f3..8a6b9b170 100644 --- a/crates/ui-contract/src/layout/arrange.rs +++ b/crates/ui-contract/src/layout/arrange.rs @@ -71,6 +71,7 @@ pub fn arrange(ui: &mut Ui, layout: &dyn Arrangement, children: &mut [Placed<'_> placed.response = Some(placed.child.show_at(ui, *id, flow.to_physical(*rect))); } let whole = flow.to_physical(Rect::from_min_size(room.min, taken)); + super::close_flow_start_in(ui); alloc::advance_past(ui, whole); whole } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 91b569bc7..2daf30757 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -212,6 +212,79 @@ fn report_first_line(ctx: &egui::Context, target: Id, at: Option) { }); } +/// The bodies whose flow has placed nothing yet in the sweep or run under way, by body id, each with whether a rule +/// precedes the body's start (`Scoped::after_rule`). +#[derive(Default)] +pub(crate) struct FlowStarts(IdMap); + +/// Where the next child placed in flow under `env` starts: `Some(edge)` while the body that places it has placed +/// nothing yet in this sweep or run, with `after_rule` when a rule precedes that body's start (`Scoped::after_rule`); +/// `None` once a child took room there, and outside a body. +pub(crate) fn flow_start(ctx: &egui::Context, env: &Env) -> Option { + let body = env.flow_body?; + pass_state::with::(ctx, |starts| starts.0.get(&body).copied()) +} + +/// Whether the next child placed in flow under `env` starts its body's flow (`flow_start`). +pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool { + flow_start(ctx, env).is_some() +} + +/// A child took room in the flow of the body that places the children under `env`: its flow start closes. +pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) { + if let Some(body) = env.flow_body { + pass_state::with::(ctx, |starts| starts.0.remove(&body)); + } +} + +/// `close_flow_start` for a child placed in the flow of `ui` outside `place_in_cell` and `take_in_flow`. +pub(crate) fn close_flow_start_in(ui: &Ui) { + close_flow_start(ui.ctx(), &Env::of(ui)); +} + +/// What the labelled rows of a bracketed `Row` (`ContainerProps::bracket`) reported of their controls in the sweep or +/// run under way, and the rect of the row's last child in flow, by the row's layout id. +#[derive(Default)] +pub(crate) struct Brackets(IdMap); + +/// The controls of a bracket's rows and the child after them. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct BracketTook { + /// The centre line of the first row's control. + pub(crate) first: Option, + /// The centre line of the last row's control. + pub(crate) last: Option, + /// How far the rows' controls reach toward the row's end edge, at most: right, or left under right-to-left. + pub(crate) end: Option, + /// The rect of the row's last child placed in flow: the control in the bracket's middle. + pub(crate) middle: Option, +} + +impl BracketTook { + /// The centre line between the first and the last row's controls, once two rows reported. + pub(crate) fn centre(&self) -> Option { + self.first.zip(self.last).filter(|(first, last)| last > first).map(|(first, last)| (first + last) / 2.0) + } +} + +/// Reports the `control` rect of a labelled row to the bracketed row `row`, its end edge `rtl`-aware. +pub(crate) fn report_bracket_control(ctx: &egui::Context, row: Id, control: Rect, rtl: bool) { + pass_state::with::(ctx, |brackets| { + if let Some(took) = brackets.0.get_mut(&row) { + let centre = control.center().y; + took.first.get_or_insert(centre); + took.last = Some(centre); + let end = if rtl { -control.min.x } else { control.max.x }; + took.end = Some(took.end.map_or(end, |was: f32| was.max(end))); + } + }); +} + +/// What the rows of the bracketed row `row` reported in the run that just ended; `None` outside a bracketed row. +pub(crate) fn take_bracket(ctx: &egui::Context, row: Id) -> Option { + pass_state::with::(ctx, |brackets| brackets.0.remove(&row)) +} + /// How a child that fills the main axis of the body it sits in sizes along it. enum MainFill { /// The body is being measured: the child takes no room along the axis and is counted. @@ -1151,9 +1224,16 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { let env = Env::of(ui); let (line, target) = (env.row_line.filter(|line| line.places), env.first_line); let child = InFlow { first: if child.line { child.first } else { one_line(child.first, size.y) }, ..child }; - let above = line.and_then(|line| line.centre).zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); + // A one-line child of a bracketed row sits with its centre on the bracket's middle, between the controls its + // rows reported before it. + let bracket = line.filter(|line| env.bracket == Some(line.body)).and_then(|line| { + let took = pass_state::with::(ui.ctx(), |brackets| brackets.0.get(&line.body).copied())?; + Some((line.body, took.centre().map(|centre| centre - ui.available_rect_before_wrap().top()))) + }); + let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre)); + let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); let slot = Vec2::new(size.x, line.and_then(|line| line.height).map_or(above + size.y, |height| height.max(above + size.y))); - let (rect, in_cell) = take_in(ui, env.grid, slot); + let (rect, in_cell) = take_in(ui, &env, slot); let placed = if child.fill && in_cell { rect } else { @@ -1166,6 +1246,9 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { }; Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below)) }; + if let Some((row, _)) = bracket { + pass_state::with::(ui.ctx(), |brackets| brackets.0.get_mut(&row).map(|took| took.middle = Some(placed))); + } if measure::active(ui.ctx()) { if let Some(line) = line { pass_state::with::(ui.ctx(), |rows| { @@ -1184,7 +1267,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { /// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the /// next allocation of `ui`'s layout. Returns the rect taken and whether it is a cell. pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { - take_in(ui, Env::of(ui).grid, size) + take_in(ui, &Env::of(ui), size) } /// Leaves the next cell of the `Grid` body that encloses `ui` directly empty: the next child takes the cell after it. @@ -1194,13 +1277,15 @@ pub fn empty_cell(ui: &mut Ui) { let env = Env::of(ui); let grid = env.grid.filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); if grid.is_some() { - take_in(ui, grid, Vec2::ZERO); + take_in(ui, &env, Vec2::ZERO); } } -/// `take_in_flow`, with `grid` the body of `ui`'s env that places its children itself. -fn take_in(ui: &mut Ui, grid: Option, size: Vec2) -> (Rect, bool) { - match cell_in(ui, grid, size) { +/// `take_in_flow` under `env`, `ui`'s env: the next cell of its grid, else the next allocation; the body's flow start +/// closes. +fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { + close_flow_start(ui.ctx(), env); + match cell_in(ui, env.grid, size) { Some(cell) => (cell, true), None => (alloc::space(ui, size), false), } @@ -1209,7 +1294,12 @@ fn take_in(ui: &mut Ui, grid: Option, size: Vec2) -> (Rect, bool) { /// Takes the next cell of the `Grid` or spread `Row` body that encloses `ui` directly for a child of `size`, and returns /// it; `None`, taking nothing, outside such a body. pub(crate) fn take_cell(ui: &mut Ui, size: Vec2) -> Option { - cell_in(ui, Env::of(ui).grid, size) + let env = Env::of(ui); + let cell = cell_in(ui, env.grid, size); + if cell.is_some() { + close_flow_start(ui.ctx(), &env); + } + cell } fn cell_in(ui: &mut Ui, grid: Option, size: Vec2) -> Option { @@ -1360,6 +1450,7 @@ fn run_grid( scoped.derive_local(|scoped| { scoped.grid = Some(id); scoped.grid_top = cells == CellAlign::Top; + scoped.flow_body = Some(id); }), ); let (inner, unsettled) = ColumnGroup::grid(ui, id, count, seed, &mut body); @@ -1651,8 +1742,14 @@ pub(crate) fn run_body_measured( // Each sweep of a measuring run finds the body's first line and an unwrapped row's line afresh. let target = env.first_line.filter(|_| sizing); let row = (sizing && matches!(layout, BodyLayout::Row { wrap: false, .. })).then_some(id); + // Each sweep and the real run start the body's flow, and a bracketed row's reports, afresh. + let (after_rule, bracket) = (env.after_rule, env.bracket == Some(id)); let body = |ui: &mut Ui| { open_sweep(&ctx, target, row, least); + pass_state::with::(&ctx, |starts| starts.0.insert(id, after_rule)); + if bracket { + pass_state::with::(&ctx, |brackets| brackets.0.insert(id, BracketTook::default())); + } body(ui) }; // Each layout runs in its own function, so a body nested in bodies keeps only its own layout's frame on the stack. @@ -1680,7 +1777,10 @@ struct RowIn { /// A `Stack` body: each leaf shows at most the stack's room, never below its least. fn run_stack(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> R) -> R { let ctx = ui.ctx().clone(); - let env = env.derive_local(|scoped| scoped.shrink = Some(Shrink::Fit)); + let env = env.derive_local(|scoped| { + scoped.shrink = Some(Shrink::Fit); + scoped.flow_body = Some(at.id); + }); let installed = Env::install_for(ui, env.clone()); // A held child of a column whose own room is unbounded keeps the width it measured at. let inner = if env.content_column && flow_room(ui).x.is_finite() { @@ -1705,6 +1805,7 @@ fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m scoped.grid_top = false; scoped.row_line = Some(line); scoped.first_line = None; + scoped.flow_body = Some(id); }), ); let inner = run_spread(ui, id, gap.x, rtl, &mut body); @@ -1728,6 +1829,7 @@ fn run_start_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mu scoped.row_room = Some(room.width()); scoped.row_line = Some(line); scoped.first_line = None; + scoped.flow_body = Some(id); }), ); let inner = run_shrinking(ui, id, &mut body); @@ -1777,6 +1879,7 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign env.derive_local(|scoped| { scoped.row_room = Some(room.width()); scoped.row_line = line; + scoped.flow_body = Some(id); if line.is_some() { scoped.first_line = None; } diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 54fdb32d1..bc6ed6396 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,7 +24,8 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - BodyLine, InFlow, close_first_line, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, grid_cell, - in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_held, report_least, report_shrink, row_alone_room, - run_body_measured, shares_y, shrink_cap, take_cell, take_in_flow, view_room, + BodyLine, BracketTook, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, + flow_region, flow_room, flow_start, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, + report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, + take_cell, take_in_flow, view_room, }; diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index 895da0217..bb5a5056b 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -67,9 +67,9 @@ pub use tool::ToolIcon; #[cfg(feature = "testing")] pub use textures::FakeThumbSource; pub use textures::{ - CachedTexture, LoadFailure, LoadResult, LoadedPicture, LoaderOptions, MAX_TEXTURE, Priority, Revision, TextureBudget, TextureKey, TextureLoader, - TextureState, TextureStatistics, TextureStore, TextureStoreOptions, TextureWords, ThumbFit, ThumbJob, ThumbPaint, ThumbRender, ThumbRequest, - ThumbSource, ThumbnailOptions, Thumbnails, fit_image, fit_rect, reduce_image, texture_factor, texture_side, thumb_image, + CachedTexture, LoadFailure, LoadResult, LoadedPicture, LoaderOptions, MAX_TEXTURE, Priority, Revision, Serials, TextureBudget, TextureKey, + TextureLoader, TextureState, TextureStatistics, TextureStore, TextureStoreOptions, TextureWords, ThumbFit, ThumbJob, ThumbPaint, ThumbRender, + ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, fit_image, fit_rect, reduce_image, texture_factor, texture_side, thumb_image, }; pub(crate) use draw::DataMode; diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 9b36826d8..d09cc6ea9 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -5,7 +5,7 @@ use crate::runtime::egui::memory; use crate::runtime::egui::text_layout; pub use crate::style::Span; use crate::style::text_measure::{paragraph_job, span_format}; -use crate::style::{StyleColor, TypeRole, UiTokens}; +use crate::style::{LetterCase, StyleColor, TypeRole, UiTokens}; use craft_i18n::Direction; use egui::epaint::text::FontCacheRevision; use egui::text::{LayoutJob, TextWrapping}; @@ -118,6 +118,11 @@ impl<'a> TextRun<'a> { /// Sets the type role. pub fn role(mut self, role: TypeRole) -> Self { self.role = role; + if role.letter_case() == LetterCase::Upper { + for span in &mut self.spans { + span.text = Cow::Owned(span.text.to_uppercase()); + } + } self } diff --git a/crates/ui-contract/src/primitives/textures/mod.rs b/crates/ui-contract/src/primitives/textures/mod.rs index faabf4501..df9a52a57 100644 --- a/crates/ui-contract/src/primitives/textures/mod.rs +++ b/crates/ui-contract/src/primitives/textures/mod.rs @@ -8,7 +8,7 @@ mod words; pub use limits::{MAX_TEXTURE, fit_image, reduce_image, texture_factor, texture_side}; pub use loader::{LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, TextureLoader}; -pub use store::{CachedTexture, Revision, TextureBudget, TextureKey, TextureState, TextureStatistics, TextureStore, TextureStoreOptions}; +pub use store::{CachedTexture, Revision, Serials, TextureBudget, TextureKey, TextureState, TextureStatistics, TextureStore, TextureStoreOptions}; pub use words::TextureWords; /// The tint that leaves a texture's own colours as they are: every texel is multiplied by white. diff --git a/crates/ui-contract/src/primitives/textures/store.rs b/crates/ui-contract/src/primitives/textures/store.rs index 35fc6c92f..8144fa8ea 100644 --- a/crates/ui-contract/src/primitives/textures/store.rs +++ b/crates/ui-contract/src/primitives/textures/store.rs @@ -371,6 +371,22 @@ impl Default for Stores { } } +/// The numbers that keep apart the textures one owner makes: a mask or preview made anew gets a number no earlier one +/// of the same `Serials` had, so an entry kept under its key is never taken for the new one's. The owner of what the +/// textures show (a tool's state, a model) holds the `Serials`. The numbers are unique per owner, not per context: a +/// texture store that several owners share keys each entry by the owner's component id as well as the serial. Plain +/// data, so it can sit in tracked or model state. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Serials(u64); + +impl Serials { + /// A new number: never one this `Serials` gave before. + pub fn mint(&mut self) -> u64 { + self.0 += 1; + self.0 + } +} + /// Textures by key and revision, with byte and entry budgets: the one place an app's pictures become egui /// textures. The app never holds a `TextureHandle`. The state lives in runtime memory of the context under the /// salt; the value is a cheap handle that clones share. diff --git a/crates/ui-contract/src/runtime/egui/viewports.rs b/crates/ui-contract/src/runtime/egui/viewports.rs index 65f0231d6..e20acbb1e 100644 --- a/crates/ui-contract/src/runtime/egui/viewports.rs +++ b/crates/ui-contract/src/runtime/egui/viewports.rs @@ -35,8 +35,12 @@ pub(crate) struct Spec<'a> { pub resizable: bool, /// Whether the window has a taskbar or Dock entry. pub taskbar: bool, - /// Whether the window opens hidden; [`show`] reveals it. + /// Whether the window opens hidden; [`set_visible`] reveals it. pub hidden: bool, + /// Whether the window takes OS focus when it opens. + pub active: bool, + /// Whether pointer input passes through the window. + pub passes_pointer: bool, /// The app id the OS window carries (dock icon, Wayland compositor rules); empty carries none. pub app_id: &'a str, } @@ -48,6 +52,12 @@ pub(crate) fn show_immediate(ctx: &Context, id: ViewportId, spec: &Spec<'_>, if spec.hidden { builder = builder.with_visible(false); } + if !spec.active { + builder = builder.with_active(false); + } + if spec.passes_pointer { + builder = builder.with_mouse_passthrough(true); + } if !spec.app_id.is_empty() { builder = builder.with_app_id(spec.app_id); } @@ -74,9 +84,9 @@ pub(crate) fn show_immediate(ctx: &Context, id: ViewportId, spec: &Spec<'_>, ctx.show_viewport_immediate(id, builder, |ui, _| body(ui)) } -/// Makes the hidden viewport `id` visible. -pub(crate) fn show(ctx: &Context, id: ViewportId) { - ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Visible(true)); +/// Shows or hides the window of viewport `id`. +pub(crate) fn set_visible(ctx: &Context, id: ViewportId, visible: bool) { + ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Visible(visible)); } /// The viewport id of the container `id`. @@ -168,6 +178,16 @@ pub(crate) fn raise(ctx: &Context, viewport: ViewportId) { ctx.request_repaint_of(viewport); } +/// Brings `viewport`'s window in front of the app's other windows without giving it focus, by standing it above every +/// window and then back at `level`, its own level. egui-winit ignores `Focus` for a window that has focus, and the +/// window holding a modal usually has it; on Windows the level change also puts the window in front of the ordinary +/// windows that were made ordinary before it. A Wayland compositor gives clients no stacking control. +pub(crate) fn raise_above(ctx: &Context, viewport: ViewportId, level: WindowLevel) { + command(ctx, viewport, ViewportCommand::WindowLevel(WindowLevel::AlwaysOnTop)); + command(ctx, viewport, ViewportCommand::WindowLevel(level)); + ctx.request_repaint_of(viewport); +} + /// Cancels an OS close request of the running viewport so the owner can decide. pub(crate) fn cancel_close(ctx: &Context) { ctx.send_viewport_cmd(ViewportCommand::CancelClose); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 93b2610a5..a37c5dc6b 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -138,6 +138,18 @@ pub struct Scoped { /// Where the first child the scope places in flow reports its first line: a container's header or body /// (`layout::FirstLines`). `None` in the children of a `Row` body, which reports its line itself. pub(crate) first_line: Option, + /// The body whose flow places the scope's direct children: the flow start a child reads (`layout::flow_start`) + /// and the one a child placed in flow closes. + pub(crate) flow_body: Option, + /// A rule precedes the start of the body this scope opens: its container draws one under its header, or draws + /// nothing of its own and itself follows one. The body's layout opens its flow start with it. + pub(crate) after_rule: bool, + /// The body is an unwrapped `Row` placed from its start whose container is a row of a vertical flow: its first + /// child in flow starts where the rows of that flow start (`label::in_column`). + pub(crate) column_row: bool, + /// The layout of the bracketed `Row` body (`ContainerProps::bracket`) whose labelled rows report their controls to + /// it: set for the row's body and kept through the containers inside it up to a labelled one. + pub(crate) bracket: Option, /// The container whose footer stands in its body (`FooterPlace::Body`) and the size that footer measured: a /// `FooterSlot` shown under it takes that size and is where the footer is drawn. pub(crate) footer_slot: Option, @@ -366,6 +378,7 @@ impl Scoped { /// layer is no line of a bar it was opened from. A layer's content measures and runs in this. pub(crate) fn start_layer(&mut self) { self.start_room(); + self.bracket = None; self.measure = None; self.arena = None; self.roving = None; @@ -395,6 +408,8 @@ impl Scoped { self.row_room = None; self.row_line = None; self.first_line = None; + self.flow_body = None; + self.column_row = false; self.fill_body = None; self.fill_share = None; self.shrink = None; @@ -563,6 +578,10 @@ impl Env { row_room: None, row_line: None, first_line: None, + flow_body: None, + after_rule: false, + column_row: false, + bracket: None, footer_slot: None, fill_body: None, fill_share: None, @@ -652,6 +671,7 @@ impl Env { pub(crate) fn new_room(&self) -> Env { self.derive_local(|scoped| { scoped.start_room(); + scoped.bracket = None; scoped.lazy = None; scoped.measure = None; // A pane opened from a bar is not the bar's line. diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index b6804a2b8..3efa412a9 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -197,6 +197,13 @@ pub struct Stamped { value: T, } +impl Stamped { + /// The record as its viewport's latest pass left it. + pub(crate) fn value(&self) -> &T { + &self.value + } +} + impl PerViewport { fn record(&mut self, viewport: ViewportId) -> &mut T { let at = match self.records.iter().position(|(id, _)| *id == viewport) { @@ -257,6 +264,11 @@ impl PerViewport { } } + /// Runs `f` on the record of `viewport` when it has one; creates none. + pub(crate) fn with_existing(ctx: &Context, viewport: ViewportId, f: impl FnOnce(&mut T) -> R) -> Option { + T::records(ctx, |records| records.records.iter_mut().find(|(id, _)| *id == viewport).map(|(_, record)| f(record))) + } + /// Runs `f` on the record of every viewport that has one. pub(crate) fn each(ctx: &Context, mut f: impl FnMut(&mut T)) { T::records(ctx, |records| records.records.iter_mut().for_each(|(_, record)| f(record))); diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 5c5b630dc..3894fd46b 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1239,6 +1239,11 @@ pub(crate) mod guard { ("layout::body::HeldWidths", "held widths: opened and closed by the column's own first sweep"), ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), + ( + "layout::body::FlowStarts", + "flow starts: opened by each sweep of the body and closed by its first child in flow; a child reads its body's at its own start, and its measure key holds what it read", + ), + ("layout::body::Brackets", "bracket reports: opened by each sweep of the bracketed row and taken after its body"), ("layout::body::Cursors", "grid and spread cursors: opened and closed by the body's own run"), ("layout::body::ShrinkReports", "shrink reports: opened and closed by the row's own first sweep; the widths go through emit_record"), ("layout::body::LeastReports", "least reports: opened and closed by the row's own least sweep; the widths go through emit_record"), diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index d43456fd0..015651a50 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -75,7 +75,7 @@ impl Rank { /// Whether a layer of this rank takes keys without a focus scope. Modal chrome takes none: Cancel and Enter stay /// with the modal under it. - const fn takes_keys(self) -> bool { + pub(crate) const fn takes_keys(self) -> bool { matches!(self, Rank::Popup | Rank::Modal { .. }) } @@ -152,6 +152,10 @@ pub struct OpenEntry { /// The entry is an OS window of the integration: it takes its place in the stack's order and facts, and no egui /// layer is shown for it. pub(crate) window: bool, + /// The entry stands in its opener's stack for a layer shown in a popup window of its own (with `window`): the + /// family, the anchor and the presses in the opener's window are judged here, and the popup's own stack holds the + /// layer, so the entry blocks nothing here. + pub(crate) popup: bool, /// The screen rect the layer is contained in: its scrim, placement, clip and input blocking stop at it. pub(crate) region: Option, /// The layer's place on its dialog stack (`stack_place`): the modal families of one stack stack in its order. @@ -178,6 +182,7 @@ impl OpenEntry { scoped: false, absorbs: false, window: false, + popup: false, region: None, place: None, dialog: None, @@ -187,7 +192,7 @@ impl OpenEntry { /// Whether the layer is a modal over its whole window: a modal contained in a region blocks only inside it, and the /// window's keys, commands and hits stay with the rest. pub(crate) fn blocks_window(&self) -> bool { - self.rank.is_modal() && self.region.is_none() + self.rank.is_modal() && self.region.is_none() && !self.popup } /// Whether the layer takes keys: the layers `top` can name. A layer with a focus scope takes keys whatever its rank. @@ -535,11 +540,38 @@ pub fn opening(ctx: &Context, id: Id) -> bool { /// not outlive it. The closes are carried: with no motion the layer's body hides in the same frame, so the owner of /// a popup in it runs again only when the layer reopens, and takes the close then. pub(crate) fn close_descendants(ctx: &Context, id: Id) { - for descendant in family(ctx, id).into_iter().filter(|member| *member != id) { + let mut members: Vec = family(ctx, id).into_vec(); + // A member shown in a popup window keeps the layers opened from inside it in that window's stack. + let mut at = 0; + while at < members.len() { + let member = members[at]; + for inner in family_in(ctx, crate::runtime::egui::viewports::viewport_id(member), member) { + if !members.contains(&inner) { + members.push(inner); + } + } + at += 1; + } + for descendant in members.into_iter().filter(|member| *member != id) { push_close(ctx, descendant, CloseReason::Requested, true); } } +/// `id` and everything opened from inside it, as `viewport`'s latest pass showed them (a popup window's: its pass of +/// this frame, or its last one once it is no longer shown); none for a viewport that has no stack. +fn family_in(ctx: &Context, viewport: ViewportId, id: Id) -> Vec { + let Some(last) = PerViewport::>::with_existing(ctx, viewport, |pass| pass.value().current.clone()) else { + return Vec::new(); + }; + let mut out: Vec = last.iter().filter(|entry| entry.id == id).map(|entry| entry.id).collect(); + for entry in &last { + if entry.parent.is_some_and(|parent| out.contains(&parent)) && !out.contains(&entry.id) { + out.push(entry.id); + } + } + out +} + /// Records that a primary press landed outside the layer `id`, its anchor and its family in this pass. pub(crate) fn note_pressed_outside(ctx: &Context, id: Id) { with_pass(ctx, |pass| pass.pressed_outside.push(id)); @@ -810,7 +842,7 @@ pub(crate) fn end_pass(ctx: &Context) { } fn modal_in_other_viewports(ctx: &Context, running: ViewportId) -> bool { - pass::live_viewports(ctx).into_iter().filter(|viewport| *viewport != running).any(|viewport| with_persist(ctx, viewport, |persist| persist.modal)) + modal_viewport(ctx, running).is_some() } /// Whether a modal layer is open in a viewport other than `viewport`: the global open-modal fact the input hook @@ -886,9 +918,19 @@ pub(crate) fn beneath(ctx: &Context, layer: Id) -> (bool, Option) { (root.is_some() || modal_in_other_viewports(ctx, viewport), root) } +/// The live viewports with a modal layer open as of their last finished pass. +fn modal_viewports(ctx: &Context) -> impl Iterator + '_ { + pass::live_viewports(ctx).into_iter().filter(|viewport| with_persist(ctx, *viewport, |persist| persist.modal)) +} + /// A viewport other than `viewport` that has a modal layer open: the window a blocked press raises. pub(crate) fn modal_viewport(ctx: &Context, viewport: ViewportId) -> Option { - pass::live_viewports(ctx).into_iter().filter(|other| *other != viewport).find(|other| with_persist(ctx, *other, |persist| persist.modal)) + modal_viewports(ctx).find(|other| *other != viewport) +} + +/// A viewport that has a modal layer open: the window that blocks the app's other windows. +pub(crate) fn app_modal_viewport(ctx: &Context) -> Option { + modal_viewports(ctx).next() } /// Whether a layer of key class `class` that is not fading out was shown last frame and the screen point `at` lies in diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index def4d3915..d616909a5 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -96,6 +96,8 @@ pass_state! { held_widths: crate::layout::body::HeldWidths, first_lines: crate::layout::body::FirstLines, row_lines: crate::layout::body::RowLines, + flow_starts: crate::layout::body::FlowStarts, + brackets: crate::layout::body::Brackets, cursors: crate::layout::body::Cursors, footer_slots: crate::contract::footer_slot::Slots, column_groups: crate::layout::column_group::Open, diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index a5d117b24..42409d37c 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -48,9 +48,9 @@ pub use shell::shell_of; use shell::{refresh, window_info}; #[cfg(feature = "testing")] pub(crate) use shell::{set_chrome, set_os}; -use spec::chrome_of; +use spec::{AppState, chrome_of}; pub use spec::{WindowLevel, WindowSpec}; -pub(crate) use viewport::{ViewportOpen, show_viewport, take_close_request, unplaced}; +pub(crate) use viewport::{PopupOpen, ViewportOpen, close_popup, place_popup, show_popup, show_viewport, take_close_request, unplaced}; /// Seconds between writes of a changed placement store. const FLUSH_SECONDS: f64 = 1.0; @@ -86,11 +86,17 @@ pub(crate) struct Shared { desktop: Option, /// Whether the root window had focus in the last root pass. root_focused: bool, - /// Whether no window of the app had focus when the last frame's windows had all reported. - away: bool, + /// The app's state when the last frame's windows had all reported, which its palettes follow. + app: AppState, + /// Whether a palette window stood lowered under an app-modal layer in this frame. + lowered: bool, + /// Where the raise of the modal's window above the palettes it lowered stands. + raise: Raise, /// The app's windows from the one focused longest ago to the one focused last: the stacking order of /// overlapping windows. stacking: Vec, + /// The windows that got a primary press, each with the root frame of the press, in this root frame and the last. + presses: Vec<(ViewportId, u64)>, } /// One viewport's window record. @@ -105,8 +111,10 @@ pub(crate) struct Record { chrome: Option, /// The caption buttons the app draws in this window. captions: Option, - /// The level the window was opened with or last set to; a palette's egui level follows the app's activity. + /// The level the window was opened with or last set to; a palette's egui level follows the app's state. level: Option, + /// Whether the window is hidden because the app's state hides it (a palette while the main window is minimized). + hidden: bool, /// H4: whether the primary button is down as the viewport's events left the input hook. primary_down: bool, /// Whether the user can resize the window; unknown for a window not opened by `show_viewport`. @@ -146,6 +154,22 @@ pub(crate) struct Record { seen: Option, /// The smallest inner size its caller asks for, as the window's builder carries it. min_size: Option, + /// For a popup window ([`show_popup`]): the window its layer was opened from, while the layer shows. + opener: Option, +} + +/// The raise of the window holding an app-modal layer above the palettes the modal lowered. The raise goes out in the +/// frame after a palette was built lowered: a raise in the same frame may reach the OS before the palette's new level +/// does, and the palette, made an ordinary window after it, would stand in front again. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Raise { + /// No palette has stood lowered under the open modal yet, or no modal is open. + #[default] + Waiting, + /// A palette stood lowered in the last frame: the modal's window is raised in this one. + Due, + /// The modal's window was raised. + Done, } /// Passes between searches for an OS window that was not found. @@ -294,6 +318,15 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool { if handed_off && tracked == Some(viewport) { shared(ctx, |shared| shared.tracked_move = None); } + let pressed = + input.events.iter().any(|event| matches!(event, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, .. })); + if pressed { + let frame = pass::root_frame_nr(ctx); + shared(ctx, |shared| { + shared.presses.retain(|(_, at)| at + 1 >= frame); + shared.presses.push((viewport, frame)); + }); + } released } @@ -350,6 +383,73 @@ fn opens_over(ctx: &Context, opener: ViewportId) -> bool { !covers } +/// Where the layers opened in a palette window show: in popup windows of their own, placed in desktop points. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PopupRoom { + /// The palette window's inner top-left corner in desktop points: the origin of its viewport's points. + pub origin: Pos2, + /// The room its layers may take, in its viewport's points: the work area of the monitor the window is on, or where + /// no monitor is listed, the area the app's windows other than popups span. + pub room: Rect, +} + +/// The room of the layers opened in the running viewport when it is a palette window (a dock window or a popup +/// window, both at [`WindowLevel::Palette`]) that opens OS windows ([`opens_over`]) where the platform places them: +/// every such layer shows in a popup window of its own. `None` in every other window, whose layers stay in it. +pub(crate) fn popup_room(ctx: &Context) -> Option { + let viewport = pass::current_viewport(ctx); + if !base_shell(ctx).window_positions() || !opens_over(ctx, viewport) { + return None; + } + let facts = PerViewport::::with_existing(ctx, viewport, |record| record.facts.filter(|_| record.level == Some(WindowLevel::Palette)))??; + let origin = facts.inner?.min; + let scale = host::scale_of(ctx, &facts).unwrap_or(1.0).max(f32::EPSILON); + let work = host::monitor_of(ctx, &facts).map(|monitor| { + let (pos, size) = monitor.work_px.unwrap_or((monitor.pos_px, monitor.size_px)); + let min = Pos2::new(pos[0] as f32, pos[1] as f32) / scale; + Rect::from_min_size(min, Vec2::new(size[0] as f32, size[1] as f32) / scale) + }); + // The popup windows themselves don't count: a popup's room never depends on where a popup stands. + let spanned = || { + let popup = |viewport: ViewportId| PerViewport::::with_existing(ctx, viewport, |record| record.opener.is_some()).unwrap_or(false); + viewports::reported(ctx) + .iter() + .filter(|(viewport, _)| !popup(*viewport)) + .filter_map(|(_, facts)| facts.inner) + .fold(Rect::NOTHING, Rect::union) + }; + let room = work.unwrap_or_else(spanned).translate(-origin.to_vec2()); + Some(PopupRoom { origin, room }) +} + +/// Whether a primary press landed, in this root frame (or in the last one, unless the popup window `popup` just +/// `appeared`), in a window of the app other than the running viewport (the popup's opener, whose own presses its +/// layer stack judges) and the popup window and the popup windows opened from it. +pub(crate) fn pressed_elsewhere(ctx: &Context, popup: ViewportId, appeared: bool) -> bool { + let opener = pass::current_viewport(ctx); + let frame = pass::root_frame_nr(ctx); + let presses = shared(ctx, |shared| shared.presses.clone()); + presses.into_iter().filter(|(_, at)| *at == frame || (!appeared && at + 1 == frame)).any(|(viewport, _)| { + if viewport == opener { + return false; + } + // A press in a popup window opened from the popup, at any depth, is inside its family. + let mut at = Some(viewport); + while let Some(window) = at { + if window == popup { + return false; + } + at = PerViewport::::with_existing(ctx, window, |record| record.opener).flatten(); + } + true + }) +} + +/// Whether no window of the app has focus, as the last frame's windows reported. +pub(crate) fn app_away(ctx: &Context) -> bool { + shared(ctx, |shared| shared.app.away) +} + /// Refuses the close request of the running viewport while an app-modal layer blocks it, and raises the modal's /// window. True when it refused. fn refuse_close_under_modal(ctx: &Context) -> bool { @@ -465,12 +565,14 @@ fn flush_store(ctx: &Context) { } } -/// Keeps the app's activity and the stacking order of its windows current from the windows' focus. A palette's -/// window level follows the activity: the mounts build their viewports with the level of the moment, and a change +/// Keeps the app's state and the stacking order of its windows current from the windows' facts. A palette's window +/// level and visibility follow the state: the mounts build their viewports with the state of the moment, and a change /// asks for the next frame. Runs at the end of the root pass, inside which every child window's pass of the frame /// has run, so each window's focus is the one its own pass reported after its input batch. The root input's list of /// windows holds each child as of its previous pass, so it is not read for focus. The app is inactive when no /// window reports focus: the batch that took focus from one window gave it to no other. +/// +/// Once a palette has stood lowered under an app-modal layer, the modal's window is raised above it, once per modal. fn follow_activity(ctx: &Context) { let windows = viewports::reported(ctx); let focused: Vec = windows @@ -478,13 +580,27 @@ fn follow_activity(ctx: &Context) { .map(|(viewport, _)| *viewport) .filter(|viewport| PerViewport::::with(ctx, *viewport, |record| record.facts.is_some_and(|facts| facts.focused))) .collect(); - let changed = shared(ctx, |shared| { + let modal = overlay::app_modal_viewport(ctx); + let minimized = viewports::current(ctx).minimized; + let (repaint, raise) = shared(ctx, |shared| { shared.stacking.retain(|viewport| windows.iter().any(|(open, _)| open == viewport) && !focused.contains(viewport)); shared.stacking.extend(&focused); - let away = focused.is_empty(); - std::mem::replace(&mut shared.away, away) != away + let app = AppState { away: focused.is_empty(), modal, minimized }; + let lowered = std::mem::take(&mut shared.lowered); + let (step, raise) = match shared.raise { + _ if app.modal != shared.app.modal => (Raise::Waiting, None), + Raise::Waiting if lowered => (Raise::Due, None), + Raise::Due => (Raise::Done, app.modal), + step => (step, None), + }; + shared.raise = step; + let changed = std::mem::replace(&mut shared.app, app) != app; + (changed || step == Raise::Due, raise) }); - if changed { + if let Some(modal) = raise { + act(ctx, modal, WindowAction::Raise); + } + if repaint { ctx.request_repaint(); } } diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 5e15aac8d..84ed27cde 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -421,7 +421,7 @@ pub(super) fn monitors(ctx: &Context) -> Vec { /// The monitor the top-left corner of a window with `facts` lies on. A corner is on a monitor when its pixel position /// at that monitor's scale is inside the monitor. -fn monitor_of(ctx: &Context, facts: &viewports::Facts) -> Option { +pub(super) fn monitor_of(ctx: &Context, facts: &viewports::Facts) -> Option { let corner = facts.outer.or(facts.inner)?.min; monitors(ctx).into_iter().find(|monitor| monitor.rect_px().contains(corner * monitor.scale)) } diff --git a/crates/ui-contract/src/runtime/windows/native.rs b/crates/ui-contract/src/runtime/windows/native.rs index b13db3737..9974910df 100644 --- a/crates/ui-contract/src/runtime/windows/native.rs +++ b/crates/ui-contract/src/runtime/windows/native.rs @@ -5,7 +5,7 @@ use super::host::scale_of; #[cfg(doc)] use super::logic; use super::shell::{base_shell, os_of, window_info}; -use super::spec::WindowLevel; +use super::spec::{Standing, WindowLevel}; use super::{HandOff, Record, SEARCH_EVERY, shared}; use crate::runtime::egui::{pass, viewports}; use crate::runtime::frame::{PerViewport, Stored}; @@ -40,6 +40,9 @@ pub enum WindowAction { SetMaximized(bool), /// Raises the window and gives it OS focus. Focus, + /// Brings the window in front of the app's other windows without giving it focus, as the window holding an + /// app-modal layer comes in front of the palettes the modal lowered. + Raise, /// The OS starts moving the window with the pointer. StartMove, /// The OS starts resizing the window from `edge`. @@ -100,7 +103,8 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { | WindowAction::Restore | WindowAction::SetMinInnerSize(_) | WindowAction::SetLevel(_) - | WindowAction::SetTitle(_) => commands, + | WindowAction::SetTitle(_) + | WindowAction::Raise => commands, WindowAction::SetOpacity(_) => false, }; if !allowed { @@ -109,6 +113,7 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { match action { WindowAction::Close => viewports::close(ctx, viewport), WindowAction::Focus => viewports::raise(ctx, viewport), + WindowAction::Raise => viewports::raise_above(ctx, viewport, standing(ctx, viewport, level_of(ctx, viewport)).level), WindowAction::Minimize => viewports::command(ctx, viewport, egui::ViewportCommand::Minimized(true)), WindowAction::ToggleMaximize => viewports::command(ctx, viewport, egui::ViewportCommand::Maximized(window.state != WindowState::Maximized)), WindowAction::ToggleFullscreen => { @@ -147,8 +152,7 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { if opened { ctx.request_repaint_of(viewport); } else { - let active = !shared(ctx, |shared| shared.away); - viewports::command(ctx, viewport, egui::ViewportCommand::WindowLevel(level.for_egui(active, os_of(ctx)))); + viewports::command(ctx, viewport, egui::ViewportCommand::WindowLevel(standing(ctx, viewport, level).level)); } } WindowAction::SetTitle(title) => { @@ -172,6 +176,16 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { true } +/// The level `viewport`'s window was opened with or last set to. +fn level_of(ctx: &Context, viewport: ViewportId) -> WindowLevel { + PerViewport::::with(ctx, viewport, |record| record.level.unwrap_or_default()) +} + +/// How `viewport`'s window at `level` stands in the app's current state. +fn standing(ctx: &Context, viewport: ViewportId, level: WindowLevel) -> Standing { + level.standing(viewport, shared(ctx, |shared| shared.app), os_of(ctx)) +} + /// Applies `opacity` to the OS window. A faded window is told again in every pass, because the window system's own /// style changes can drop the layered style; an opaque one only when it was faded. Returns whether the platform applied /// it now. diff --git a/crates/ui-contract/src/runtime/windows/spec.rs b/crates/ui-contract/src/runtime/windows/spec.rs index cb8277a54..af9e889e6 100644 --- a/crates/ui-contract/src/runtime/windows/spec.rs +++ b/crates/ui-contract/src/runtime/windows/spec.rs @@ -4,7 +4,7 @@ use super::shared; use super::shell::{base_shell, os_of}; use craft_host::target::{Os, WindowChrome, WindowKind}; use craft_window::policy::{CaptionFamily, Captions, Frame, MacInset, tool_frame}; -use egui::Context; +use egui::{Context, ViewportId}; /// Where a window stands in the stack of windows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -13,26 +13,53 @@ pub enum WindowLevel { /// An ordinary window. #[default] Normal, - /// A palette: above the app's other windows while the app is active, and an ordinary window (behind other - /// apps' windows on Windows) once none of the app's windows has focus, so it stays shown without covering - /// other apps. + /// A palette: above the app's other windows while the app is active, an ordinary window while an app-modal layer + /// in another window blocks it, and an ordinary window (behind other apps' windows on Windows) once none of the + /// app's windows has focus, so it stays shown without covering other apps or the modal. Hidden while the main + /// window is minimized, except on macOS, where the app stays active and its palettes stay. Palette, /// Above every other window. AlwaysOnTop, } +/// The app's state that its palettes follow, as its windows reported it in the last frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct AppState { + /// No window of the app has focus. + pub away: bool, + /// The window that holds an app-modal layer, which blocks the app's other windows. + pub modal: Option, + /// The main window is minimized. + pub minimized: bool, +} + +/// How a window stands among the windows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Standing { + /// The level egui is given. + pub level: egui::WindowLevel, + /// Whether the window is shown. + pub shown: bool, + /// Whether the window stands as an ordinary window because an app-modal layer in another window blocks it. + pub lowered: bool, +} + impl WindowLevel { - /// The level egui is given while the app is `active` or not, on `os`. An inactive app's palette goes behind - /// other apps' windows: on Windows `Normal` puts a window in front of every window that is not topmost, the - /// activated app's included, so the palette goes to the bottom. - pub(super) fn for_egui(self, active: bool, os: Os) -> egui::WindowLevel { - match self { + /// How `viewport`'s window at this level stands while the app is in `app`, on `os`. An inactive app's palette goes + /// behind other apps' windows: on Windows `Normal` puts a window in front of every window that is not topmost, the + /// activated app's included, so the palette goes to the bottom. A palette blocked by a modal stands as an ordinary + /// window, so the modal's window can be raised above it. + pub(super) fn standing(self, viewport: ViewportId, app: AppState, os: Os) -> Standing { + let palette = self == WindowLevel::Palette; + let lowered = palette && !app.away && app.modal.is_some_and(|modal| modal != viewport); + let level = match self { WindowLevel::Normal => egui::WindowLevel::Normal, WindowLevel::AlwaysOnTop => egui::WindowLevel::AlwaysOnTop, - WindowLevel::Palette if active => egui::WindowLevel::AlwaysOnTop, - WindowLevel::Palette if os == Os::Windows => egui::WindowLevel::AlwaysOnBottom, - WindowLevel::Palette => egui::WindowLevel::Normal, - } + WindowLevel::Palette if app.away && os == Os::Windows => egui::WindowLevel::AlwaysOnBottom, + WindowLevel::Palette if app.away || lowered => egui::WindowLevel::Normal, + WindowLevel::Palette => egui::WindowLevel::AlwaysOnTop, + }; + Standing { level, shown: !(palette && app.minimized && os != Os::Mac), lowered } } } @@ -58,6 +85,10 @@ pub struct WindowSpec { pub taskbar: bool, /// Whether the window opens hidden and appears once its first pass has been laid out and painted. pub shown_after_first_paint: bool, + /// Whether the window takes OS focus when it opens. + pub takes_focus: bool, + /// Whether pointer input passes through the window to the window below it. + pub passes_pointer: bool, } impl WindowSpec { @@ -67,6 +98,13 @@ impl WindowSpec { WindowSpec { kind: WindowKind::Tool, level: WindowLevel::Palette, taskbar: false, ..Self::dialog() } } + /// A popup window: a layer opened from a palette window (a flyout, menu or tooltip) in an OS window of its own. It + /// has no frame, no taskbar entry and a palette level, and appears once its first pass ran, at the size and place + /// its layer took in that pass. + pub fn popup() -> Self { + WindowSpec { chrome: Some(WindowChrome::Integrated), shown_after_first_paint: true, ..Self::tool() } + } + /// A document window with the installed decision's frame. pub fn document() -> Self { WindowSpec { kind: WindowKind::Document, ..Self::dialog() } @@ -81,6 +119,8 @@ impl WindowSpec { level: WindowLevel::Normal, taskbar: true, shown_after_first_paint: false, + takes_focus: true, + passes_pointer: false, } } @@ -130,6 +170,20 @@ impl WindowSpec { self } + /// Sets whether the window takes OS focus when it opens. + #[must_use] + pub fn takes_focus(mut self, takes_focus: bool) -> Self { + self.takes_focus = takes_focus; + self + } + + /// Sets whether pointer input passes through the window to the window below it (a tooltip's). + #[must_use] + pub fn passes_pointer(mut self, passes_pointer: bool) -> Self { + self.passes_pointer = passes_pointer; + self + } + /// Sets whether the window opens hidden and appears after its first paint, so a window that shows a capture or /// other content that must be ready does not flash an empty frame. #[must_use] diff --git a/crates/ui-contract/src/runtime/windows/viewport.rs b/crates/ui-contract/src/runtime/windows/viewport.rs index a037488a7..b621430c3 100644 --- a/crates/ui-contract/src/runtime/windows/viewport.rs +++ b/crates/ui-contract/src/runtime/windows/viewport.rs @@ -54,10 +54,10 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im keep_placed(ctx, viewport, pos, size.filter(|_| open.follows_size)); } let spec = open.spec; - let active = !shared(ctx, |shared| shared.away); + let state = shared(ctx, |shared| shared.app); let os = os_of(ctx); let (chrome, captions) = frame_of_spec(ctx, spec); - let level = PerViewport::::with(ctx, viewport, |record| { + let standing = PerViewport::::with(ctx, viewport, |record| { record.kind = Some(spec.kind); record.chrome = Some(chrome); record.captions = captions.clone(); @@ -73,8 +73,11 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im record.searched = None; } } - record.level.get_or_insert(spec.level).for_egui(active, os) + record.level.get_or_insert(spec.level).standing(viewport, state, os) }); + if standing.lowered { + shared(ctx, |shared| shared.lowered = true); + } let app = app_id(ctx); let opens = viewports::Spec { title: open.title, @@ -88,10 +91,12 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im // 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, + level: standing.level, resizable: open.resizable, taskbar: spec.taskbar, hidden: PerViewport::::with(ctx, viewport, |record| record.awaiting_first_paint), + active: spec.takes_focus, + passes_pointer: spec.passes_pointer, app_id: &app, }; viewports::show_immediate(ctx, viewport, &opens, |ui| { @@ -115,8 +120,77 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im record_placement(&ctx, viewport, key, &at_known(&ctx, viewport, viewports::current(&ctx))); } }); - if PerViewport::::with(ctx, viewport, |record| std::mem::take(&mut record.awaiting_first_paint)) { - viewports::show(ctx, viewport); + // A window opened hidden appears once its first pass ran; a window the app's state hides goes and comes back with + // it. The builder's visibility only opens the window: egui sends no change of it once the window is open. + let hidden = !standing.shown; + let (reveal, changed) = PerViewport::::with(ctx, viewport, |record| { + let first = std::mem::take(&mut record.awaiting_first_paint); + let changed = std::mem::replace(&mut record.hidden, hidden) != hidden; + (first || changed, changed) + }); + if hidden && changed { + viewports::set_visible(ctx, viewport, false); + } else if !hidden && reveal { + viewports::set_visible(ctx, viewport, true); + } +} + +/// What a layer shown in a popup window asks for ([`show_popup`]). +pub(crate) struct PopupOpen<'a> { + /// The layer's id; the popup's viewport derives from it. + pub id: Id, + /// How the window opens: a [`WindowSpec::popup`]. + pub spec: &'a WindowSpec, + /// The window's place in desktop points (outer top-left corner and inner size) when the layer's size is known + /// before its pass; otherwise the caller places it after the pass ([`place_popup`]). + pub rect: Option, +} + +/// Opens the popup window of a layer opened in the running viewport (its opener) and runs `body` in its pass. The +/// window is a viewport mount without a container: it opens at `open.rect` and follows it, and the opener gets the OS +/// focus back when it closes ([`close_popup`]). +pub(crate) fn show_popup(ctx: &Context, open: &PopupOpen<'_>, body: impl FnMut(&mut Ui)) { + let opener = crate::runtime::egui::pass::current_viewport(ctx); + PerViewport::::with(ctx, viewports::viewport_id(open.id), |record| record.opener = Some(opener)); + let mount = ViewportOpen { + id: open.id, + title: "", + size: open.rect.map(|rect| rect.size()), + follows_size: true, + save: None, + spec: open.spec, + limits: (None, None), + position: open.rect.map(|rect| rect.min), + resizable: false, + moved_by_app: false, + }; + show_viewport(ctx, &mount, body); +} + +/// Sends the popup window of layer `id` to `rect` (desktop points) where it is not there already: a layer whose size +/// its pass measured is placed once that pass ran. +pub(crate) fn place_popup(ctx: &Context, id: Id, rect: Rect) { + let viewport = viewports::viewport_id(id); + let known = PerViewport::::with(ctx, viewport, |record| record.known); + if known.is_none_or(|known| differs(ctx, viewport, rect.min - known.min)) { + act(ctx, viewport, WindowAction::SetOuterPosition(rect.min)); + } + if known.is_none_or(|known| differs(ctx, viewport, rect.size() - known.size())) { + act(ctx, viewport, WindowAction::SetInnerSize(rect.size())); + } + PerViewport::::with(ctx, viewport, |record| record.known = Some(rect)); +} + +/// The layer `id` is hidden: when it showed in a popup window that still has the OS focus, the window it was opened +/// from takes the focus back. Once per close; a layer that never showed in a popup does nothing. +pub(crate) fn close_popup(ctx: &Context, id: Id) { + let viewport = viewports::viewport_id(id); + let closed = PerViewport::::with_existing(ctx, viewport, |record| { + let focused = record.facts.is_some_and(|facts| facts.focus_reported); + record.opener.take().filter(|_| focused) + }); + if let Some(opener) = closed.flatten() { + act(ctx, opener, WindowAction::Focus); } } @@ -151,9 +225,17 @@ pub(crate) fn unplaced(ctx: &Context, id: Id) -> bool { && PerViewport::::with(ctx, viewports::viewport_id(id), |record| record.kind.is_some() && record.seen.is_none()) } -/// How far a caller's place may differ from the known place before it is a change: the OS rounds to pixels, and a -/// placement records the position in pixels. -const ROUNDING: f32 = 0.5; +/// How far a caller's place may differ from the known place before it is a change, in physical pixels of the window's +/// display: the OS rounds to pixels, and a placement records the position in pixels. +const ROUNDING_PX: f32 = 0.5; + +/// Whether `delta`, in points, moves the window `viewport` by more than rounding on its display: a whole pixel on +/// a 2x display is half a point. +fn differs(ctx: &Context, viewport: ViewportId, delta: Vec2) -> bool { + let facts = PerViewport::::with(ctx, viewport, |record| record.facts); + let scale = facts.and_then(|facts| super::host::scale_of(ctx, &facts)).unwrap_or(1.0); + delta.x.abs() * scale > ROUNDING_PX || delta.y.abs() * scale > ROUNDING_PX +} /// The place of a window with `facts`: its outer top-left corner and its inner size. fn place_of(facts: &viewports::Facts) -> Option { @@ -182,11 +264,10 @@ fn keep_placed(ctx: &Context, viewport: ViewportId, pos: Option, size: Opt (record.known, state || record.moved_pointer.is_some()) }); let Some(known) = known.filter(|_| !held) else { return }; - let differs = |delta: Vec2| delta.x.abs() > ROUNDING || delta.y.abs() > ROUNDING; - if let Some(pos) = pos.filter(|pos| differs(*pos - known.min)) { + if let Some(pos) = pos.filter(|pos| differs(ctx, viewport, *pos - known.min)) { act(ctx, viewport, WindowAction::SetOuterPosition(pos)); } - if let Some(size) = size.filter(|size| differs(*size - known.size())) { + if let Some(size) = size.filter(|size| differs(ctx, viewport, *size - known.size())) { act(ctx, viewport, WindowAction::SetInnerSize(size)); } } diff --git a/crates/ui-contract/src/style/mod.rs b/crates/ui-contract/src/style/mod.rs index dc5783d61..a2fd71549 100644 --- a/crates/ui-contract/src/style/mod.rs +++ b/crates/ui-contract/src/style/mod.rs @@ -18,6 +18,7 @@ pub use cache::{Accepted, accepted_variant}; pub use craft_behavior::{ControlMetrics, Insets, Metrics}; #[doc(hidden)] pub use craft_theme::GroupValues; +pub use craft_theme::LetterCase; pub use craft_theme::{FlagMask, Flags, Mix, Resolve, State, StateMix, Stateful, States, TokenGroup, Tokens, TypeRole, Variant}; pub use craft_ui_macros::{ComponentStyle, TokenGroup}; pub(crate) use cx::control_metrics; diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 924eed4d6..6b86efe0f 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -1,8 +1,8 @@ //! `runtime::windows`: the input hook per viewport, window info per viewport, the press release after an OS //! resize (H4), the raise of a modal's window, the mount of a full-window container (in a window of its own, or in a -//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, -//! injected keys across a focus loss, non-finite injected points, a repeated injected press, the window that has the -//! keys, and `act`. +//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, a +//! palette's level under a modal and its visibility while the main window is minimized, injected keys across a focus +//! loss, non-finite injected points, a repeated injected press, the window that has the keys, and `act`. use craft_behavior::{Cursor, CursorIcon, PointerButton}; use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind}; @@ -302,6 +302,81 @@ fn a_palette_drops_its_level_while_the_app_is_inactive() { assert_eq!(frame(true, false), on_top, "the frame after the main window took focus again"); } +/// A palette stands as an ordinary window while an app-modal layer in the main window blocks it, so the modal is never +/// behind a palette: the frame after the modal opens builds the palette's window at the ordinary level, a later frame +/// raises the main window above it once, by its level (egui ignores `Focus` for a window that has focus), and the +/// palette stands above the app's windows again once the modal closes. +#[trial] +fn a_palette_stands_behind_the_window_that_holds_a_modal() { + let windows = Windows::new(); + windows.root_info(ViewportInfo { focused: Some(true), ..ViewportInfo::default() }); + let frame = |modal: bool| { + let out = windows.frame(vec![], vec![], |ui| { + windows.child_info(ViewportInfo { focused: Some(false), ..ViewportInfo::default() }); + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {}); + if modal { + let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal())); + Modal { common: Common::new(), props }.id_salt("save prompt").show(ui, |_, _| {}); + } + }); + let raise: Vec = out + .commands + .iter() + .filter(|(id, command)| *id == ViewportId::ROOT && matches!(command, ViewportCommand::WindowLevel(_) | ViewportCommand::Focus)) + .map(|(_, command)| command.clone()) + .collect(); + (builder_titled(&out, "tool").1.window_level, raise) + }; + let (on_top, normal) = (Some(egui::WindowLevel::AlwaysOnTop), Some(egui::WindowLevel::Normal)); + assert_eq!(frame(false), (on_top, vec![]), "no modal: the palette stands above the main window"); + let frames: Vec<_> = (0..4).map(|_| frame(true)).collect(); + assert_eq!(frames.last().map(|(level, _)| *level), Some(normal), "the modal open: the palette is an ordinary window"); + let raises: Vec = frames.iter().enumerate().filter(|(_, (_, raise))| !raise.is_empty()).map(|(at, _)| at).collect(); + let lowered = frames.iter().position(|(level, _)| *level == normal); + assert_eq!(raises.len(), 1, "the main window is raised once: {frames:?}"); + assert!(lowered.is_some_and(|lowered| raises[0] > lowered), "the raise follows the frame that lowered the palette: {frames:?}"); + let level = |level| ViewportCommand::WindowLevel(level); + assert_eq!( + frames[raises[0]].1, + vec![level(egui::WindowLevel::AlwaysOnTop), level(egui::WindowLevel::Normal)], + "the raise stands the main window above every window and back, without focus" + ); + frame(false); + assert_eq!(frame(false), (on_top, vec![]), "the modal closed: the palette stands above again"); +} + +/// A palette's window is hidden while the main window is minimized and shown again at its place when the main window +/// is restored, on Windows and Linux; a document window stays. On macOS a minimized main window leaves the app active, +/// and its palettes stay. +#[trial] +fn palettes_hide_while_the_main_window_is_minimized() { + for os in [Os::Windows, Os::Linux, Os::Mac] { + let windows = Windows::with(InstallSpec::new(ShellInfo::default().os(os).caps(Caps::native(os)), Arc::new(FakeSystem::new()))); + let frame = |minimized: bool| { + windows.root_info(ViewportInfo { minimized: Some(minimized), ..ViewportInfo::default() }); + windows.frame(vec![], vec![], |ui| { + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {}); + Palette::new("doc", Some(WindowSpec::document())).show(ui, |_, _| {}); + }) + }; + let first = frame(false); + let (tool, doc) = (builder_titled(&first, "tool").0, builder_titled(&first, "doc").0); + frame(false); + let commands = |minimized: bool| -> Vec<(ViewportId, ViewportCommand)> { (0..3).flat_map(|_| frame(minimized).commands).collect() }; + let sent = |commands: &[(ViewportId, ViewportCommand)], to: ViewportId| -> Vec { + commands.iter().filter(|(id, _)| *id == to).map(|(_, command)| command.clone()).collect() + }; + let (minimized, restored) = (commands(true), commands(false)); + let hides = os != Os::Mac; + let visible = |on: bool| if hides { vec![ViewportCommand::Visible(on)] } else { vec![] }; + let (tool_minimized, doc_minimized) = (sent(&minimized, tool), sent(&minimized, doc)); + let (tool_restored, doc_restored) = (sent(&restored, tool), sent(&restored, doc)); + assert_eq!(tool_minimized, visible(false), "{os:?}: the main window minimized: the palette is hidden, and nothing else is sent"); + assert_eq!(tool_restored, visible(true), "{os:?}: the main window restored: the palette is shown where it was"); + assert_eq!((doc_minimized, doc_restored), (vec![], vec![]), "{os:?}: a document window is left as it is"); + } +} + /// A full-window container mounted in its own window opens a resizable OS window titled as the container where /// viewports are available, and covers the main window's content where they are not. #[trial] diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 1980e15bd..fc6369b3b 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -9,7 +9,7 @@ use super::dock_column::{CHEVRON, ColumnArrow, describe_chevron, paint_chevron}; use super::drop::{DragUnit, start_group_drag}; -use super::{DockDropTarget, DockDropped, DockWords, GroupDrag, PanelDrag, PanelKey, native}; +use super::{DockDropTarget, DockDropped, DockSizes, DockWords, GroupDrag, PanelDrag, PanelKey, native}; use crate::contract::BodyCx; use crate::contract::SizeLimits; use crate::contract::overlay::{PlacementChange, PlacementKind, Popup, ResizeEdges}; @@ -53,14 +53,21 @@ pub struct FloatingGroupStyle { /// The column a dock's floating window holds. The window's title row is the column's bar: it shows the column's /// double arrow at the end on `edge`, and a collapsed column shows against that edge of the window's rect. +/// +/// A column whose content fixes its height ([`held`](Self::held)) shows at that height whatever the rect's, and the +/// rect keeps its own height for when the content no longer fixes it: a column collapsed to icons, and one whose +/// every group is minimized. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct WindowColumn { /// The edge of the float area, in reading order, that the window keeps to: the dock model's `Floating::edge`, /// else the one nearer the window. pub edge: DockEdge, - /// The size of the collapsed column under the title row; `None` while the column is expanded. - pub collapsed: Option, + /// The height of the column under the title row when its content fixes it: a collapsed column's icons, or the + /// tab strips of a column whose every group is minimized. `None` while the rect gives the height. + pub held: Option, + /// The width of the collapsed column; `None` while the column is expanded, and the rect gives the width. + pub collapsed: Option, /// The least and most width the sides of a collapsed column's window resize it to /// ([`DockSizes::iconic_bounds`](super::DockSizes::iconic_bounds)); unbounded while the column is expanded. pub widths: (f32, f32), @@ -74,20 +81,27 @@ pub struct WindowColumn { impl WindowColumn { /// An expanded column that keeps to `edge`. pub fn expanded(edge: DockEdge) -> Self { - WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } + WindowColumn { edge, held: None, collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } } /// A column collapsed to icons, `size` under the title row, that keeps to `edge`. The window's sides resize its /// width within `widths`, as a docked collapsed column's inner edge does; its height stays `size`'s. pub fn collapsed(edge: DockEdge, size: Vec2, widths: (f32, f32)) -> Self { - WindowColumn { edge, collapsed: Some(size), widths, fitted: None, arrow: ColumnArrow::Collapse } + WindowColumn { edge, held: Some(size.y), collapsed: Some(size.x), widths, fitted: None, arrow: ColumnArrow::Collapse } + } + + /// An expanded column whose every group is minimized, their strips `height` under the title row, that keeps to + /// `edge`. The window shows at its rect's place and width and that height; its sides resize the width, and the + /// rect keeps its height, which the window takes back once a group is restored. + pub fn minimized(edge: DockEdge, height: f32) -> Self { + WindowColumn { edge, held: Some(height), collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } } /// An expanded column whose content is `size` under the title row, that keeps to `edge`. The window shows at /// that size at its rect's place; a resize the user makes is reported for the host to turn into the column's /// steps, and a move keeps the rect's size. pub fn fitted(edge: DockEdge, size: Vec2) -> Self { - WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: Some(size), arrow: ColumnArrow::Collapse } + WindowColumn { edge, held: None, collapsed: None, widths: UNBOUNDED, fitted: Some(size), arrow: ColumnArrow::Collapse } } /// The column with the double arrow `arrow` ([`ColumnArrow::of`]). @@ -96,20 +110,25 @@ impl WindowColumn { self } - /// Where a window that keeps `rect` shows while its column is collapsed: the collapsed column under the window's - /// chrome, `chrome` tall (`DockSizes::window_chrome`), at the top of `rect` and against the edge the window keeps - /// to. `None` while the column is expanded. + /// Where a window that keeps `rect` shows while its content fixes its height ([`Self::held`]): the column under + /// the window's chrome, `chrome` tall (`DockSizes::window_chrome`), at the top of `rect`, as wide as a collapsed + /// column or else as `rect`, and against the edge the window keeps to. `None` while the rect gives the height. pub fn shown(self, rect: Rect, chrome: f32, rtl: bool) -> Option { - let size = self.collapsed? + Vec2::new(0.0, chrome); + let size = Vec2::new(self.collapsed.unwrap_or(rect.width()), self.held? + chrome); 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 that the column's side on the edge the window keeps to stays on that side - /// of `rect`, whatever width the column shows at; `rect` keeps its expanded size. While expanded, `shown`. + /// The rect a window that keeps `rect` keeps when it shows at `shown`, so that it keeps its height while its + /// content fixes the shown one ([`Self::shown`]). While collapsed, `rect` moved with the collapsed column so that + /// the column's side on the edge the window keeps to stays on that side of `rect`, whatever width the column shows + /// at; `rect` keeps its expanded size. While every group is minimized, `shown`'s place and width with `rect`'s + /// height. Otherwise `shown`. pub fn kept(self, shown: Rect, rect: Rect, chrome: f32, rtl: bool) -> Rect { let Some(at) = self.shown(rect, chrome, rtl) else { return shown }; + if self.collapsed.is_none() { + return Rect::from_min_size(shown.min, Vec2::new(shown.width(), rect.height())); + } let dx = if at_left(self.edge, rtl) { shown.left() - at.left() } else { shown.right() - at.right() }; rect.translate(Vec2::new(dx, shown.top() - at.top())) } @@ -126,7 +145,8 @@ impl WindowColumn { /// at the same place against that edge ([`Self::around_strip`]); an expanded window keeps `rect`, and the edge /// nearer it (`None`). pub fn dropped(self, rect: Rect, bounds: Rect, rtl: bool) -> (Rect, Option) { - let Some(size) = self.collapsed else { return (rect, None) }; + let (Some(width), Some(height)) = (self.collapsed, self.held) else { return (rect, None) }; + let size = Vec2::new(width, height); let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x }; let (rect, edge) = Self::around_strip(Rect::from_min_size(Pos2::new(left, rect.top()), size), rect.size(), bounds, rtl); (rect, Some(edge)) @@ -199,7 +219,8 @@ impl Outcome for FloatingGroupOutput { /// in [`FloatingGroupOutput::collapsed_width`]) while its height stays the icons', and the rect keeps its 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, and in an OS window the app runs them, so the window takes only the size the -/// host gives it. +/// host gives it. A column whose every group is minimized ([`WindowColumn::minimized`]) shows at the rect's place +/// and width and its strips' height; its sides resize the width, and the rect keeps its height. /// - 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 @@ -256,6 +277,9 @@ pub struct FloatingGroup<'a> { placed: Option, /// The width a resize gave the collapsed column this pass. collapsed_width: Option, + /// The display scale of the OS window the group shows in, which sizes the rule under its title row; unset, the + /// running window's. + scale: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, /// Takes the drops released on the group, on the group's own layer. @@ -302,6 +326,7 @@ impl<'a> FloatingGroup<'a> { rtl: false, placed: None, collapsed_width: None, + scale: None, start_drag: None, take_drop: None, moving: false, @@ -338,6 +363,14 @@ impl<'a> FloatingGroup<'a> { self } + /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the + /// running window's: its chrome is sized at that scale. + #[must_use] + pub fn scale(mut self, pixels_per_point: f32) -> Self { + self.scale = Some(pixels_per_point); + self + } + /// The action parts at the end of the title row, in reading order. #[must_use] pub fn actions(mut self, actions: impl IntoIterator) -> Self { @@ -348,11 +381,11 @@ impl<'a> FloatingGroup<'a> { /// Shows the group; `body` fills the area under the title row unless the group is minimized. pub fn show_group(mut self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { let env = Env::of(ui); - let header = title_row(&env.tokens); // A window in the app window keeps the band over its title row that a layer the user moves keeps for its top - // grip; an OS window's grips lie over its title row. - let band = if self.native.is_none() { crate::contract::grip_band(&env.tokens) } else { 0.0 }; - (self.header, self.chrome, self.rtl) = (header, header + band, env.direction.is_rtl()); + // grip; an OS window's grips lie over its title row. The rule under the title row takes a band of its own. + let sizes = DockSizes::style(&StyleCx::of_env(ui.ctx(), &env)); + let sizes = self.scale.map_or(sizes, |scale| sizes.at_scale(scale)); + (self.header, self.chrome, self.rtl) = (sizes.title_row, sizes.window_chrome(self.native.is_none()), env.direction.is_rtl()); let mount = self.mount(); self.props = self.props.mount(mount); let minimized = self.minimized; @@ -367,10 +400,15 @@ impl<'a> FloatingGroup<'a> { fn mount(&self) -> Mount { // The frame's limits are the body's with the chrome on top. let frame = self.limits.around(Vec2::new(0.0, self.chrome)); - let collapsed = self.collapsed_rect().zip(self.column.map(|column| column.widths)); + // A collapsed column's width stays within its own bounds, a minimized one's within the panels' limits. + let widths = self.column.map(|column| match column.collapsed { + Some(_) => column.widths, + None => (frame.min.x, frame.max.map_or(f32::INFINITY, |max| max.x)), + }); + let held = self.held_rect().zip(widths); let mut overlay = Overlay::floating().movable(true).resizable(!self.minimized).opacity(self.opacity).body_scroll(false); - overlay = if let Some((shown, (least, most))) = collapsed { - // The sides resize a collapsed column's width; its height is its icons'. + overlay = if let Some((shown, (least, most))) = held { + // The sides resize the column's width; its content fixes its height. let height = shown.height(); let edges = if self.minimized { ResizeEdges::NONE } else { ResizeEdges::LEFT.union(ResizeEdges::RIGHT) }; overlay.placed(shown).resize_edges(edges).size_limits(SizeLimits::new(Vec2::new(least, height), Vec2::new(most.max(least), height))) @@ -399,9 +437,9 @@ impl<'a> FloatingGroup<'a> { } } - /// Where the group shows while its column is collapsed: the collapsed column under the chrome, at the top of the - /// rect and against its edge the window keeps to. `None` while the column is expanded. - fn collapsed_rect(&self) -> Option { + /// Where the group shows while its column's content fixes its height ([`WindowColumn::shown`]). `None` while the + /// rect gives the height. + fn held_rect(&self) -> Option { self.column?.shown(self.rect, self.chrome, self.rtl) } @@ -524,14 +562,15 @@ impl Container for FloatingGroup<'_> { fn placement_changed(&mut self, change: &PlacementChange) { let mut change = *change; let fitted = self.column.is_some_and(|column| column.fitted.is_some()); - if let Some(column) = self.column.filter(|column| column.collapsed.is_some()) { - // A resize of the collapsed window sets the column's width; the rect keeps its expanded size. + if let Some(column) = self.column.filter(|column| column.held.is_some()) { + // A resize of the collapsed window sets the column's width; the rect keeps its expanded size. A minimized + // window's rect takes the width and keeps its height. let resized = match change.kind { PlacementKind::Size(_) => true, - PlacementKind::Keyboard => self.collapsed_rect().is_some_and(|shown| change.rect.width() != shown.width()), + PlacementKind::Keyboard => self.held_rect().is_some_and(|shown| change.rect.width() != shown.width()), _ => false, }; - if resized { + if resized && column.collapsed.is_some() { self.collapsed_width = Some(change.rect.width()); } change.rect = column.kept(change.rect, self.rect, self.chrome, self.rtl); diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 4971991ec..6ab02daf3 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -205,7 +205,9 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> { /// Whether Auto-Collapse Iconic Panels is on. #[prop] auto_collapse: bool, - /// The rect the dock may grow within, which bounds how wide its inner edge can make the column. + /// The rect the dock may grow within, which bounds how wide its inner edge can make the column, and the rect its + /// flyouts open in. Unset, the flyouts take the room layers opened there have (`overlay::layer_room`): around a + /// palette window, the work area. #[prop] within: Rect, open: Bind<'a, Option

>, @@ -617,7 +619,7 @@ impl Component for IconicColumn<'_, P> { let (opens, auto_collapse, column) = (self.opens, self.auto_collapse, cx.rect); // The screen side the flyouts open on, mirrored in a right-to-left layout. let right = (opens == Side::End) != cx.flow.is_rtl(); - let within = if self.within.is_positive() { self.within } else { cx.core.ctx.content_rect() }; + let within = if self.within.is_positive() { self.within } else { crate::contract::overlay::layer_room(&cx.core.ctx) }; // The column side of the bounds stops at the column, so a saved width wider than the room keeps that side. let bounds = if right { within.with_min_x(within.min.x.max(column.right())) } else { within.with_max_x(within.max.x.min(column.left())) }; if !bounds.is_positive() { diff --git a/crates/ui-panels/src/docking/native.rs b/crates/ui-panels/src/docking/native.rs index 568e3d011..4ef261889 100644 --- a/crates/ui-panels/src/docking/native.rs +++ b/crates/ui-panels/src/docking/native.rs @@ -46,6 +46,12 @@ pub fn opens_os_windows(ctx: &Context, config: &DockConfig) -> bool { config.native_windows && host.opens_windows() && host.positions_reported() } +/// The display scale the OS window `viewport` lays out at: its monitor's scale with the app's zoom, as the window +/// reported it (`WindowHost::facts`). `None` before it reported one. +pub fn pixels_per_point(ctx: &Context, viewport: ViewportId) -> Option { + WindowHost::of(ctx).facts(viewport)?.scale.map(|scale| scale * ctx.zoom_factor()) +} + /// The window a group of panels with `specs` opens: a document window when any panel is a document, else a tool /// window (a palette level, no taskbar entry). pub fn spec_for(specs: &[PanelSpec]) -> WindowSpec { diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 15a9f1c79..ab44830f8 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -7,7 +7,7 @@ use super::{DragUnit, PanelKey, PanelSpec, scale_widths, width_bounds}; use crate::contract::DropMark; use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored}; -use crate::style::StyleCx; +use crate::style::{RuleKind, RuleWidth, StyleCx}; use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Layout, Node, ZoneSize, node_at, zones}; use egui::{Context, Id, Pos2, Rect, Vec2}; @@ -53,6 +53,12 @@ pub struct DockSizes { pub bar: f32, /// The height of a floating window's title row, which is the bar of the column the window holds. pub title_row: f32, + /// The divider rule a floating window draws under its title row, which the container lays out in a band of its + /// own: the rule's width in whole physical pixels on the window's display ([`Self::pixels_per_point`]). + pub title_rule: RuleWidth, + /// The display scale the sizes that depend on it are for: the running window's, or with [`Self::at_scale`] an OS + /// window's own. + pub pixels_per_point: f32, /// The band a floating window in the app window keeps clear over its title row for its top grip /// (`contract::grip_band`); an OS window keeps none. Every height of a window's body or content is the window's /// height less its chrome ([`Self::window_chrome`]). @@ -107,6 +113,8 @@ impl DockSizes { strip: size.panel_header, bar: size.control.sm, title_row: super::floating::title_row(cx.tokens), + title_rule: cx.rule(RuleKind::Divider).width, + pixels_per_point: cx.frame_ctx().pixels_per_point(), top_band: crate::contract::grip_band(cx.tokens), least: size.panel_header, reach: size.hit.target, @@ -119,10 +127,23 @@ impl DockSizes { } } - /// The height above a floating window's body: its title row and, for a window in the app window (`in_app`), the - /// band over it. + /// The height above a floating window's body: its title row, the rule under it and, for a window in the app + /// window (`in_app`), the band over it. pub fn window_chrome(&self, in_app: bool) -> f32 { - self.title_row + if in_app { self.top_band } else { 0.0 } + self.title_row + self.title_rule.points(self.pixels_per_point) + if in_app { self.top_band } else { 0.0 } + } + + /// The sizes for a window on a display of `pixels_per_point`: an OS window lays out at its own monitor's scale. + #[must_use] + pub fn at_scale(mut self, pixels_per_point: f32) -> Self { + self.pixels_per_point = pixels_per_point; + self + } + + /// The height of a column whose every group is minimized: their tab strips, as the column stacks them. `None` + /// while a group is open. + pub fn minimized_height

(&self, column: &Column

) -> Option { + column.groups.iter().all(|group| group.minimized).then_some(self.strip * column.groups.len() as f32) } /// The width bounds of an expanded column from the limits of its panels. diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 5d3c00ca7..954fc901f 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -187,7 +187,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { struct AreaMemory

{ /// The open flyout when the host binds none. open: Option

, - /// The running move or resize of a floating window. + /// The running resize or keyboard move of a floating window. moving: Option>, /// The least window id above every id the workspaces this area showed held: an undo that brings back an older /// workspace keeps its new windows above it ([`Workspace::raise_window_floor`]). @@ -1270,6 +1270,10 @@ impl Pass<'_, P> { /// 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 every group is minimized shows its title row and their strips at its rect's place and width + /// ([`WindowColumn::minimized`]): its sides resize its width, and its placement keeps its expanded height, so a + /// restore shows it at that height again. + /// /// 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 @@ -1297,6 +1301,14 @@ 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); + // An OS window lays out at its own monitor's scale, which sizes its chrome; one in the app window at the + // main window's. + let scale = opening + .spec + .as_ref() + .and_then(|_| WindowHost::of(&ctx).viewport_of(group_id)) + .and_then(|viewport| native::pixels_per_point(&ctx, viewport)); + let window_sizes = scale.map_or(scene.sizes, |scale| scene.sizes.at_scale(scale)); 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. @@ -1330,6 +1342,8 @@ impl Pass<'_, P> { WindowColumn::collapsed(edge, size, scene.sizes.iconic_bounds(&window.column, &spec_of)) } else if let Some(content) = self.stepped_height(ui, body, &window.column, width, true) { WindowColumn::fitted(edge, Vec2::new(width, content)) + } else if let Some(strips) = scene.sizes.minimized_height(&window.column) { + WindowColumn::minimized(edge, strips) } else { WindowColumn::expanded(edge) } @@ -1343,6 +1357,9 @@ impl Pass<'_, P> { .takes_drops(target, &dropped) .command_scope(DockCommands::SCOPE) .id(group_id); + if let Some(scale) = scale { + group = group.scale(scale); + } group = match opening.spec.clone() { Some(window_spec) => group.native(window_spec), None => group.bounds(scene.bounds), @@ -1363,7 +1380,10 @@ impl Pass<'_, P> { while let Some((command, _)) = body.take_command::() { commands.push(command); } - let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within: scene.bounds, open: open.clone() }; + // An OS window's flyouts and other layers take the room around the window (`overlay::layer_room`); an + // in-app window's stay in the float area. + let within = if opening.spec.is_some() { Rect::NOTHING } else { scene.bounds }; + let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within, open: open.clone() }; self.column(ui, body, &window.column, at); }); self.dock = area_dock; @@ -1373,8 +1393,9 @@ impl Pass<'_, P> { cross_window::accept_cross_window(&ctx); self.report.actions.push(dropped.action); } - // The height above the window's body: the title row, and in the app window the band over it. - let chrome = scene.sizes.window_chrome(opening.spec.is_none()); + // The height above the window's body at its scale: the title row, the rule under it, and in the app window + // the band over it. + let chrome = window_sizes.window_chrome(opening.spec.is_none()); // A resize of a window whose column has steps: the steps it sets, and the window's rect at them. let resized = output .placed @@ -1406,8 +1427,11 @@ impl Pass<'_, P> { let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, 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. + } else if let Some(mut change) = output.placed.filter(|change| change.kind != PlacementKind::Move || change.phase == GesturePhase::Commit) + { + // The layer host shows a window its title row moves under the pointer, so the move reaches the workspace + // once, when it ends: one edit. A collapsed window keeps its edge until then, and the move ends where its + // strip was dropped. let mut keeps = shape.collapsed.map(|_| edge); if change.phase == GesturePhase::Commit && output.collapsed_width.is_none() { (change.rect, keeps) = shape.dropped(change.rect, scene.bounds, scene.rtl); @@ -1470,8 +1494,9 @@ fn split_changes

(from: &Node

, to: &Node

) -> Vec<(Vec, SplitSize)> /// The workspace edit of a floating window's move or resize, the step `phase` of a gesture that `action` /// (`Action::MoveFloating`) places the window by: the gesture runs from the window's `Begin` to its `Commit`, so one -/// drag is one undo step. `moving` holds the gesture and the workspace it began on; `rights` are the panels' -/// permissions with the lock applied, which refuse the move of a locked workspace. +/// drag is one undo step. A move by the title row arrives only as its `Commit`, which sets the place. `moving` holds +/// the gesture and the workspace it began on; `rights` are the panels' permissions with the lock applied, which refuse +/// the move of a locked workspace. fn window_edit( ctx: &Context, current: &Arc>, diff --git a/crates/ui-patterns/src/patterns/dock/area/stories.rs b/crates/ui-patterns/src/patterns/dock/area/stories.rs index 4a5d2abeb..0c2a31a27 100644 --- a/crates/ui-patterns/src/patterns/dock/area/stories.rs +++ b/crates/ui-patterns/src/patterns/dock/area/stories.rs @@ -96,38 +96,45 @@ impl DockPanels for Demo { } /// A canvas between a start dock, a toolbar column one step wide and a column of panels, and an iconic column at the -/// end, with one floating group and one floating window collapsed to icons. -fn workspace() -> Arc> { +/// end, with one floating group, `minimized` or not, and one floating window collapsed to icons. +fn workspace(minimized: bool) -> Arc> { let tools = Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1); let side = Column::new(vec![Group::new(vec![LAYERS, CHANNELS], 0), Group::new(vec![PROPERTIES], 0)]).with_width(SIDE); let mut icons = Column::new(vec![Group::new(vec![SWATCHES], 0)]).with_width(SIDE); icons.iconic = true; let centre = Node::split(Axis::X, SplitSize::Ratio(0.8), Node::tabs(vec![CANVAS], 0), Node::dock(DockEdge::End, vec![icons])); let root = Node::split(Axis::X, SplitSize::FixedFirst(SIDE), Node::dock(DockEdge::Start, vec![tools, side]), centre); - let window = Floating::single(1, vec![HISTORY], 0, WINDOW); + let mut window = Floating::single(1, vec![HISTORY], 0, WINDOW); + window.column.groups[0].minimized = minimized; let mut collapsed = Floating::single(2, vec![NAVIGATOR], 0, COLLAPSED_WINDOW); collapsed.column.iconic = true; Arc::new(Workspace::new(Layout::new(Some(root), vec![window, collapsed]))) } -fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo) -> StoryOutput { +fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo, minimized: bool) -> StoryOutput { /// One spec model for every story, so its revision stays put across frames. static SPECS: LazyLock> = LazyLock::new(|| Tracked::new(DemoSpecs)); - let (workspace, workspace_at) = data.value_at("workspace", workspace()); + let (workspace, workspace_at) = data.value_at("workspace", workspace(minimized)); DockArea::new("Dock", workspace_at.bind(&mut *workspace), &*SPECS, demo, DockConfig::default()).show(ui).into() } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn docked_columns_a_floating_group_and_a_flyout(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }) + dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, false) } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn a_canvas_group_the_host_draws(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: true, host_rows: false }) + dock(ui, data, &mut Demo { canvas_view: true, host_rows: false }, false) } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn host_rows_above_the_dock_rows_in_a_panel_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: false, host_rows: true }) + dock(ui, data, &mut Demo { canvas_view: false, host_rows: true }, false) +} + +/// The floating group minimized: its window shows the title row and the tab strip at its width. +#[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] +fn a_minimized_floating_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, true) } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export.rs b/crates/ui-patterns/src/patterns/form_dialogs/export.rs index 8cb0d5fbd..00c5e6431 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export.rs @@ -388,7 +388,7 @@ const MIN_SIDE: f64 = 1.0; impl ExportOptions { /// The options as the controls can hold them for a document of size `source`: a format the list has (the first - /// when not), a resample method of `methods` (the first when not; any method when `methods` is empty), a quality + /// when not), a resample method of `methods` (Automatic when listed, else the first; any method when `methods` is empty), a quality /// of 1 to 100, and a size the document can take. A linked pixel width keeps its width and /// takes the height from this document (the last export's proportions would stretch another shape); unlinked /// pixels stay as asked when in range; anything out of range becomes 100 percent. @@ -399,10 +399,8 @@ impl ExportOptions { { self.format = first.id.to_owned(); } - if let Some(first) = Resample::ALL.iter().find(|method| methods.contains(method)) - && !methods.contains(&self.resample) - { - self.resample = *first; + if !methods.is_empty() && !methods.contains(&self.resample) { + self.resample = if methods.contains(&default_resample()) { default_resample() } else { methods[0] }; } self.quality = self.quality.clamp(*QUALITY.start(), *QUALITY.end()); let in_range = |side: u32| (MIN_SIDE..=MAX_DOCUMENT_SIDE).contains(&f64::from(side)); diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs index 25d17f695..1a331c3e8 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs @@ -140,8 +140,8 @@ pub struct ExportAsDialog<'a> { /// The formats the list offers. #[prop(into)] formats: Vec, - /// The resample methods the list offers, in the order of [`Resample::ALL`]; all of them when empty. A method the - /// list lacks, remembered or from a preset, opens as the first listed one. + /// The resample methods the list offers, in the order given; all of them when empty. A method the list lacks, + /// remembered or from a preset, opens as Automatic when listed, else as the first listed one. #[prop] methods: Vec, /// The dialog's title in place of "Export As" ("Export As: Layer 1"). @@ -451,7 +451,7 @@ impl HostedExportAs { self } - /// The resample methods the list offers, in the order of [`Resample::ALL`]; all of them when empty + /// The resample methods the list offers, in the order given; all of them when empty /// ([`ExportAsDialog::methods`]). #[must_use] pub fn methods(mut self, methods: Vec) -> Self { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs index f4d9282bd..6f2417c35 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs @@ -8,7 +8,7 @@ use crate::display::{Shade, Text}; use crate::list::{List, ListRow, ThumbAspect}; use crate::patterns::presets::PresetId; use crate::primitives::{ContentPainterCx, StrokeWidth}; -use crate::runtime::env::{Env, Label, UnitKind}; +use crate::runtime::env::{Label, UnitKind}; use crate::style::TypeRole; use crate::tabs::{Tab, TabKind, TabStrip}; use crate::tile_grid::{Tile, TileGrid}; @@ -171,7 +171,7 @@ pub(super) fn show(ui: &mut Ui, session: &Session, values: &DocumentOptions, rea } else { let count = read.units.number(cards.len() as f64, 0..=0); let heading = Label::from(words.presets_heading.fill(&[("n", &count)])); - Text::new(Env::of(ui).view().resolve(&heading).as_str().to_uppercase()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + Text::new(heading).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui); let shown = TileGrid::::new(words.cards.clone()) .card_columns(CARD_COLUMNS) .card() diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs index b1f23fd8c..dfdb6a893 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs @@ -5,7 +5,7 @@ use super::presets::{ BackgroundContents, ColorMode, DocumentOptions, MAX_NAME, MAX_SAVED, Orientation, PIXEL_ASPECTS, RESOLUTION_UNITS, SIZE_UNITS, SQUARE_PIXELS, }; use super::{NewDocumentWords, Read, Session, background_rgb, depth_label, mode_label}; -use crate::buttons::Button; +use crate::buttons::{Button, IconButton}; use crate::choice::{Checkbox, Segmented, Swatch}; use crate::contract::{Bind, Entry, FieldLayout, Gap, MemoProps, Props as _, Show as _, ShowContainer as _, Sizing, Validity, clicked}; use crate::display::{Shade, Text}; @@ -123,16 +123,29 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti PIXEL_ASPECTS.iter().map(|(id, _)| Entry::new((*id).to_owned(), pixel_aspect_label(words, id).clone())).collect(); pixel_aspects.extend(setup.custom_pixel_aspects.iter().map(|(id, name)| Entry::new(id.clone(), name.clone()))); - Text::new(Env::of(ui).view().resolve(&words.preset_details).as_str().to_uppercase()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + Text::new(words.preset_details.clone()).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui); FieldGroup::new(words.preset_details.clone()).gap(Gap::Tight).show(ui, |ui, _| { Field::new(words.name.clone()).layout(FieldLayout::Above).id_salt("name").show(ui, |ui, _| { - let shown = TextField::new(words.name.clone(), Bind::given(values.name.clone())).limit(MAX_NAME).select_on_focus().show(ui); - if let Some(name) = shown.value().cloned() { - values.name = name; - } - if std::mem::take(&mut session.focus_name) { - focus::request(ui.ctx(), FocusTarget::Id(shown.response.id)); - } + Row::new().show(ui, |ui, _| { + let shown = TextField::new(words.name.clone(), Bind::given(values.name.clone())) + .limit(MAX_NAME) + .select_on_focus() + .sizing(Sizing::FillWidth) + .show(ui); + if let Some(name) = shown.value().cloned() { + values.name = name; + } + if std::mem::take(&mut session.focus_name) { + focus::request(ui.ctx(), FocusTarget::Id(shown.response.id)); + } + let title = words.save_preset_title.clone(); + let save = IconButton::new(IconId::new("square_plus")).label(title.clone()).tooltip(title).id_salt("save-preset").show(ui); + if clicked(&save) { + session.naming = Some(proposed_name(read)); + session.name_tried = false; + session.focus_preset_name = true; + } + }); }); let dimension = |ui: &mut Ui, session: &mut Session, side: Side| { @@ -229,22 +242,6 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti } }); }); - Field::new(words.profile.clone()).layout(FieldLayout::Above).id_salt("profile").show(ui, |ui, _| { - let current = values.profile.clone().filter(|profile| others.contains(&profile)); - let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).sizing(Sizing::FillWidth).show(ui); - if let Some(profile) = shown.value().cloned() { - values.profile = profile; - } - }); - Field::new(words.pixel_aspect.clone()).layout(FieldLayout::Above).id_salt("pixel-aspect").show(ui, |ui, _| { - let listed = pixel_aspects.iter().any(|entry| entry.value() == Some(&values.pixel_aspect)); - let current = if listed { values.pixel_aspect.clone() } else { SQUARE_PIXELS.to_owned() }; - let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).sizing(Sizing::FillWidth).show(ui); - if let Some(id) = shown.value().cloned() { - values.pixel_aspect = id; - } - }); - Field::new(words.background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| { Row::new().show(ui, |ui, _| { let kind = BackgroundKind::of(values.background); @@ -265,15 +262,23 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti } }); }); + Field::new(words.profile.clone()).layout(FieldLayout::Above).id_salt("profile").show(ui, |ui, _| { + let current = values.profile.clone().filter(|profile| others.contains(&profile)); + let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).sizing(Sizing::FillWidth).show(ui); + if let Some(profile) = shown.value().cloned() { + values.profile = profile; + } + }); + Field::new(words.pixel_aspect.clone()).layout(FieldLayout::Above).id_salt("pixel-aspect").show(ui, |ui, _| { + let listed = pixel_aspects.iter().any(|entry| entry.value() == Some(&values.pixel_aspect)); + let current = if listed { values.pixel_aspect.clone() } else { SQUARE_PIXELS.to_owned() }; + let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).sizing(Sizing::FillWidth).show(ui); + if let Some(id) = shown.value().cloned() { + values.pixel_aspect = id; + } + }); }); - let save = Button::new(words.save_preset_title.clone()).painted(words.save_preset.clone()).id_salt("save-preset").show(ui); - if clicked(&save) { - session.naming = Some(proposed_name(read)); - session.name_tried = false; - session.focus_preset_name = true; - } - let fitted = values.clone().fitted(); if fitted != *values { *values = fitted; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs b/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs index 6de918a89..84e82f056 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs @@ -3,7 +3,7 @@ use super::FormDialog; use super::size_model::{LinkedSize, MAX_DOCUMENT_SIDE}; -use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _}; +use crate::contract::{Bind, Bracket, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing}; use crate::dialog::{DialogResult, FieldRefusal, HeldAnswer}; use crate::display::Text; use crate::form::{Field, FieldGroup}; @@ -138,11 +138,11 @@ impl Resample { } } - /// The list entries of the methods in `allowed`, in the order of [`Resample::ALL`]; all of them when `allowed` names - /// none. + /// The list entries of the methods in `allowed`, in the order given; all of them in the order of + /// [`Resample::ALL`] when `allowed` names none. pub fn entries(words: &SizingWords, allowed: &[Resample]) -> Vec> { - let listed = |method: &Resample| allowed.is_empty() || allowed.contains(method); - Resample::ALL.iter().copied().filter(listed).map(|method| Entry::new(method, method.label(words))).collect() + let methods = if allowed.is_empty() { &Resample::ALL[..] } else { allowed }; + methods.iter().map(|&method| Entry::new(method, method.label(words))).collect() } } @@ -412,10 +412,11 @@ impl Kit { } } - /// The width and height rows, with the chain beside them when the model draws one. + /// The width and height rows, with the chain bracketed to them when the model draws one. pub(super) fn sides(&self, ui: &mut Ui, size: &mut LinkedSize) { let chain = size.has_chain(); - Row::new().show(ui, |ui, _| { + let row = if chain { Row::new().bracket(if size.is_linked() { Bracket::Linked } else { Bracket::Unlinked }) } else { Row::new() }; + row.show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { self.row(ui, size, Dimension::Width); self.row(ui, size, Dimension::Height); @@ -465,6 +466,7 @@ impl Kit { .range(range.clone()) .unit_label(unit_name.clone()) .number_enabled(editable) + .sizing(Sizing::Content) .id_salt("field") .show(ui); if let Some(number) = shown.edit.value().copied().flatten() { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs b/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs index 2f518ac4a..5b571c966 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs @@ -4,7 +4,7 @@ use super::{Kit, LinkedSize, Resample, SizeForm, SizingOutput, set_size_json, sh use crate::choice::Checkbox; use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; -use crate::form::Field; +use crate::layout_components::Row; use crate::pickers::Select; use crate::runtime::env::{ColumnSize, Label, UnitKind}; use crate::runtime::{keys, overlay}; @@ -155,7 +155,7 @@ pub struct ImageSize<'a> { /// Binds the open state to `open`. #[prop(name = "opened")] open: Option>, - /// The methods the list offers, in the order of [`Resample::ALL`]; all of them when empty. + /// The methods the list offers, in the order given; all of them when empty. #[prop] methods: Vec, /// The bytes one pixel of the flat image takes, for the file size readout: the mode's colour channels at the @@ -220,18 +220,19 @@ impl<'a> ImageSize<'a> { } } } - let on = Checkbox::new(Bind::given(state.size.is_resampling())).label(words.resample.clone()).id_salt("resample").show(ui); - if let Some(on) = on.value().copied() { - state.size.resampling(on); - } - if state.size.is_resampling() { - Field::new(words.resample_method.clone()).id_salt("method").show(ui, |ui, _| { - let picked = Select::new(words.resample_method.clone(), Bind::given(state.method), &entries).show(ui); + // Resample and its method share a row that starts in the control column. + Row::new().id_salt("resample-row").show(ui, |ui, _| { + let on = Checkbox::new(Bind::given(state.size.is_resampling())).label(words.resample.clone()).id_salt("resample").show(ui); + if let Some(on) = on.value().copied() { + state.size.resampling(on); + } + if state.size.is_resampling() { + let picked = Select::new(words.resample_method.clone(), Bind::given(state.method), &entries).id_salt("method").show(ui); if let Some(method) = picked.value().copied() { state.method = method; } - }); - } + } + }); let styles = Checkbox::new(Bind::given(state.scale_styles)) .label(words.scale_styles.clone()) .id_salt("scale-styles") diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 60704d765..c10dbad28 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -65,6 +65,10 @@ struct Bed { } fn bed(layout: Layout) -> Bed { + bed_with(layout, DockConfig::default()) +} + +fn bed_with(layout: Layout, config: DockConfig) -> Bed { let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(layout)))); let actions: Rc>>> = Rc::default(); let second = Rc::new(Cell::new(false)); @@ -77,7 +81,7 @@ fn bed(layout: Layout) -> Bed { let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); let mut panels = Panels; - let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); + let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &specs, &mut panels, config.clone()).show(ui); *held.borrow_mut() = workspace; seen_actions.borrow_mut().extend(out.actions); if let Some(space) = out.float_space { @@ -138,15 +142,13 @@ fn a_tab_dragged_over_a_floating_window_marks_and_joins_the_window() { assert!(window.panels().any(|panel| *panel == SECOND), "the tab joined the window: {:?}", bed.actions.borrow()); } -/// A window's move is the area's own edit, written each pass, and keeps its drag; a host that replaces the workspace -/// ends the drag, and the release drops nothing. +/// A host that replaces the workspace while a window's move runs ends the drag, and the release drops nothing. #[trial] -fn a_replaced_workspace_ends_the_drag_that_the_areas_own_edits_keep() { +fn a_replaced_workspace_ends_a_window_drag() { let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); let by = Vec2::new(-40.0, 30.0); press_and_move(&mut bed.fixture, window_title(), by); - let moved_to = bed.workspace.borrow().layout().floating[0].rect; - assert!(dragging(&bed) && moved_to != WINDOW_AT, "the window moves under its drag: {moved_to:?}"); + assert!(dragging(&bed), "the window's drag runs"); Arc::make_mut(&mut bed.workspace.borrow_mut()).replace(Workspace::new(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0))))); bed.fixture.frame(vec![moved(window_title() + by * 1.25)]); assert!(!dragging(&bed), "the replacement ended the drag"); @@ -175,7 +177,7 @@ fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() { let mut fixture = Fixture::new(move |ui| { let given = held.borrow().clone(); let mut panels = Requesting; - let out = DockArea::new("Given dock", Bind::given(given), &specs, &mut panels, DockConfig::default()).show(ui); + let out = DockArea::new("Given dock", Bind::given(given), &specs, &mut panels, DockConfig::default().title_bar_docks(false)).show(ui); Arc::make_mut(&mut held.borrow_mut()).apply_all(out.actions, false, |_| Permissions::ALL).expect("the area's actions apply"); seen.borrow_mut().extend(out.requested); }); @@ -185,11 +187,40 @@ fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() { let own = |action: &Action| *action == Action::activate(DOCKED) || *action == Action::activate(WINDOW); assert!(!asked.is_empty() && asked.iter().all(own), "each body's request came back: {asked:?}"); assert_eq!(workspace.borrow().layout().floating[0].rect, WINDOW_AT, "nothing moved yet"); - press_and_move(&mut fixture, window_title(), Vec2::new(-40.0, 30.0)); + let by = Vec2::new(-40.0, 30.0); + press_and_move(&mut fixture, window_title(), by); + fixture.frame(vec![release(window_title() + by)]); + fixture.settle(); let moved_to = workspace.borrow().layout().floating[0].rect; assert!(moved_to != WINDOW_AT, "the host's copy took the window's move: {moved_to:?}"); } +/// A drag of a floating window's title row shows the window under the pointer in the frame of each step, in one pass; +/// the workspace takes the move once, on the drop. +#[trial] +fn a_dragged_floating_window_stands_under_the_pointer_in_each_frame_and_moves_on_the_drop() { + let mut bed = bed(with_window(None)); + let from = window_title(); + let step = Vec2::new(-10.0, 8.0); + bed.fixture.frame(vec![moved(from)]); + bed.fixture.frame(vec![press(from)]); + for n in 1..=4 { + let to = WINDOW_AT.translate(step * n as f32); + bed.fixture.frame(vec![moved(from + step * n as f32)]); + let shown = layer_rects(bed.fixture.ctx()); + assert!( + shown.iter().any(|rect| (rect.min - to.min).length() < SLACK && (rect.size() - to.size()).length() < SLACK), + "step {n}: the window stands under the pointer in its frame: {shown:?}, wanted {to:?}" + ); + assert_eq!(bed.fixture.passes(), 1, "step {n}: the frame runs one pass"); + assert_eq!(bed.workspace.borrow().layout().floating[0].rect, WINDOW_AT, "step {n}: the workspace is not written while the move runs"); + } + bed.fixture.frame(vec![release(from + step * 4.0)]); + bed.fixture.settle(); + let rect = bed.workspace.borrow().layout().floating.first().map(|window| window.rect); + assert!(rect.is_some_and(|rect| (rect.min - (WINDOW_AT.min + step * 4.0)).length() < SLACK), "the drop moves the window: {rect:?}"); +} + /// A dock area's first pass leaves a drag running in another area alone. #[trial] fn an_areas_first_pass_keeps_a_running_drag() { @@ -247,11 +278,14 @@ fn a_floating_windows_group_starts_under_the_chrome_the_area_sizes_windows_by() ); } -/// The window's rect while a press at `from` drags by `by`, before the release, which would dock a window moved over -/// the docked group. +/// The window's rect after a press at `from` drags by `by` and releases, in an area whose title-row drags only move a +/// window, so the release docks nothing. fn dragged_from(from: Pos2, by: Vec2) -> Rect { - let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); + let config = DockConfig::default().title_bar_docks(false); + let mut bed = bed_with(with_window(Some(Node::tabs(vec![DOCKED], 0))), config); press_and_move(&mut bed.fixture, from, by); + bed.fixture.frame(vec![release(from + by)]); + bed.fixture.settle(); bed.workspace.borrow().layout().floating[0].rect } @@ -520,6 +554,52 @@ fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_col assert_eq!(bed.workspace.borrow().layout().floating[0].rect, WINDOW_AT, "the expanded rect is unchanged"); } +/// A floating window whose every group is minimized shows its title row and tab strip at its place and width. Its free +/// side resizes its width and not its height, and its rect keeps the expanded height, which the window shows at again +/// once the group is restored. +#[trial] +fn a_window_whose_groups_are_all_minimized_shows_its_strip_and_comes_back_at_its_height() { + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); + let window_layer = |bed: &Bed| { + let layers = layer_rects(bed.fixture.ctx()).into_iter().filter(|rect| rect.contains(window_title())); + layers.min_by(|a, b| a.area().total_cmp(&b.area())).expect("the window's layer holds its title row") + }; + let strip = |bed: &Bed| { + let lists = bed.fixture.by_role(Role::TAB_LIST).into_iter().filter(|list| WINDOW_AT.expand(SLACK).contains_rect(list.rect)); + lists.map(|list| list.rect).next().expect("the window shows its tab strip") + }; + Arc::make_mut(&mut bed.workspace.borrow_mut()) + .apply(Action::set_minimized(WINDOW, true), false, |_| Permissions::ALL) + .expect("the group minimizes"); + bed.fixture.settle(); + let shown = window_layer(&bed); + assert!((shown.bottom() - strip(&bed).bottom()).abs() <= SLACK, "the window ends at its strip: {shown:?}, {:?}", strip(&bed)); + assert!((shown.min - WINDOW_AT.min).length() <= SLACK && (shown.width() - WINDOW_AT.width()).abs() <= SLACK, "at its place and width: {shown:?}"); + + // The window keeps to the end edge; its start side is free, and a press just inside it holds the side's grip. + let side = Pos2::new(shown.left() + 2.0, shown.center().y); + let by = Vec2::new(-40.0, 10.0); + press_and_move(&mut bed.fixture, side, by); + bed.fixture.frame(vec![release(side + by)]); + bed.fixture.settle(); + let resized = window_layer(&bed); + let rect = bed.workspace.borrow().layout().floating[0].rect; + assert!((resized.width() - (shown.width() - by.x)).abs() <= SLACK, "the side resizes the width: {shown:?}, then {resized:?}"); + assert!((resized.height() - shown.height()).abs() <= SLACK, "the height stays the strip's: {resized:?}"); + assert!( + (rect.width() - resized.width()).abs() <= SLACK && rect.height() == WINDOW_AT.height(), + "the rect takes the width and keeps its height: {rect:?}" + ); + + Arc::make_mut(&mut bed.workspace.borrow_mut()) + .apply(Action::set_minimized(WINDOW, false), false, |_| Permissions::ALL) + .expect("the group restores"); + bed.fixture.settle(); + let restored = window_layer(&bed); + assert!((restored.height() - WINDOW_AT.height()).abs() <= SLACK, "restored, the window shows at its height: {restored:?}"); + assert!((restored.width() - resized.width()).abs() <= SLACK, "at the width the side gave it: {restored:?}"); +} + /// A floating collapsed column opens its flyouts towards the room of the float area, away from the edge it keeps to. #[trial] fn a_floating_collapsed_columns_flyout_opens_towards_the_room() { diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 8e0fd047e..2cc0dd9c8 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -4,6 +4,7 @@ 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::Role; use craft_ui::contract::{Bind, BodyCx, DropMark, PlainData, Show as _, ShowContainer as _, SizeLimits, Tracked}; use craft_ui::display::Text; use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec, PanelSpecs}; @@ -11,11 +12,12 @@ use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; use craft_ui::runtime::InstallSpec; use craft_ui::runtime::drag; +use craft_ui::testing::access::AccessTree; use craft_ui::testing::input::key_press; 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 craft_ui_test_kit::windows::{Out, Windows}; use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; use std::sync::Arc; @@ -257,6 +259,10 @@ struct NativeDock { /// 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, + /// The palette's window: the first child window the dock opened. + palette: Option, + /// The tree the palette window's pass produced in the last frame. + palette_tree: Option, } impl NativeDock { @@ -278,7 +284,7 @@ impl NativeDock { windows.child_info(info(true, FLOAT_AT)); let workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette]))); let specs = Tracked::new(Specs { rights: Permissions::ALL, least: false, stepped }); - let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None }; + let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None, palette: None, palette_tree: None }; for _ in 0..3 { dock.frame(vec![]); } @@ -300,7 +306,12 @@ impl NativeDock { let out = self.windows.frame(root, child, |ui| { actions.extend(DockArea::new("Native dock", Bind::bound(workspace), specs, &mut *panels, DockConfig::default()).show(ui).actions); }); - for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT) { + if self.palette.is_none() { + self.palette = out.builders.iter().map(|(viewport, _)| *viewport).find(|viewport| *viewport != ViewportId::ROOT); + } + let palette = self.palette; + self.palette_tree = out.trees.into_iter().find(|(viewport, _)| Some(*viewport) == palette).map(|(_, tree)| tree); + for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| Some(*viewport) == palette) { match self.builder.as_mut() { Some(kept) => { let _ = kept.patch(builder); @@ -308,7 +319,7 @@ impl NativeDock { None => self.builder = Some(builder), } } - let commands = out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect(); + let commands = out.commands.into_iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command).collect(); (actions, commands) } } @@ -717,6 +728,68 @@ fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only() assert_eq!(at.width(), width, "the window keeps the width the OS gave it"); } +/// A native palette whose every group is minimized shrinks to its title row and tab strip at its place and width. +/// The OS resizes its width and never its height: AppKit takes the height as fixed, and the app sends no size back +/// for the width the OS gave it. The model keeps the expanded height throughout, and restored, the window takes that +/// height back at the width it was given. +#[trial] +fn a_minimized_native_palette_keeps_its_width_resizable_and_comes_back_at_its_height() { + for os in [Os::Mac, Os::Windows] { + let mut dock = NativeDock::on(os, Arc::new(FakeSystem::new())); + let expanded = FLOAT_AT.size(); + let mut at = FLOAT_AT; + // The OS follows the window commands of each frame, within the limits in force, 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 mut max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size); + let commands = dock.frame(vec![]).1; + for command in &commands { + match command { + ViewportCommand::MaxInnerSize(limit) => max = Some(*limit), + ViewportCommand::InnerSize(size) => *at = Rect::from_min_size(at.min, max.map_or(*size, |max| size.min(max))), + ViewportCommand::OuterPosition(to) => *at = Rect::from_min_size(*to, at.size()), + _ => {} + } + } + dock.windows.child_info(info(true, *at)); + sent.extend(commands); + } + sent + }; + let recorded = + |dock: &NativeDock| Vec2::from(dock.workspace.layout().floating[0].native.clone().expect("the model records the window").normal.size); + Arc::make_mut(&mut dock.workspace).apply(Action::set_minimized(1, true), false, |_| Permissions::ALL).expect("the group minimizes"); + follow(&mut dock, &mut at, 3); + let strips = at; + assert!(strips.height() < expanded.y / 4.0, "{os:?}: the window shrinks to its title row and strip: {strips:?}"); + if let Err(fit) = fits_exactly(dock.palette_tree.as_ref().expect("the palette ran a pass"), strips.size(), Role::TAB_LIST) { + panic!("{os:?}: the minimized window fits its title row and strip: {fit}"); + } + assert_eq!((strips.min, strips.width()), (FLOAT_AT.min, expanded.x), "{os:?}: at its place and width"); + assert_eq!(recorded(&dock), expanded, "{os:?}: minimized, the model keeps the expanded size"); + let builder = dock.builder.clone().expect("the palette's window opened"); + let (least, most) = (builder.min_inner_size.expect("a least size"), builder.max_inner_size.expect("a most size")); + assert!(least.y == most.y && (least.y - strips.height()).abs() <= 0.5, "{os:?}: the height is fixed: {least:?}..{most:?}, {strips:?}"); + assert!(least.x < most.x, "{os:?}: the width resizes: {least:?}..{most:?}"); + if os == Os::Mac { + assert_eq!(builder.resizable, Some(true), "AppKit resizes the minimized window"); + } + + // The OS widens the window. + let width = expanded.x + 60.0; + at = Rect::from_min_size(at.min, Vec2::new(width, at.height())); + dock.windows.child_info(info(true, at)); + let sent = follow(&mut dock, &mut at, 3); + assert!(!sent.iter().any(|command| matches!(command, ViewportCommand::InnerSize(_))), "{os:?}: no size goes back: {sent:?}"); + assert_eq!(recorded(&dock), Vec2::new(width, expanded.y), "{os:?}: the model takes the width and keeps the expanded height"); + + Arc::make_mut(&mut dock.workspace).apply(Action::set_minimized(1, false), false, |_| Permissions::ALL).expect("the group restores"); + follow(&mut dock, &mut at, 3); + assert_eq!(at, Rect::from_min_size(FLOAT_AT.min, Vec2::new(width, expanded.y)), "{os:?}: restored, the window takes its height back"); + } +} + /// On a display at 125 % (Windows), a click on the double arrow of a native palette collapsed to icons expands its /// column, and the OS window takes its expanded size. #[trial] @@ -751,6 +824,246 @@ fn a_click_on_the_double_arrow_of_a_collapsed_native_palette_expands_it() { assert_eq!(at.size(), FLOAT_AT.size(), "the OS window takes its expanded size"); } +/// Panels whose palette panel's body records, in each of its real runs, the viewport it runs in. +#[derive(Default)] +struct BodyProbe(Vec); + +impl DockPanels for BodyProbe { + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + let ctx = ui.ctx(); + if *panel == 1 && !craft_ui::testing::is_measuring(ctx) { + self.0.push(ctx.viewport_id()); + } + } +} + +/// The scale of the display the collapsed palette trials run on: Windows at 125 %, where the issue was reported. +const COLLAPSED_SCALE: f32 = 1.25; + +/// A native palette collapsed to icons on Windows at 125 %, and the rect its OS window shows the strip at. +fn collapsed_palette() -> (NativeDock, Rect) { + let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new())); + // Both windows report the display at 125 % before the column collapses. + dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE)); + let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, COLLAPSED_SCALE)); + collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + for _ in 0..4 { + collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]); + } + (dock, at) +} + +/// One frame of `dock` with `panels`, `root` events for the main window and `child` events for the palette's window, +/// whose OS window follows its commands at `at`: the frame's output. +fn collapsed_frame(dock: &mut NativeDock, panels: &mut dyn DockPanels, at: &mut Rect, root: Vec, child: Vec) -> Out { + let workspace = &mut dock.workspace; + let specs = &dock.specs; + let out = dock.windows.frame(root, child, |ui| { + let _ = DockArea::new("Native dock", Bind::bound(workspace), specs, &mut *panels, DockConfig::default()).show(ui); + }); + let palette = dock.palette; + let commands: Vec = + out.commands.iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command.clone()).collect(); + *at = placed_by(&commands, *at); + dock.windows.child_info(scaled(true, *at, COLLAPSED_SCALE)); + out +} + +/// The windows the frame showed other than the main window and the palette's: its popup windows. +fn popups(dock: &NativeDock, out: &Out) -> Vec { + out.builders.iter().map(|(viewport, _)| *viewport).filter(|viewport| *viewport != ViewportId::ROOT && Some(*viewport) != dock.palette).collect() +} + +/// The rect of `viewport`'s window in desktop points, as the window system reports it. +fn window_rect(dock: &NativeDock, viewport: ViewportId) -> Rect { + dock.windows.facts(viewport).inner_rect.expect("the window reports its rect") +} + +/// The rect, in its window's points, of the node of `tree` named `name` whose role is `role`. +fn node_rect(tree: &AccessTree, name: &str, role: Role) -> Option { + tree.keys().into_iter().find(|key| tree.name_of(*key) == Some(name) && tree.role_of(*key) == Some(role)).and_then(|key| tree.bounds_of(key)) +} + +/// How far a node's edge may stray from the window's for float rounding: far under a pixel at any scale. +const FIT_ROUNDING: f32 = 0.05; + +/// Whether a window `size` big fits what its pass shows in `tree` exactly: every node lies inside it, and the lowest +/// node of `role` ends at its bottom, within float rounding. +fn fits_exactly(tree: &AccessTree, size: Vec2, role: Role) -> Result<(), String> { + let window = Rect::from_min_size(Pos2::ZERO, size); + let outside: Vec = + tree.keys().into_iter().filter_map(|key| tree.bounds_of(key)).filter(|rect| !window.expand(FIT_ROUNDING).contains_rect(*rect)).collect(); + let bottom = tree.with_role(role).into_iter().filter_map(|key| tree.bounds_of(key)).map(|rect| rect.max.y).fold(f32::MIN, f32::max); + if !outside.is_empty() { + return Err(format!("nodes past the {size:?} window: {outside:?}")); + } + if (bottom - size.y).abs() > FIT_ROUNDING { + return Err(format!("the content ends at {bottom}, the {size:?} window at {}", size.y)); + } + Ok(()) +} + +/// The role and name of each named node of `tree`. +fn nodes(tree: &AccessTree) -> Vec<(Option, String)> { + let mut nodes: Vec<(Option, String)> = + tree.keys().into_iter().filter_map(|key| tree.name_of(key).map(|name| (tree.role_of(key), name.to_owned()))).collect(); + nodes.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); + nodes +} + +/// The tree the frame's pass of `viewport` produced. +fn tree_of_viewport(out: &Out, viewport: ViewportId) -> &AccessTree { + &out.trees.iter().find(|(shown, _)| *shown == viewport).expect("the viewport ran a pass").1 +} + +/// Opens the flyout of the collapsed palette's panel by a click on its icon; returns the flyout's popup window. +fn open_flyout(dock: &mut NativeDock, panels: &mut dyn DockPanels, at: &mut Rect) -> ViewportId { + let out = collapsed_frame(dock, panels, at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let icon = node_rect(tree_of_viewport(&out, palette), PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon").center(); + for events in [vec![moved(icon)], vec![press(icon)], vec![release(icon)]] { + collapsed_frame(dock, panels, at, vec![], events); + } + let out = collapsed_frame(dock, panels, at, vec![], vec![]); + let opened = popups(dock, &out); + assert_eq!(opened.len(), 1, "the click opens one popup window: {opened:?}"); + opened[0] +} + +/// A click on the icon of a native palette collapsed to icons opens the panel's flyout in a popup OS window of its +/// own, beside the strip against its side away from the edge it keeps to, in desktop points: a palette-level window +/// with no taskbar entry that takes the focus. The flyout's body runs in the popup's pass only, as often in each +/// frame, never in the palette's. +#[trial] +fn a_click_on_an_icon_of_a_collapsed_native_palette_opens_its_flyout_in_an_os_window_beside_it() { + let (mut dock, mut at) = collapsed_palette(); + let mut probe = BodyProbe::default(); + let palette = dock.palette.expect("the palette's window opened"); + let strip = nodes(tree_of_viewport(&collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]), palette)); + let popup = open_flyout(&mut dock, &mut probe, &mut at); + let flyout = window_rect(&dock, popup); + let end = at.max.x >= FLOAT_AT.max.x - 1.0; + let outer = if end { (flyout.max.x - at.min.x).abs() } else { (flyout.min.x - at.max.x).abs() }; + assert!(outer <= 0.5, "the flyout stands against the strip's side away from its edge: {flyout:?} beside {at:?}"); + assert!(flyout.min.y >= at.min.y - 0.5 && flyout.min.y < at.max.y, "the flyout's top is level with the strip: {flyout:?}, {at:?}"); + let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]); + let builder = &out.builders.iter().find(|(viewport, _)| *viewport == popup).expect("the popup shows").1; + assert_eq!(builder.window_level, Some(egui::WindowLevel::AlwaysOnTop), "the popup stands as a palette of the active app"); + assert_eq!(builder.taskbar, Some(false), "the popup has no taskbar entry"); + assert_ne!(builder.active, Some(false), "the flyout takes the focus"); + assert_eq!(nodes(tree_of_viewport(&out, palette)), strip, "the palette's window shows none of the flyout"); + assert!(!tree_of_viewport(&out, popup).keys().is_empty(), "the popup window shows the flyout"); + let runs = |probe: &mut BodyProbe, dock: &mut NativeDock, at: &mut Rect| { + probe.0.clear(); + collapsed_frame(dock, probe, at, vec![], vec![]); + std::mem::take(&mut probe.0) + }; + let (first, second) = (runs(&mut probe, &mut dock, &mut at), runs(&mut probe, &mut dock, &mut at)); + assert!(!first.is_empty() && first.iter().all(|viewport| *viewport == popup), "the body runs in the popup's pass: {first:?}"); + assert_eq!(first.len(), second.len(), "the body runs as often in each frame"); +} + +/// The pointer rests on the double arrow of a collapsed native palette past the tooltip delay: the frame that follows. +fn hovered_arrow(dock: &mut NativeDock, at: &mut Rect) -> (Out, Rect) { + let end = at.max.x >= FLOAT_AT.max.x - 1.0 && at.min.x > FLOAT_AT.min.x + 1.0; + let arrow = Pos2::new(if end { at.width() - 4.0 } else { 4.0 }, 4.0); + collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![moved(arrow)]); + // The tooltip shows after its delay, at 60 frames a second. + let frames = (craft_ui::contract::tooltip::DELAY * 60.0).ceil() as usize + 2; + for _ in 0..frames { + collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]); + } + let out = collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let name = tree_of_viewport(&out, palette).keys().into_iter().find_map(|key| { + let tree = tree_of_viewport(&out, palette); + tree.name_of(key) + .filter(|name| name.starts_with("Expand")) + .filter(|_| tree.role_of(key) == Some(Role::BUTTON)) + .and_then(|_| tree.bounds_of(key)) + }); + let arrow_rect = name.expect("the title row shows the double arrow"); + (out, arrow_rect) +} + +/// A native palette collapsed to icons paints the icons of its panels and no text cut by its window, also while the +/// pointer rests on its double arrow: the arrow's tooltip shows outside the strip, not wrapped inside it, and the +/// window fits the title row, its rule and the icons exactly. +#[trial] +fn a_collapsed_native_palette_paints_its_icons_and_no_clipped_text() { + let (mut dock, mut at) = collapsed_palette(); + let (out, _) = hovered_arrow(&mut dock, &mut at); + let palette = dock.palette.expect("the palette's window opened"); + let tree = tree_of_viewport(&out, palette); + let window = Rect::from_min_size(Pos2::ZERO, at.size()); + let icon = node_rect(tree, PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon"); + assert!(window.contains(icon.center()), "the icon shows in the strip: {icon:?} in {window:?}"); + assert!(tree.with_role(Role::TOOLTIP).is_empty(), "no tooltip shows inside the strip"); + if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) { + panic!("the strip's window fits its icons: {fit}"); + } +} + +/// A native palette on a monitor at 1x while the main window is on one at 2x (a laptop with an external display): +/// collapsed to icons, its window fits the title row, the rule under it and the icons exactly at its own scale. +#[trial] +fn a_collapsed_native_palette_on_a_1x_monitor_beside_a_2x_main_window_fits_its_icons_exactly() { + let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new())); + dock.windows.root_info(scaled(true, MAIN_AT, 2.0)); + let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, 1.0)); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + for _ in 0..4 { + let commands = dock.frame(vec![]).1; + at = placed_by(&commands, at); + dock.windows.child_info(scaled(true, at, 1.0)); + } + let tree = dock.palette_tree.as_ref().expect("the palette ran a pass"); + if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) { + panic!("the strip's window fits its icons at its own scale: {fit}"); + } +} + +/// The tooltip of a collapsed native palette's double arrow opens in a popup OS window below the arrow, in desktop +/// points, on one line: the window takes no focus and lets the pointer through to the palette. +#[trial] +fn a_tooltip_from_a_native_palette_opens_in_a_popup_os_window() { + let (mut dock, mut at) = collapsed_palette(); + let (out, arrow) = hovered_arrow(&mut dock, &mut at); + let shown = popups(&dock, &out); + let tip = shown + .iter() + .copied() + .find(|viewport| !tree_of_viewport(&out, *viewport).with_role(Role::TOOLTIP).is_empty()) + .expect("the tooltip shows in a popup window"); + let builder = &out.builders.iter().find(|(viewport, _)| *viewport == tip).expect("the popup shows").1; + assert_eq!(builder.active, Some(false), "the tooltip's window takes no focus"); + assert_eq!(builder.mouse_passthrough, Some(true), "the pointer passes through the tooltip's window"); + let rect = window_rect(&dock, tip); + assert!(rect.min.y >= at.min.y + arrow.max.y - 0.5, "the tooltip stands below the arrow: {rect:?}, arrow {arrow:?} in {at:?}"); + assert!(rect.width() > at.width() && rect.height() < rect.width(), "the tooltip's text runs on one line, wider than the strip: {rect:?}"); +} + +/// A press in the main window closes the flyout a collapsed native palette opened in a popup window. +#[trial] +fn a_press_in_the_main_window_closes_a_native_palettes_flyout() { + let (mut dock, mut at) = collapsed_palette(); + let mut probe = BodyProbe::default(); + let popup = open_flyout(&mut dock, &mut probe, &mut at); + let over = OVER_GROUP - MAIN_AT.min.to_vec2(); + for root in [vec![moved(over)], vec![press(over)], vec![release(over)]] { + collapsed_frame(&mut dock, &mut probe, &mut at, root, vec![]); + } + // The flyout fades out, then its window closes. + let closed = (0..60).any(|_| { + let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]); + !popups(&dock, &out).contains(&popup) + }); + assert!(closed, "the flyout's window closed"); +} + /// Palettes no smaller than `PALETTE_LEAST`. struct Least; diff --git a/crates/ui-patterns/tests/it/form_dialogs/export.rs b/crates/ui-patterns/tests/it/form_dialogs/export.rs index 9e8c91f79..b27455b9f 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/export.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/export.rs @@ -8,6 +8,7 @@ use craft_ui::patterns::form_dialogs::{ HostedFormatOptions, JpegOptions, OutputPathRow, Resample, ScaleRow, ScaleSize, SizeEstimate, }; use craft_ui::runtime::requests::PathRequest; +use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, Vec2}; use std::cell::RefCell; @@ -281,6 +282,36 @@ fn export_as_starts_from_its_remembered_options_and_stores_the_confirmed_ones() assert_eq!(again.scale_all, jpeg.scale_all, "and their Scale All rows"); } +/// Export As lists the app's resample methods in the order it gives, and an unlisted opening method opens as Automatic +/// when listed, else as the first listed one. +#[trial] +fn export_as_lists_resample_methods_in_the_hosts_order() { + let methods = vec![Resample::Bicubic, Resample::BicubicSmoother, Resample::NearestNeighbor, Resample::PreserveDetails]; + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(Vec2::new(1400.0, 1000.0)); + let mut start = ExportOptions::default(); + start.resample = Resample::Lanczos; + host.borrow_mut().open(HostedExportAs::new("Poster", document(), start).methods(methods.clone())); + fixture.idle(10); + let opened = host.borrow_mut().get_mut::().map(|dialog| dialog.options().resample).expect("the dialog is open"); + assert_eq!(opened, Resample::Bicubic, "without Automatic in the list, the first listed method opens"); + + let select = fixture.by_label("Resample").expect("the resample select"); + fixture.access(AccessActionKind::Focus, &select).idle(2); + fixture.key(Key::Space, Modifiers::NONE).idle(3); + let mut options = fixture.by_role(Role::LIST_BOX_OPTION); + options.sort_by(|a, b| a.center().y.total_cmp(&b.center().y)); + let names: Vec = options.iter().map(|option| fixture.tree().name_of(option.node).expect("the option has a name").to_owned()).collect(); + assert_eq!(names.len(), methods.len(), "the list offers the listed methods only"); + assert_eq!( + names, + ["Bicubic (smooth gradients)", "Bicubic Smoother (enlargement)", "Nearest Neighbor (hard edges)", "Preserve Details"], + "the list keeps the host's order" + ); +} + /// Export As with the app's resample methods offers no other: an unlisted opening method opens as the first listed /// one, and automation cannot set an unlisted one. #[trial] diff --git a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs index 91004c210..74646a479 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs @@ -464,3 +464,120 @@ fn image_size_alt_digits_pick_resample_without_typing_into_a_field() { alt_digit(&mut fixture, Key::Num7, "7", alt); assert_eq!(resample(&host), Some(json!("nearestNeighbor")), "Alt+7 picks a listed method"); } + +/// Opens a dialog on a host. +type Opener = fn(&mut DialogHost); + +/// Image Size's and Canvas Size's Width and Height rows (a stack of fields beside the link) show as they measured, at +/// 1x and 1.25x (#15483, #15538): each label sits beside its field, each field and unit select is as tall as a direct +/// row's control (`reference`), and Height's label starts under Width's controls. +#[trial] +fn sizing_dialogs_show_width_and_height_beside_their_labels_at_full_height() { + for scale in [1.0, 1.25] { + let opens: [(Opener, &str); 2] = [ + ( + |host| { + host.open(image_size()); + }, + "Resolution", + ), + ( + |host| { + host.open(canvas_size()); + }, + "Canvas extension color", + ), + ]; + for (open, reference) in opens { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + fixture.pixels_per_point(scale); + open(&mut host.borrow_mut()); + fixture.settle(); + let rect = |name: &str| fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).rect; + let label_of = |name: &str| { + // The field's label names the unit select's group, the number field's parent. + let tree = fixture.tree(); + let mut node = fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).node; + let label = loop { + if let Some(label) = tree.labelled_by_key(node).into_iter().next() { + break label; + } + node = tree.parent_of_key(node).unwrap_or_else(|| panic!("{name} is labelled")); + }; + tree.bounds_of(label).unwrap_or_else(|| panic!("{name}'s label is shown")) + }; + let full = rect(reference).height(); + for name in ["Width", "Height"] { + let (label, field) = (label_of(name), rect(name)); + for part in [field, rect(&format!("{name} unit"))] { + assert!(part.height() >= full - 0.5, "{name}'s controls are a full row tall at {scale}x ({reference}): {part:?} {full}"); + } + assert!(label.max.x <= field.min.x + 0.5, "{name}'s label sits before its field at {scale}x ({reference}): {label:?} {field:?}"); + assert!( + label.min.y < field.max.y && label.max.y > field.min.y, + "{name}'s label is on its field's line at {scale}x: {label:?} {field:?}" + ); + } + let (width, height) = (rect("Width").union(rect("Width unit")), label_of("Height")); + assert!(height.min.y >= width.max.y - 0.5, "Height's row starts under Width's at {scale}x ({reference}): {height:?} {width:?}"); + } + } +} + +/// The horizontal line segments one frame of `fixture` paints, as (y, from x, to x). +fn horizontal_lines(fixture: &mut Fixture) -> Vec<(f32, f32, f32)> { + fixture + .frame_shapes() + .into_iter() + .filter_map(|shape| match shape { + egui::Shape::LineSegment { points: [a, b], .. } if (a.y - b.y).abs() < 0.5 => Some((a.y, a.x.min(b.x), a.x.max(b.x))), + _ => None, + }) + .collect() +} + +/// Image Size as 0.23.1 lays it out: the chain sits halfway between Width's and Height's controls with the bracket +/// drawn from each control to it, and Resample starts in the control column with the method on its line. +#[trial] +fn image_size_brackets_width_and_height_and_starts_resample_in_the_control_column() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(image_size()); + fixture.settle(); + let rect = |fixture: &Fixture, name: &str| fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).rect; + let (width, height, link) = (rect(&fixture, "Width unit"), rect(&fixture, "Height unit"), rect(&fixture, "Maintain aspect ratio")); + let middle = (width.center().y + height.center().y) / 2.0; + assert!((link.center().y - middle).abs() <= 0.5, "the chain sits halfway between Width and Height: {link:?} {middle}"); + let lines = horizontal_lines(&mut fixture); + for (name, row) in [("Width", width), ("Height", height)] { + assert!( + lines.iter().any(|(y, from, to)| (y - row.center().y).abs() <= 1.0 && *from >= row.max.x && *to >= link.center().x - 1.0), + "a tick runs from {name}'s control to the chain: {lines:?}" + ); + } + let (number, check, method) = (rect(&fixture, "Width"), rect(&fixture, "Resample"), rect(&fixture, "Resample method")); + assert!((check.min.x - number.min.x).abs() <= 0.5, "Resample starts at the control column: {check:?} {number:?}"); + assert!( + method.min.x >= check.max.x - 0.5 && method.min.y < check.max.y && method.max.y > check.min.y, + "the method follows Resample on its line: {method:?} {check:?}" + ); +} + +/// Canvas Size draws one rule between its title and Current Size, the title's: the first section's rule above would +/// stand right under it. The rule between the two sections stays. +#[trial] +fn canvas_size_draws_one_rule_under_its_title() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(canvas_size()); + fixture.settle(); + let text = |fixture: &Fixture, text: &str| { + fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted")) + }; + let (title, current, new) = (text(&fixture, "Canvas Size"), text(&fixture, "Current Size"), text(&fixture, "New Size")); + let lines = horizontal_lines(&mut fixture); + let across = |top: f32, bottom: f32| lines.iter().filter(|(y, from, to)| *y > top && *y < bottom && to - from > current.width()).count(); + assert_eq!(across(title.max.y, current.min.y), 1, "one rule between the title and Current Size: {lines:?}"); + assert_eq!(across(current.max.y, new.min.y), 1, "a rule between Current Size and New Size: {lines:?}"); +} diff --git a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs index 81066b702..760b341b0 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs @@ -10,7 +10,7 @@ use egui::{Key, Modifiers, Vec2}; use std::cell::RefCell; use std::rc::Rc; -/// Opens the Save Document Preset pane with the button below the fields, types `name` over the proposed one and saves. +/// Opens the Save Document Preset pane with the icon on the Name row, types `name` over the proposed one and saves. fn save_preset(fixture: &mut Fixture, name: &str) { let save = fixture.by_label("Save Document Preset").expect("the Save Document Preset button"); fixture.click(&save).idle(10); @@ -266,5 +266,38 @@ fn the_new_document_layout_places_presets_and_details_below_the_tabs() { assert!(recent.bottom() <= mode.top(), "tabs go above the details"); assert!((mode.top() - depth.top()).abs() < 1.0, "color mode and depth share a row"); assert!(mode.right() <= depth.left(), "depth follows color mode"); - assert!(mode.bottom() <= save.top() && save.bottom() <= create.top(), "Save Preset is between the fields and the footer"); + assert!(save.bottom() <= create.top(), "Save Preset is above the footer"); +} + +/// The fields run Name, size, Color Mode, Background Contents, then the advanced Color Profile and Pixel Aspect Ratio; the +/// save icon (no text) sits at the end of the Name row. +#[trial] +fn the_new_document_fields_run_background_before_the_advanced_ones_and_save_sits_on_the_name_row() { + let mut options = DocumentOptions::default(); + let mut fixture = Fixture::new(move |ui| { + let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); + }); + fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + let top = |fixture: &Fixture, label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the {label} field")).rect.top(); + let (mode, background) = (top(&fixture, "Color Mode"), top(&fixture, "Background Contents")); + let (profile, aspect) = (top(&fixture, "Color Profile"), top(&fixture, "Pixel Aspect Ratio")); + assert!(mode < background && background < profile && profile < aspect, "Background Contents comes before the advanced fields"); + + let name = fixture.by_label("Name").expect("the Name field").rect; + let save = fixture.by_label("Save Document Preset").expect("the save action").rect; + assert!(save.top() < name.bottom() && name.top() < save.bottom(), "the save icon shares the Name row"); + assert!(name.right() <= save.left(), "the save icon is at the end of the Name field"); + assert!(!fixture.texts().iter().any(|run| run.text.starts_with("Save ")), "the save control is an icon, with no text"); +} + +/// The caption role sets its text in capitals when it paints; the label stays as written. +#[trial] +fn section_captions_paint_in_capitals_and_keep_their_text() { + let mut options = DocumentOptions::default(); + let mut fixture = Fixture::new(move |ui| { + let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); + }); + fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + assert!(shows(&fixture, "PRESET DETAILS"), "the caption paints in capitals"); + assert!(fixture.by_label("Preset Details").is_some(), "the accessible name keeps the text as written"); } diff --git a/crates/ui-test-kit/src/windows.rs b/crates/ui-test-kit/src/windows.rs index 300940877..01fd11af2 100644 --- a/crates/ui-test-kit/src/windows.rs +++ b/crates/ui-test-kit/src/windows.rs @@ -22,8 +22,11 @@ thread_local! { static CHILD_EVENTS: RefCell> = const { RefCell::new(Vec::new()) }; /// The files hovering over and dropped on the child's window in the next child pass. static CHILD_FILES: RefCell<(Vec, Vec)> = const { RefCell::new((Vec::new(), Vec::new())) }; - /// The window facts every child pass reports. + /// The window facts every child opened from the root reports. static CHILD_INFO: RefCell = RefCell::new(ViewportInfo::default()); + /// The window facts of each child opened from another child (a popup window): it opens where its builder puts it + /// and follows its own commands. + static OWN_INFO: RefCell> = const { RefCell::new(Vec::new()) }; /// The window facts the root reports. static ROOT_INFO: RefCell = RefCell::new(ViewportInfo::default()); /// The children whose windows are open: those that ran a pass and are still shown. Like an integration, every pass's @@ -43,14 +46,30 @@ thread_local! { /// Seconds between two frames. const FRAME_SECONDS: f64 = 1.0 / 60.0; +/// Runs `f` on the facts `id` reports: its own for a child opened from another child, else the ones every child +/// opened from the root shares. +fn with_facts(id: ViewportId, f: impl FnOnce(&mut ViewportInfo) -> R) -> R { + let own = OWN_INFO.with(|own| { + let mut own = own.borrow_mut(); + own.iter().position(|(held, _)| *held == id).map(|at| own.swap_remove(at)) + }); + match own { + Some((_, mut info)) => { + let out = f(&mut info); + OWN_INFO.with(|own| own.borrow_mut().push((id, info))); + out + } + None => CHILD_INFO.with(|info| f(&mut info.borrow_mut())), + } +} + /// The window system's answer to a move or a resize: the children's facts follow the commands (the fake window -/// has no decoration, so its inner and outer rects are one). Every child shares one set of facts. +/// has no decoration, so its inner and outer rects are one). The children opened from the root share one set of facts. fn os_applies(id: ViewportId, command: &ViewportCommand) { if id == ViewportId::ROOT { return; } - CHILD_INFO.with(|info| { - let mut info = info.borrow_mut(); + with_facts(id, |info| { let current = info.outer_rect.or(info.inner_rect).unwrap_or_else(|| Rect::from_min_size(Pos2::ZERO, CHILD_SIZE)); let moved = match command { ViewportCommand::OuterPosition(pos) => Rect::from_min_size(*pos, current.size()), @@ -75,26 +94,40 @@ fn keep_commands(output: &FullOutput) { } /// The window facts of every window the integration knows: the root and the children that ran, each with the -/// facts the trial gave it. -fn all_viewports(child: ViewportInfo) -> egui::ViewportIdMap { +/// facts the trial gave it or its own. +fn all_viewports() -> egui::ViewportIdMap { let mut all = egui::ViewportIdMap::default(); all.insert(ViewportId::ROOT, ROOT_INFO.with(|info| info.borrow().clone())); CHILDREN.with(|children| { for id in children.borrow().iter() { - all.insert(*id, child.clone()); + all.insert(*id, with_facts(*id, |info| info.clone())); } }); all } -/// Patches the window of `id` with `builder`, as an integration does before the child's pass: the fields that -/// changed go to the window as commands. The first builder opens the window. -fn patch_window(id: ViewportId, builder: ViewportBuilder) { +/// Patches the window of `ids.this` with `builder`, as an integration does before the child's pass: the fields that +/// changed go to the window as commands. The first builder opens the window; a window opened from another child opens +/// where the builder puts it, with focus unless the builder opens it inactive. +fn patch_window(ids: egui::ViewportIdPair, builder: ViewportBuilder) { + let id = ids.this; let commands = BUILDERS.with(|kept| { let mut kept = kept.borrow_mut(); match kept.iter_mut().find(|(held, _)| *held == id) { Some((_, window)) => window.patch(builder).0, None => { + if ids.parent != ViewportId::ROOT { + let rect = Rect::from_min_size(builder.position.unwrap_or(Pos2::ZERO), builder.inner_size.unwrap_or(CHILD_SIZE)); + let scale = CHILD_INFO.with(|info| info.borrow().native_pixels_per_point); + let info = ViewportInfo { + focused: Some(builder.active.unwrap_or(true)), + inner_rect: Some(rect), + outer_rect: Some(rect), + native_pixels_per_point: scale, + ..ViewportInfo::default() + }; + OWN_INFO.with(|own| own.borrow_mut().push((id, info))); + } kept.push((id, builder)); Vec::new() } @@ -129,12 +162,12 @@ impl egui::DroppedFile for DroppedPath { } fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) { - patch_window(viewport.ids.this, viewport.builder); + patch_window(viewport.ids, viewport.builder); let mut callback = viewport.viewport_ui_cb; let events = CHILD_EVENTS.with(|events| std::mem::take(&mut *events.borrow_mut())); let (hovered_files, dropped) = CHILD_FILES.with(|files| std::mem::take(&mut *files.borrow_mut())); let dropped_files = dropped.into_iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect(); - let mut info = CHILD_INFO.with(|info| info.borrow().clone()); + let mut info = with_facts(viewport.ids.this, |info| info.clone()); info.parent = Some(viewport.ids.parent); let mut input = RawInput { viewport_id: viewport.ids.this, @@ -152,7 +185,8 @@ fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) { children.push(viewport.ids.this); } }); - input.viewports = all_viewports(info); + input.viewports = all_viewports(); + input.viewports.insert(viewport.ids.this, info); let mut output = ctx.run_ui(input, |ui| callback(ui)); output.textures_delta.clear(); keep_commands(&output); @@ -205,6 +239,7 @@ impl Windows { CHILD_EVENTS.with(|events| events.borrow_mut().clear()); CHILD_FILES.with(|files| *files.borrow_mut() = Default::default()); CHILD_INFO.with(|info| *info.borrow_mut() = ViewportInfo::default()); + OWN_INFO.with(|own| own.borrow_mut().clear()); CHILDREN.with(|children| children.borrow_mut().clear()); COMMANDS.with(|kept| kept.borrow_mut().clear()); BUILDERS.with(|kept| kept.borrow_mut().clear()); @@ -217,6 +252,12 @@ impl Windows { CHILD_INFO.with(|kept| *kept.borrow_mut() = info); } + /// The window facts `viewport` reports: its own for a child opened from another child, else those + /// [`child_info`](Self::child_info) gave. + pub fn facts(&self, viewport: ViewportId) -> ViewportInfo { + with_facts(viewport, |info| info.clone()) + } + /// The window facts the root viewport reports from now on. pub fn root_info(&self, info: ViewportInfo) { *self.root_info.borrow_mut() = info; @@ -258,11 +299,15 @@ impl Windows { now.get() })); ROOT_INFO.with(|info| *info.borrow_mut() = self.root_info.borrow().clone()); - input.viewports = all_viewports(CHILD_INFO.with(|info| info.borrow().clone())); + input.viewports = all_viewports(); let mut output = self.ctx.run_ui(input, ui); // A child the frame no longer shows has closed: like an integration, the kit drops its window, so later inputs - // stop listing it (and what its last pass left, such as a modal, stops counting). - CHILDREN.with(|children| children.borrow_mut().retain(|id| output.viewport_output.contains_key(id))); + // stop listing it (and what its last pass left, such as a modal, stops counting), and a window opened again + // opens anew. + let shown = |id: &ViewportId| output.viewport_output.contains_key(id); + CHILDREN.with(|children| children.borrow_mut().retain(shown)); + OWN_INFO.with(|own| own.borrow_mut().retain(|(id, _)| shown(id))); + BUILDERS.with(|kept| kept.borrow_mut().retain(|(id, _)| shown(id))); output.textures_delta.clear(); keep_commands(&output); keep_tree(&mut output, ViewportId::ROOT); diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index 49048d3f2..a869191b7 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -2,7 +2,7 @@ //! lays its children out (6.3). use crate::contract::{ - Access, BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, Gap, HeaderRegion, LabelScheme, + Access, BodyCx, Bracket, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, Gap, HeaderRegion, LabelScheme, LeastWidth, Pad, Role, Scroll, Sizing, ThemeScope, WrapWidth, }; use crate::layout::{BodyLayout, CellAlign, GridFit, RowAlign}; @@ -334,6 +334,14 @@ impl Row { self.props = self.props.least_height(points); self } + + /// Links the labelled rows of the first child to the child after them (width and height to their chain): that + /// child sits halfway between the first and the last row's controls, and `Bracket::Linked` draws the bracket + /// from the controls to it. + pub fn bracket(mut self, bracket: Bracket) -> Self { + self.props = self.props.bracket(bracket); + self + } } impl Default for Row { diff --git a/crates/ui-widgets/src/layout_components/stories.rs b/crates/ui-widgets/src/layout_components/stories.rs index 30359b634..511f7f5db 100644 --- a/crates/ui-widgets/src/layout_components/stories.rs +++ b/crates/ui-widgets/src/layout_components/stories.rs @@ -1,11 +1,13 @@ //! Stories of the layout components `Row`, `Stack` and `Grid`. use super::{Grid, Row, Stack}; -use crate::contract::{Gap, LeastWidth, Pad, Props as _, Show as _, ShowContainer as _, Sizing, WrapWidth}; +use crate::contract::{Bind, Bracket, Gap, LeastWidth, Pad, Props as _, Show as _, ShowContainer as _, Sizing, WrapWidth}; use crate::display::Text; +use crate::form::{Field, FieldGroup}; use crate::layout::{CellAlign, GridFit, empty_cell}; use crate::story_kit::sample::{outlined, words}; use crate::testing::{StoryData, StoryOutput, story}; +use crate::text::{NumberField, link_toggle}; use craft_behavior::ColumnWidth; use egui::Ui; @@ -37,6 +39,29 @@ fn stack_footer(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { outlined(ui, |ui| Stack::new().gap(Gap::Stack).pad(Pad::Regular).footer(|ui, _| words(ui, 2..3)).show(ui, |ui, _| words(ui, 0..2)).into()) } +/// A bracketed row: the width and height of a form linked to their chain, which sits halfway between the two fields' +/// controls. The bracket is drawn while they are linked. +#[story(Row, covers = [], title = "Linked rows")] +fn row_bracket(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let linked = *data.choice("linked", true, &[("Linked", true), ("Unlinked", false)]); + outlined(ui, |ui| { + FieldGroup::new("Size") + .show(ui, |ui, _| { + Row::new().bracket(if linked { Bracket::Linked } else { Bracket::Unlinked }).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + for name in ["Width", "Height"] { + Field::new(name).show(ui, |ui, _| { + NumberField::new(name, Bind::given(Some(800.0))).sizing(Sizing::Content).show(ui); + }); + } + }); + link_toggle("Constrain proportions", Bind::given(linked)).show(ui); + }); + }) + .into() + }) +} + /// A side menu beside a page: the menu as wide as its widest item and as tall as the row, its footer at the bottom. #[story(Stack<'static>, covers = [])] fn stack_fill_height(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { diff --git a/crates/ui-widgets/src/pickers/unit_select.rs b/crates/ui-widgets/src/pickers/unit_select.rs index 7afe8fd2e..ef9418508 100644 --- a/crates/ui-widgets/src/pickers/unit_select.rs +++ b/crates/ui-widgets/src/pickers/unit_select.rs @@ -2,7 +2,8 @@ use super::select::Select; use crate::contract::{ - Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, MeasureCx, Outcome, PaintUi, Props as _, Role, WordSetCx as _, + Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, MeasureCx, Outcome, PaintUi, Props as _, Resolved, Role, Sizing, + WordSetCx as _, }; use crate::runtime::env::{Label, UnitKind, Units}; use crate::style::{ComponentStyle, StyleCx}; @@ -14,7 +15,7 @@ use std::ops::{Deref, RangeInclusive}; #[cfg(feature = "suite")] pub(crate) mod stories; -/// The style of a unit select: the gap between the field and the select, and the number field's width. +/// The style of a unit select: the gap between the field and the select, and the number field's widths. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct UnitSelectStyle { @@ -22,6 +23,8 @@ pub struct UnitSelectStyle { metrics: Metrics, /// The width of the number field; the select has the room after it. number: f32, + /// The width of the number field of a content-sized unit select: one number cell. + cell: f32, } /// The output of a unit select: the number's edit, the unit's edit when a unit was picked, and the number field's @@ -63,6 +66,10 @@ impl Outcome for UnitSelectOutput { /// (its spellings: "12 mm") and shows its number with, and the kind sets the digits and the step of the number; the /// select names the unit, so the field shows the number alone. The number itself is the field's value, and the unit /// goes to its own binding, so the app converts the number when the unit changes. +/// +/// Content-sized (`Sizing::Content`), the field is one number cell wide and the select as wide as its longest unit, +/// as a compact form's rows show them (Image Size); otherwise the field takes a field's width and the select the room +/// after it. #[derive(crate::contract::Component, crate::contract::Props)] #[component] pub struct UnitSelect<'a> { @@ -139,7 +146,7 @@ impl Component for UnitSelect<'_> { fn style(cx: &StyleCx<'_>, _: UnitSelectStyleKey) -> UnitSelectStyle { let control = cx.control(); - UnitSelectStyle { metrics: Metrics::new().gap(control.gap), number: control.field } + UnitSelectStyle { metrics: Metrics::new().gap(control.gap), number: control.field, cell: control.number } } fn sense(&self) -> Sense { @@ -149,10 +156,10 @@ impl Component for UnitSelect<'_> { fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { let group = cx.label(); let mut number = self.number(group.clone(), shown_of(cx.value()), None); - let mut select = Select::new(self.select_name(&group), Bind::::given(Mixed::Mixed), self.units); + let mut select = sized(Select::new(self.select_name(&group), Bind::::given(Mixed::Mixed), self.units), cx.resolved); let number = cx.child("number", &mut number, Proposal::Ideal); let select = cx.child("unit", &mut select, Proposal::Ideal); - Vec2::new(cx.style.number + cx.gap() + select.x, number.y.max(select.y)) + Vec2::new(number_width(cx.resolved, cx.style) + cx.gap() + select.x, number.y.max(select.y)) } fn bind(&mut self) -> Option>> { @@ -164,7 +171,7 @@ impl Component for UnitSelect<'_> { /// is adopted as the component's own. fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let group = cx.label(); - let (number_rect, select_rect) = arrange(cx.rect.size(), cx.style.metrics.gap, cx.style.number); + let (number_rect, select_rect) = arrange(cx.rect.size(), cx.style.metrics.gap, number_width(cx.resolved, cx.style)); let flow = Flow::new(cx.rect, cx.flow.is_rtl()); let place = |logical: Rect| flow.to_physical(logical.translate(cx.rect.min.to_vec2())); let kind = match self.unit.reborrow().get() { @@ -177,7 +184,7 @@ impl Component for UnitSelect<'_> { let number = ui.child("number", place(number_rect), self.number(group.clone(), shown, kind.map(|kind| (kind, &units)))); cx.adopt(&number, &start, |value, mine| *mine = *value); self.out_of_range = number.out_of_range; - let select = Select::new(self.select_name(&group), self.unit.reborrowed(), self.units); + let select = sized(Select::new(self.select_name(&group), self.unit.reborrowed(), self.units), cx.resolved); self.unit_event = ui.child("unit", place(select_rect), select).events; } @@ -186,6 +193,16 @@ impl Component for UnitSelect<'_> { } } +/// The unit select's select, content-sized as the unit select is: as wide as its longest unit. +fn sized<'s>(select: Select<'s, UnitKind>, resolved: &Resolved<'_>) -> Select<'s, UnitKind> { + if resolved.sizing() == Some(Sizing::Content) { select.sizing(Sizing::Content) } else { select } +} + +/// The width of the number field: one number cell in a content-sized unit select, a field's width otherwise. +fn number_width(resolved: &Resolved<'_>, style: &UnitSelectStyle) -> f32 { + if resolved.sizing() == Some(Sizing::Content) { style.cell } else { style.number } +} + /// The number field's and the select's rects in a room of `size`, in logical coordinates from the start edge: the /// number field first, the select in the room after it. fn arrange(size: Vec2, gap: f32, number_width: f32) -> (Rect, Rect) { diff --git a/crates/ui-widgets/src/pickers/unit_select/stories.rs b/crates/ui-widgets/src/pickers/unit_select/stories.rs index 6cd8a11d8..316d64226 100644 --- a/crates/ui-widgets/src/pickers/unit_select/stories.rs +++ b/crates/ui-widgets/src/pickers/unit_select/stories.rs @@ -1,7 +1,7 @@ //! Stories of `UnitSelect`. use super::UnitSelect; -use crate::contract::{Bind, Entry, Show as _, Validity}; +use crate::contract::{Bind, Entry, Props as _, Show as _, Sizing, Validity}; use crate::runtime::env::{Message, UnitKind}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::Mixed; @@ -19,6 +19,16 @@ fn unit_select(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { UnitSelect::new("Width", width_at.bind(width), Bind::bound(unit), &units).show(ui).into() } +/// Content-sized, as a compact form's rows show it: the field one number cell wide, the select as wide as its +/// longest unit. +#[story(UnitSelect<'static>, covers = [], drive = Drive::Type("42"))] +fn unit_select_content_sized(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let units = units(); + let (width, width_at) = data.value_at("compact_width_and_unit", (Some(210.0), UnitKind::Millimetres)); + let (width, unit) = (&mut width.0, &mut width.1); + UnitSelect::new("Width", width_at.bind(width), Bind::bound(unit), &units).sizing(Sizing::Content).show(ui).into() +} + #[story(UnitSelect<'static>, covers = [Mixed], drive = Drive::Never)] fn unit_select_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let units = units(); diff --git a/crates/ui-widgets/tests/it/label/bracket.rs b/crates/ui-widgets/tests/it/label/bracket.rs new file mode 100644 index 000000000..107d7e8d8 --- /dev/null +++ b/crates/ui-widgets/tests/it/label/bracket.rs @@ -0,0 +1,116 @@ +//! A bracketed row and the row a check box starts: the chain halfway between its fields with the bracket drawn to +//! their controls, and a check box that starts a row of a form in the form's control column. + +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, Bracket, Entry, Props as _, Show as _, ShowContainer as _}; +use craft_ui::display::Text; +use craft_ui::form::{Field, FieldGroup}; +use craft_ui::layout_components::{Row, Stack}; +use craft_ui::pickers::{Select, UnitSelect}; +use craft_ui::runtime::env::UnitKind; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::{NumberField, link_toggle}; +use egui::{Rect, Shape, Vec2}; + +/// How far two edges may differ and still line up, in points. +const SLACK: f32 = 0.5; + +fn control(fixture: &Fixture, name: &str) -> Rect { + fixture.by_label(name).unwrap_or_else(|| panic!("{name:?} names its control")).rect +} + +/// The horizontal line segments of one frame, as (y, from x, to x). +fn ticks(fixture: &mut Fixture) -> Vec<(f32, f32, f32)> { + fixture + .frame_shapes() + .into_iter() + .filter_map(|shape| match shape { + Shape::LineSegment { points: [a, b], .. } if (a.y - b.y).abs() < SLACK => Some((a.y, a.x.min(b.x), a.x.max(b.x))), + _ => None, + }) + .collect() +} + +/// A form with Width and Height (unit selects) stacked in a row with `bracket`, beside their link. +fn linked(bracket: Bracket) -> Fixture { + let units = [Entry::new(UnitKind::Pixels, "Pixels"), Entry::new(UnitKind::Percent, "Percent")]; + Fixture::new(move |ui| { + Row::new().show(ui, |ui, _| { + FieldGroup::new("Image size").show(ui, |ui, _| { + Row::new().bracket(bracket).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + for name in ["Width", "Height"] { + Field::new(name).show(ui, |ui, _| { + UnitSelect::new(name, Bind::given(Some(8.0)), Bind::given(UnitKind::Pixels), &units) + .unit_label(format!("{name} unit")) + .show(ui); + }); + } + }); + link_toggle("Link", Bind::given(bracket == Bracket::Linked)).show(ui); + }); + }); + }); + }) +} + +/// A linked bracket runs from the end of Width's and Height's controls to the chain's centre line, at each control's +/// centre, and the chain sits halfway between the two; unlinked, the chain keeps its place and no bracket is drawn. +/// At 1x and 1.25x. +#[trial] +fn a_bracketed_row_centres_its_chain_between_the_rows_and_draws_the_bracket_while_linked() { + for scale in [1.0, 1.25] { + for bracket in [Bracket::Linked, Bracket::Unlinked] { + let mut fixture = linked(bracket); + fixture.room(Vec2::new(1000.0, 600.0)).pixels_per_point(scale); + fixture.settle(); + let (width, height, link) = (control(&fixture, "Width unit"), control(&fixture, "Height unit"), control(&fixture, "Link")); + let middle = (width.center().y + height.center().y) / 2.0; + assert!((link.center().y - middle).abs() <= SLACK, "{bracket:?} at {scale}x: the chain sits halfway between the rows: {link:?} {middle}"); + let drawn = ticks(&mut fixture); + for (name, row) in [("Width", width), ("Height", height)] { + let tick = drawn.iter().find(|(y, from, to)| (y - row.center().y).abs() <= 1.0 && *from >= row.max.x && *to >= link.center().x - 1.0); + match bracket { + Bracket::Linked => { + assert!(tick.is_some(), "at {scale}x a tick runs from {name}'s control to the chain: {drawn:?} {row:?} {link:?}"); + } + _ => assert!(tick.is_none(), "unlinked at {scale}x, no tick on {name}'s row: {tick:?}"), + } + } + } + } +} + +/// A check box that starts a row of a form (Resample with its method after it) starts in the form's control column; +/// one after another child of the row stays where the row puts it. +#[trial] +fn a_check_box_that_starts_a_row_of_a_form_starts_in_the_control_column() { + let methods = [Entry::new(0_u8, "Automatic"), Entry::new(1_u8, "Bicubic")]; + let mut fixture = Fixture::new(move |ui| { + Row::new().show(ui, |ui, _| { + FieldGroup::new("Size").show(ui, |ui, _| { + Field::new("Resolution").show(ui, |ui, _| { + NumberField::new("Resolution", Bind::given(Some(72.0))).show(ui); + }); + Row::new().show(ui, |ui, _| { + Checkbox::new(Bind::given(true)).label("Resample").show(ui); + Select::new("Method", Bind::given(0_u8), &methods).show(ui); + }); + Row::new().show(ui, |ui, _| { + Text::new("Then").show(ui); + Checkbox::new(Bind::given(false)).label("Second").show(ui); + }); + }); + }); + }); + fixture.room(Vec2::new(1000.0, 600.0)); + fixture.settle(); + let (field, check, method) = (control(&fixture, "Resolution"), control(&fixture, "Resample"), control(&fixture, "Method")); + assert!((check.min.x - field.min.x).abs() <= SLACK, "the check box starts at the form's control edge: {check:?} {field:?}"); + assert!( + method.min.x >= check.max.x - SLACK && method.min.y < check.max.y && method.max.y > check.min.y, + "the method follows on its line: {method:?} {check:?}" + ); + let second = control(&fixture, "Second"); + assert!(second.min.x < field.min.x, "a check box after another child of the row is not moved to the control column: {second:?} {field:?}"); +} diff --git a/crates/ui-widgets/tests/it/label/mod.rs b/crates/ui-widgets/tests/it/label/mod.rs index 6facfa093..00b7f7256 100644 --- a/crates/ui-widgets/tests/it/label/mod.rs +++ b/crates/ui-widgets/tests/it/label/mod.rs @@ -2,6 +2,7 @@ pub(crate) mod align; pub(crate) mod baseline; +pub(crate) mod bracket; pub(crate) mod caption; pub mod group; pub(crate) mod hit; diff --git a/crates/ui-widgets/tests/it/label/reach.rs b/crates/ui-widgets/tests/it/label/reach.rs index 9ba55faf3..6d03c7651 100644 --- a/crates/ui-widgets/tests/it/label/reach.rs +++ b/crates/ui-widgets/tests/it/label/reach.rs @@ -8,10 +8,11 @@ use craft_ui::buttons::Button; use craft_ui::contract::{Bind, ContainerProps, Entry, LabelScheme, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::{Row, Stack}; +use craft_ui::pickers::UnitSelect; use craft_ui::runtime::env::UnitKind; use craft_ui::testing::{Fixture, Frames, last_pass_measuring_runs, trial}; -use craft_ui::text::{NumberField, NumberPick}; -use egui::Rect; +use craft_ui::text::{NumberField, NumberPick, link_toggle}; +use egui::{Rect, Vec2}; use std::cell::RefCell; /// How far two edges may differ and still line up, in points. @@ -194,3 +195,56 @@ fn a_field_before_the_groups_widest_value_shows_at_its_width() { let runs = last_pass_measuring_runs(fixture.ctx()); assert!(runs.is_empty(), "a settled frame takes the kept measurements: {runs:?}"); } + +/// A field `caption` holding a unit select, its select named "`caption` unit". +fn unit(ui: &mut egui::Ui, caption: &'static str, units: &[Entry]) { + Field::new(caption).show(ui, |ui, _| { + UnitSelect::new(caption, Bind::given(Some(8.0)), Bind::given(UnitKind::Pixels), units).unit_label(format!("{caption} unit")).show(ui); + }); +} + +/// In a content-sized form, the labelled rows of a stack inside a row (Image Size's Width and Height beside their +/// link) take the placement their measure took, at the form's final label column: each label sits beside its +/// controls, each control is as tall as a direct row's, and the next row starts under the one before. At 1x and 1.25x. +#[trial] +fn a_stack_of_labelled_rows_in_a_row_lays_out_as_it_measured() { + for scale in [1.0, 1.25] { + let units = [Entry::new(UnitKind::Pixels, "Pixels"), Entry::new(UnitKind::Percent, "Percent")]; + let mut fixture = Fixture::new(move |ui| { + Row::new().show(ui, |ui, _| { + FieldGroup::new("Image size").show(ui, |ui, _| { + number(ui, "Size"); + Row::new().show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + unit(ui, "Width", &units); + unit(ui, "Height", &units); + }); + link_toggle("Link", Bind::given(true)).show(ui); + }); + unit(ui, "Resolution", &units); + number(ui, "Canvas extension color"); + }); + }); + }); + fixture.room(Vec2::new(1400.0, 1000.0)).pixels_per_point(scale); + fixture.settle(); + let reference = control(&fixture, "Resolution"); + let mut above = f32::NEG_INFINITY; + for name in ["Width", "Height", "Resolution"] { + let (label, field, select) = (caption(&fixture, name), control(&fixture, name), control(&fixture, &format!("{name} unit"))); + for part in [field, select] { + assert!(part.height() >= reference.height() - SLACK, "{name}'s controls are a full row tall at {scale}x: {part:?} {reference:?}"); + } + assert!(label.max.x <= field.min.x + SLACK, "{name}'s label sits before its field at {scale}x: {label:?} {field:?}"); + assert!( + label.min.y < field.max.y && label.max.y > field.min.y, + "{name}'s label sits on its field's line at {scale}x: {label:?} {field:?}" + ); + assert!(label.min.y >= above - SLACK, "{name}'s row starts under the row before at {scale}x: {label:?} {above}"); + above = field.max.y.max(select.max.y); + } + let link = fixture.by_label("Link").expect("the link toggle is shown").rect; + let select = control(&fixture, "Width unit"); + assert!(link.min.x >= select.max.x - SLACK, "the link starts clear of the selects at {scale}x: {link:?} {select:?}"); + } +} diff --git a/docs/contract-api.md b/docs/contract-api.md index db116da2b..53fbdcdd2 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -1974,6 +1974,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn cells(self, cells: CellAlign) -> Self`. A `Grid` with `cells`; any other layout is unchanged. - `pub fn wrap(self, on: bool) -> Self`. A `Row` that wraps; any other layout is unchanged. - `pub fn align(self, align: RowAlign) -> Self`. A `Row` with `align`; any other layout is unchanged. +- `craft_ui::contract::Bracket`: `pub enum Bracket { Linked, Unlinked }`. The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. - `craft_ui::contract::CellWidth`: `pub type CellWidth = ColumnWidth`. The width of a caption's cell. - `craft_ui::contract::Collapse`: `pub struct Collapse { pub initially_open: bool, pub animated: bool }`. Collapse configuration. @@ -2056,7 +2057,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::Common`: `pub struct Common { pub label: Label, pub tooltip: Option, pub description: Option, pub selected: Option }`. What every component carries: the props the pipeline reads at step 1. - `pub const fn new() -> Common`. A `Common` with every prop unset, which the derive's constructors start from. - `craft_ui::contract::Component`: re-export of `craft_ui_macros::Component` (outside these crates). -- `craft_ui::contract::ContainerProps`: `pub struct ContainerProps { pub mount: Mount, pub surface: Option, pub pad: Pad, pub pad_edges: PadEdges, pub sizing: Sizing, pub content_in_bar: bool, pub room_height: Option, pub layout: BodyLayout, pub header: Option, pub scroll: Option, pub footer: Option, pub end: Option, pub help: Option