mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-22 18:41:27 +01:00
Merge pull request #2589 from aiongg/memo-stack
Memoized views: derived values; dock, Layers, menu and tool rail keys without model walks
This commit is contained in:
126 files changed
+2813
-1175
No files matched your search
Generated
+4
@@ -3118,6 +3118,8 @@ dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
"craft-settings",
|
||||
"craft-tracked",
|
||||
"craft-ui-macros",
|
||||
"craft-xml",
|
||||
"egui",
|
||||
"serde",
|
||||
@@ -4174,6 +4176,8 @@ name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
"craft-ui-macros",
|
||||
"ecolor",
|
||||
"log",
|
||||
"proptest",
|
||||
|
||||
@@ -46,7 +46,7 @@ pub enum CursorIcon {
|
||||
}
|
||||
|
||||
/// An icon's egui-free key (5.2), so plain data such as [`PaintedCursor::Tool`] names icons without egui.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui_macros::PlainData)]
|
||||
pub struct IconId(Cow<'static, str>);
|
||||
|
||||
impl IconId {
|
||||
|
||||
@@ -330,6 +330,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
.iter()
|
||||
.map(|w| Floating { column: column_shape(&w.column), rect: Rect::ZERO, native: None, edge: None, ..w.clone() })
|
||||
.collect(),
|
||||
next_window: self.next_window,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -512,9 +513,13 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
return Err(DockError::InvalidGeometry);
|
||||
}
|
||||
// A window's width is its rect's; only a collapsed column keeps to an edge of its own.
|
||||
let window = Floating::new(Column { width: None, ..moving.column }, rect);
|
||||
let id = match moving.id {
|
||||
Some(id) => id,
|
||||
None => self.fresh_window_id(),
|
||||
};
|
||||
let window = Floating::new(id, Column { width: None, ..moving.column }, rect);
|
||||
let edge = edge.filter(|_| window.column.iconic);
|
||||
self.floating.push(Floating { id: moving.id.unwrap_or(window.id), edge, ..window });
|
||||
self.floating.push(Floating { edge, ..window });
|
||||
Ok(())
|
||||
}
|
||||
Target::NewDock { side } => {
|
||||
|
||||
@@ -19,26 +19,91 @@ use super::{
|
||||
};
|
||||
|
||||
/// The panels of a workspace: a docked tree plus floating windows. Every panel occurs once.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
///
|
||||
/// Equality compares the tree and the windows, not the window id counter.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(from = "Saved<P>", bound(deserialize = "P: serde::Deserialize<'de>"))]
|
||||
#[non_exhaustive]
|
||||
pub struct Layout<P> {
|
||||
/// The docked layout; `None` when nothing is docked.
|
||||
pub root: Option<Node<P>>,
|
||||
/// Floating windows, with unique ids.
|
||||
#[serde(deserialize_with = "super::node::floating_serde::unique_ids")]
|
||||
pub floating: Vec<Floating<P>>,
|
||||
/// The least id [`Self::fresh_window_id`] may draw: above every id the layout held when it was built or loaded,
|
||||
/// every id it has drawn since, and every id the layouts it replaced held. Not saved.
|
||||
#[serde(skip)]
|
||||
pub(super) next_window: u64,
|
||||
}
|
||||
|
||||
/// A layout as saved: the tree and the windows, which load with unique ids.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(bound(deserialize = "P: serde::Deserialize<'de>"))]
|
||||
struct Saved<P> {
|
||||
root: Option<Node<P>>,
|
||||
#[serde(deserialize_with = "super::node::floating_serde::unique_ids")]
|
||||
floating: Vec<Floating<P>>,
|
||||
}
|
||||
|
||||
impl<P> From<Saved<P>> for Layout<P> {
|
||||
fn from(saved: Saved<P>) -> Self {
|
||||
Layout::new(saved.root, saved.floating)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: PartialEq> PartialEq for Layout<P> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.root == other.root && self.floating == other.floating
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> Default for Layout<P> {
|
||||
fn default() -> Self {
|
||||
Self { root: None, floating: Vec::new() }
|
||||
Self { root: None, floating: Vec::new(), next_window: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> Layout<P> {
|
||||
/// A layout with the docked tree `root` and the floating windows `floating`.
|
||||
/// A layout with the docked tree `root` and the floating windows `floating`. New windows take ids above every id
|
||||
/// in `floating`.
|
||||
pub fn new(root: Option<Node<P>>, floating: Vec<Floating<P>>) -> Self {
|
||||
Self { root, floating }
|
||||
let mut layout = Self { root, floating, next_window: 0 };
|
||||
layout.next_window = layout.window_floor();
|
||||
layout
|
||||
}
|
||||
|
||||
/// An id for a new floating window: above every window id the layout held when it was built or loaded and every
|
||||
/// id it has drawn since, so an id, and the OS window it names, is never given to another window while the layout
|
||||
/// lives. Should those ids run out (a window holds `u64::MAX`), the least id no window holds.
|
||||
pub fn fresh_window_id(&mut self) -> u64 {
|
||||
let floor = self.window_floor();
|
||||
let held = |id: u64| self.floating.iter().any(|window| window.id == id);
|
||||
let id = if held(floor) { (0..=u64::MAX).find(|id| !held(*id)).unwrap_or(floor) } else { floor };
|
||||
self.next_window = self.next_window.max(id.saturating_add(1));
|
||||
id
|
||||
}
|
||||
|
||||
/// The least id above every id the layout holds or has held.
|
||||
pub fn window_floor(&self) -> u64 {
|
||||
self.floating.iter().map(|window| window.id.saturating_add(1)).fold(self.next_window, u64::max)
|
||||
}
|
||||
|
||||
/// Keeps new window ids at or above `floor`. Returns whether the counter moved.
|
||||
pub(super) fn raise_window_floor(&mut self, floor: u64) -> bool {
|
||||
let raised = floor > self.next_window;
|
||||
self.next_window = self.next_window.max(floor);
|
||||
raised
|
||||
}
|
||||
|
||||
/// Takes the windows of `incoming`, which replaces this layout, onto ids this layout never gave out: a window
|
||||
/// whose id is below this layout's floor gets a fresh one, and the counter keeps growing from both.
|
||||
pub(super) fn hand_ids_to(&self, incoming: &mut Layout<P>) {
|
||||
let floor = self.window_floor();
|
||||
incoming.next_window = incoming.window_floor().max(floor);
|
||||
let stale: Vec<usize> = incoming.floating.iter().enumerate().filter(|(_, window)| window.id < floor).map(|(at, _)| at).collect();
|
||||
for at in stale {
|
||||
let id = incoming.fresh_window_id();
|
||||
incoming.floating[at].id = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,16 +68,17 @@ pub struct StackEntry<P> {
|
||||
///
|
||||
/// Serde reads every saved shape (see `floating_serde`); a window that is one expanded column with one plain group
|
||||
/// and no native rect writes the v1 shape `{panels, active, rect}`, so older builds can read files that use no
|
||||
/// newer feature. Every window writes its `id`; a window read without one gets a fresh one.
|
||||
/// newer feature. Every window writes its `id`; a window read without one, or with one an earlier window took, gets an
|
||||
/// id above every saved one.
|
||||
///
|
||||
/// Equality ignores `id`: two windows with the same contents and place are the same layout.
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct Floating<P> {
|
||||
/// Names the window across panel moves, and its OS window.
|
||||
/// Unique within a layout: [`Self::new`] draws a fresh id, [`Self::with_id`] sets one,
|
||||
/// loading keeps the saved id (or draws one when it is missing or taken), and merging
|
||||
/// windows keeps the receiving window's.
|
||||
/// Unique within a layout: [`Self::new`] and [`Self::with_id`] take one from the caller (a window a layout adds
|
||||
/// takes [`Layout::fresh_window_id`](super::Layout::fresh_window_id)), loading keeps the saved id (or gives one
|
||||
/// above every saved id when it is missing or taken), and merging windows keeps the receiving window's.
|
||||
pub id: u64,
|
||||
/// The window's groups, top to bottom, and its collapsed state. Its `width` is unused: the window's width is
|
||||
/// `rect`'s.
|
||||
@@ -126,35 +127,20 @@ impl<P> StackEntry<P> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A window id no other window of this process has drawn, from a random start so ids saved
|
||||
/// by earlier runs are unlikely to repeat.
|
||||
pub(super) fn fresh_window_id() -> u64 {
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
use std::sync::{
|
||||
OnceLock,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
static NEXT: OnceLock<AtomicU64> = OnceLock::new();
|
||||
let next = NEXT.get_or_init(|| AtomicU64::new(std::collections::hash_map::RandomState::new().build_hasher().finish() >> 1));
|
||||
next.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
impl<P> Floating<P> {
|
||||
/// A window holding `column`. Each call makes a new window, with a fresh [`Self::id`]: build
|
||||
/// a layout once and keep it, or give its windows ids with [`Self::with_id`]. A layout
|
||||
/// built anew each frame without them opens new OS windows each frame.
|
||||
pub fn new(column: Column<P>, rect: Rect) -> Self {
|
||||
Self { id: fresh_window_id(), column, rect, native: None, edge: None }
|
||||
/// The window `id` holding `column`. Ids are unique within a layout; a window added to a live layout takes its id
|
||||
/// from [`Layout::fresh_window_id`](super::Layout::fresh_window_id). The same id is the same window, and the same
|
||||
/// OS window, on every frame.
|
||||
pub fn new(id: u64, column: Column<P>, rect: Rect) -> Self {
|
||||
Self { id, column, rect, native: None, edge: None }
|
||||
}
|
||||
|
||||
/// A window with one group. Each call makes a new window, as [`Self::new`] does.
|
||||
pub fn single(panels: Vec<P>, active: usize, rect: Rect) -> Self {
|
||||
Self::new(Column::new(vec![Group::new(panels, active)]), rect)
|
||||
/// The window `id` with one group.
|
||||
pub fn single(id: u64, panels: Vec<P>, active: usize, rect: Rect) -> Self {
|
||||
Self::new(id, Column::new(vec![Group::new(panels, active)]), rect)
|
||||
}
|
||||
|
||||
/// The window with `id`, for a layout the app builds in code, such as a default layout:
|
||||
/// built with the same id, it is the same window, and the same OS window, on every frame.
|
||||
/// Ids must be unique within a layout.
|
||||
/// The window with `id` in place of its own. Ids must be unique within a layout.
|
||||
pub fn with_id(mut self, id: u64) -> Self {
|
||||
self.id = id;
|
||||
self
|
||||
@@ -165,10 +151,9 @@ impl<P> Floating<P> {
|
||||
self.column.panels()
|
||||
}
|
||||
|
||||
/// A window of `groups`, stacked top to bottom, expanded. `None` without groups. Each call makes a new window,
|
||||
/// as [`Self::new`] does.
|
||||
pub fn stack(groups: Vec<Group<P>>, rect: Rect) -> Option<Self> {
|
||||
(!groups.is_empty()).then(|| Self::new(Column::new(groups), rect))
|
||||
/// The window `id` of `groups`, stacked top to bottom, expanded. `None` without groups.
|
||||
pub fn stack(id: u64, groups: Vec<Group<P>>, rect: Rect) -> Option<Self> {
|
||||
(!groups.is_empty()).then(|| Self::new(id, Column::new(groups), rect))
|
||||
}
|
||||
|
||||
/// The window's groups, top to bottom.
|
||||
@@ -202,7 +187,7 @@ pub(super) mod floating_serde {
|
||||
use serde::de::IgnoredAny;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use super::{Column, DockEdge, Floating, Group, Node, fresh_window_id};
|
||||
use super::{Column, DockEdge, Floating, Group, Node};
|
||||
use crate::dock::limits::MAX_NODES;
|
||||
use crate::dock::rect_serde::{from_array, to_array};
|
||||
use crate::dock::split::SplitSize;
|
||||
@@ -339,9 +324,13 @@ pub(super) mod floating_serde {
|
||||
}
|
||||
}
|
||||
|
||||
/// A window as read, with the id it was saved with, if any.
|
||||
type Saved<P> = (Option<u64>, Floating<P>);
|
||||
|
||||
impl<P> Repr<P> {
|
||||
/// The windows the saved window becomes, first to last.
|
||||
fn into_windows<E: serde::de::Error>(self) -> Result<Vec<Floating<P>>, E> {
|
||||
/// The windows the saved window becomes, first to last, each with its saved id: the first keeps the saved
|
||||
/// window's, the others have none.
|
||||
fn into_windows<E: serde::de::Error>(self) -> Result<Vec<Saved<P>>, E> {
|
||||
let Repr { id, column, root, groups, panels, active, rect, native, minimized, edge } = self;
|
||||
let rect = from_array(rect.ok_or_else(|| E::missing_field("rect"))?);
|
||||
let columns = match (column, root, groups, panels) {
|
||||
@@ -367,11 +356,8 @@ pub(super) mod floating_serde {
|
||||
return Err(E::invalid_length(0, &"at least one group"));
|
||||
}
|
||||
let native = native.and_then(|native| native.repaired());
|
||||
let mut id = Some(id.unwrap_or_else(fresh_window_id));
|
||||
Ok(columns
|
||||
.into_iter()
|
||||
.map(|(column, rect)| Floating { id: id.take().unwrap_or_else(fresh_window_id), column, rect, native: native.clone(), edge })
|
||||
.collect())
|
||||
let mut id = id;
|
||||
Ok(columns.into_iter().map(|(column, rect)| (id.take(), Floating { id: 0, column, rect, native: native.clone(), edge })).collect())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,20 +405,36 @@ pub(super) mod floating_serde {
|
||||
groups
|
||||
}
|
||||
|
||||
/// Floating windows as saved, each read into the windows it becomes, with a fresh id for each one whose id an
|
||||
/// earlier window took.
|
||||
/// Floating windows as saved, each read into the windows it becomes. A window keeps its saved id unless an
|
||||
/// earlier window took it; one without an id, or with a taken one, gets the next id above every saved one, or,
|
||||
/// should those run out (a saved `u64::MAX`), the least id no saved or given window holds.
|
||||
pub(in crate::dock) fn unique_ids<'de, D: Deserializer<'de>, P: Deserialize<'de>>(deserializer: D) -> Result<Vec<Floating<P>>, D::Error> {
|
||||
let mut windows = Vec::new();
|
||||
for saved in Vec::<Repr<P>>::deserialize(deserializer)? {
|
||||
windows.extend(saved.into_windows::<D::Error>()?);
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for window in &mut windows {
|
||||
while !seen.insert(window.id) {
|
||||
window.id = fresh_window_id();
|
||||
}
|
||||
let saved: std::collections::HashSet<u64> = windows.iter().filter_map(|(id, _)| *id).collect();
|
||||
let mut next = saved.iter().max().map_or(Some(0), |id| id.checked_add(1));
|
||||
let mut given = std::collections::HashSet::new();
|
||||
let mut out = Vec::with_capacity(windows.len());
|
||||
for (id, window) in windows {
|
||||
let id = match id.filter(|id| given.insert(*id)) {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
let id = match next {
|
||||
Some(id) => {
|
||||
next = id.checked_add(1);
|
||||
id
|
||||
}
|
||||
None => (0..=u64::MAX).find(|id| !saved.contains(id) && !given.contains(id)).unwrap_or(0),
|
||||
};
|
||||
given.insert(id);
|
||||
id
|
||||
}
|
||||
};
|
||||
out.push(Floating { id, ..window });
|
||||
}
|
||||
Ok(windows)
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::fmt;
|
||||
/// What may happen to a panel. `Layout::apply_with_permissions` enforces these for every
|
||||
/// action, whoever issues it. They also decide which gestures and menu items the renderer
|
||||
/// offers; a renderer hides the built-in close controls of a panel that stays closable by command.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct Permissions {
|
||||
/// The panel may be moved.
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
use std::{collections::HashSet, hash::Hash};
|
||||
|
||||
use craft_tracked::{Revision, Tracked};
|
||||
|
||||
use super::{
|
||||
DockSide,
|
||||
action::{Action, DockPlacement, Location},
|
||||
@@ -19,10 +21,12 @@ use super::{
|
||||
|
||||
/// A saved arrangement of panels: the [`Layout`] and the closed panels' former places.
|
||||
///
|
||||
/// Its [`revision`](Self::revision) changes when another arrangement replaces it (switch, reset, load): replace a
|
||||
/// Two signals name its state. [`revision`](Self::revision) moves with every write: the fields are private and every
|
||||
/// method that writes moves it, and a clone is a new source, so two workspace values never share a revision.
|
||||
/// [`generation`](Self::generation) moves only when another arrangement replaces it (switch, reset, load): replace a
|
||||
/// shown workspace with [`replace`](Self::replace) or the [`WorkspaceSet`](super::WorkspaceSet) operations, never by
|
||||
/// assignment, so a running drag on it ends. Edits ([`apply`](Self::apply), [`set_visible`](Self::set_visible), the
|
||||
/// dock's own) keep the revision.
|
||||
/// dock's own) keep the generation.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(bound(deserialize = "P: serde::Deserialize<'de>"))]
|
||||
#[non_exhaustive]
|
||||
@@ -30,25 +34,29 @@ pub struct Workspace<P> {
|
||||
/// Format version; files without one are v1 (`{layout, hidden}`). Always written as
|
||||
/// [`Workspace::VERSION`].
|
||||
#[serde(default = "first_version", serialize_with = "write_version")]
|
||||
pub version: u32,
|
||||
version: u32,
|
||||
/// The current arrangement, changes included. A save without one is no workspace: it does not load.
|
||||
pub layout: Layout<P>,
|
||||
layout: Layout<P>,
|
||||
/// Closed panels, and panels the application does not register now, with where each one
|
||||
/// goes back.
|
||||
#[serde(default)]
|
||||
pub hidden: Vec<(P, Location<P>)>,
|
||||
hidden: Vec<(P, Location<P>)>,
|
||||
/// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the
|
||||
/// workspace.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub floated: Vec<(P, Location<P>)>,
|
||||
floated: Vec<(P, Location<P>)>,
|
||||
/// Counts the replacements of this live workspace. Not saved, and not part of equality.
|
||||
#[serde(skip)]
|
||||
revision: u64,
|
||||
generation: u64,
|
||||
/// Moves with every write; a clone is a new source. Not saved, and not part of equality.
|
||||
#[serde(skip)]
|
||||
revision: Tracked<()>,
|
||||
}
|
||||
|
||||
impl<P: PartialEq> PartialEq for Workspace<P> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.version == other.version && self.layout == other.layout && self.hidden == other.hidden && self.floated == other.floated
|
||||
self.revision.revision() == other.revision.revision()
|
||||
|| (self.version == other.version && self.layout == other.layout && self.hidden == other.hidden && self.floated == other.floated)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,18 +81,83 @@ impl<P> Workspace<P> {
|
||||
|
||||
/// A workspace of `layout`, with no hidden panels.
|
||||
pub fn new(layout: Layout<P>) -> Self {
|
||||
Self { version: Self::VERSION, layout, hidden: Vec::new(), floated: Vec::new(), revision: 0 }
|
||||
Self::from_parts(layout, Vec::new(), Vec::new())
|
||||
}
|
||||
|
||||
/// The revision of this live workspace: it changes with every [`replace`](Self::replace) and nothing else.
|
||||
pub fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
/// A workspace of `layout` with the closed panels' places `hidden` and the floating panels' docked places
|
||||
/// `floated`, unchecked, as a saved one loads; [`validate`](Self::validate) checks it.
|
||||
pub fn from_parts(layout: Layout<P>, hidden: Vec<(P, Location<P>)>, floated: Vec<(P, Location<P>)>) -> Self {
|
||||
Self { version: Self::VERSION, layout, hidden, floated, generation: 0, revision: Tracked::default() }
|
||||
}
|
||||
|
||||
/// Replaces the arrangement with `with` and moves to the next revision.
|
||||
/// The format version the workspace was read with.
|
||||
pub fn version(&self) -> u32 {
|
||||
self.version
|
||||
}
|
||||
|
||||
/// The current arrangement.
|
||||
pub fn layout(&self) -> &Layout<P> {
|
||||
&self.layout
|
||||
}
|
||||
|
||||
/// The closed panels, and panels the application does not register now, with where each one goes back.
|
||||
pub fn hidden(&self) -> &[(P, Location<P>)] {
|
||||
&self.hidden
|
||||
}
|
||||
|
||||
/// The floating panels with the docked location each one left.
|
||||
pub fn floated(&self) -> &[(P, Location<P>)] {
|
||||
&self.floated
|
||||
}
|
||||
|
||||
/// The revision of this workspace value: it moves with every write, and no other value has it.
|
||||
pub fn revision(&self) -> Revision {
|
||||
self.revision.revision()
|
||||
}
|
||||
|
||||
/// The generation of this live workspace: it moves with every [`replace`](Self::replace) and nothing else.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
|
||||
/// The workspace with its arrangement replaced by `layout`, for a stored set whose saved arrangement is kept apart.
|
||||
pub(super) fn with_layout(mut self, layout: Layout<P>) -> Self {
|
||||
self.layout = layout;
|
||||
self.touch();
|
||||
self
|
||||
}
|
||||
|
||||
/// Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a
|
||||
/// workspace an undo brings back to it, so no id, and no OS window, goes to a second window.
|
||||
pub fn raise_window_floor(&mut self, floor: u64) {
|
||||
if self.layout.raise_window_floor(floor) {
|
||||
self.touch();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the closed-panel records of the panels `forget` names, so reopening them does not restore their place.
|
||||
pub fn forget_hidden(&mut self, forget: impl Fn(&P) -> bool) {
|
||||
let before = self.hidden.len();
|
||||
self.hidden.retain(|(panel, _)| !forget(panel));
|
||||
if self.hidden.len() != before {
|
||||
self.touch();
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the revision. Every method that writes the workspace calls it.
|
||||
fn touch(&mut self) {
|
||||
self.revision.edit(|()| ());
|
||||
}
|
||||
|
||||
/// Replaces the arrangement with `with` and moves to the next generation. The windows of `with` take ids this
|
||||
/// workspace never gave out, so no OS window passes to another window.
|
||||
pub fn replace(&mut self, with: Workspace<P>) {
|
||||
let revision = self.revision.wrapping_add(1);
|
||||
*self = Workspace { revision, ..with };
|
||||
let generation = self.generation.wrapping_add(1);
|
||||
let revision = std::mem::take(&mut self.revision);
|
||||
let mut with = with;
|
||||
self.layout.hand_ids_to(&mut with.layout);
|
||||
*self = Workspace { generation, revision, ..with };
|
||||
self.touch();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,7 +241,9 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
let mut seen = HashSet::new();
|
||||
all_closed.retain(|p| !visible.contains(p) && seen.insert(p.clone()));
|
||||
proposed.validate()?;
|
||||
*self = proposed;
|
||||
let Workspace { layout, hidden, floated, .. } = proposed;
|
||||
(self.layout, self.hidden, self.floated) = (layout, hidden, floated);
|
||||
self.touch();
|
||||
Ok(all_closed)
|
||||
}
|
||||
|
||||
@@ -291,6 +366,15 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
/// [`Permissions::locked`] ones.
|
||||
/// `hidden` keeps at most [`MAX_PANELS`] entries, dropping the oldest unregistered ones first.
|
||||
pub fn reconcile(&mut self, registered: impl Fn(&P) -> bool, permissions: impl Fn(&P) -> Permissions, default: &Workspace<P>) {
|
||||
let before = self.clone();
|
||||
self.reconcile_parts(registered, permissions, default);
|
||||
if *self != before {
|
||||
self.touch();
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::reconcile`]'s work, which leaves the revision to it.
|
||||
fn reconcile_parts(&mut self, registered: impl Fn(&P) -> bool, permissions: impl Fn(&P) -> Permissions, default: &Workspace<P>) {
|
||||
if self.validate().is_err() {
|
||||
self.replace(default.clone());
|
||||
}
|
||||
|
||||
@@ -286,7 +286,7 @@ impl<P> From<StoredSet<P>> for WorkspaceSet<P> {
|
||||
let StoredWorkspace { mut workspace, locked: lock, saved } = named.layout;
|
||||
locked |= lock;
|
||||
if let Some(layout) = saved {
|
||||
workspace.layout = layout;
|
||||
workspace = workspace.with_layout(layout);
|
||||
}
|
||||
NamedWorkspace { id: named.id, name: named.name, layout: workspace, chrome: named.chrome, keeps: named.keeps }
|
||||
})
|
||||
@@ -297,7 +297,7 @@ impl<P> From<StoredSet<P>> for WorkspaceSet<P> {
|
||||
if let Some(layout) = stored.saved
|
||||
&& let Some(named) = saved.iter_mut().find(|w| w.id == id)
|
||||
{
|
||||
named.layout.layout = layout;
|
||||
named.layout = std::mem::take(&mut named.layout).with_layout(layout);
|
||||
}
|
||||
edited.insert(id, stored.workspace);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,10 @@ fn docked() -> Layout<u32> {
|
||||
DockEdge::End,
|
||||
vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)]).with_width(180.0), Column::new(vec![g(&[5], 0)]).with_width(120.0)],
|
||||
);
|
||||
Layout::new(Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)), vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], WINDOW).unwrap()])
|
||||
Layout::new(
|
||||
Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)),
|
||||
vec![Floating::stack(100, vec![g(&[6, 7], 1), g(&[8], 0)], WINDOW).unwrap()],
|
||||
)
|
||||
}
|
||||
|
||||
fn with_column(column: Column<u32>) -> Layout<u32> {
|
||||
@@ -165,7 +168,7 @@ fn without(skip: Option<u32>) -> Layout<u32> {
|
||||
let windows: Vec<Group<u32>> = [group(&[6], 0), tall].into_iter().flatten().collect();
|
||||
Layout::new(
|
||||
Some(hsplit(SplitSize::FixedSecond(300.0), tabs(&[1], 0), end)),
|
||||
vec![Floating::stack(windows, area(10.0, 10.0, 200.0, 300.0)).unwrap()],
|
||||
vec![Floating::stack(101, windows, area(10.0, 10.0, 200.0, 300.0)).unwrap()],
|
||||
)
|
||||
}
|
||||
|
||||
@@ -203,7 +206,7 @@ fn a_layout_saved_with_the_physical_names_loads_and_writes_back_in_reading_order
|
||||
tabs(&[1, 2], 1),
|
||||
Node::dock(DockEdge::End, vec![Column::new(vec![g(&[3], 0)]).with_width(180.0)]),
|
||||
)),
|
||||
vec![Floating::single(vec![4], 0, area(1.0, 2.0, 300.0, 200.0)).with_id(5)],
|
||||
vec![Floating::single(5, vec![4], 0, area(1.0, 2.0, 300.0, 200.0))],
|
||||
);
|
||||
assert_eq!(layout, expected);
|
||||
let written = serde_json::to_value(&layout).unwrap();
|
||||
|
||||
@@ -32,7 +32,7 @@ fn docked() -> Layout<u32> {
|
||||
vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)]).with_width(180.0), Column::new(vec![g(&[5], 0)]).with_width(120.0)],
|
||||
);
|
||||
let root = Node::split(Axis::X, SplitSize::FixedSecond(300.0), middle, dock);
|
||||
Layout::new(Some(root), vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], window()).unwrap()])
|
||||
Layout::new(Some(root), vec![Floating::stack(100, vec![g(&[6, 7], 1), g(&[8], 0)], window()).unwrap()])
|
||||
}
|
||||
|
||||
const ALL: [u32; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 11, 12];
|
||||
@@ -79,32 +79,33 @@ fn apply_all_changes_everything_or_nothing_and_reports_the_closed_panels() {
|
||||
#[test]
|
||||
fn reconcile_drops_unknown_panels_and_places_missing_registered_ones() {
|
||||
let default = Workspace::new(docked());
|
||||
let mut workspace = default.clone();
|
||||
workspace.layout.apply(Action::close(5)).unwrap();
|
||||
workspace.layout.apply(Action::close(12)).unwrap();
|
||||
workspace.layout.apply(Action::open_at(99, 2, DockPlacement::tab(None))).unwrap();
|
||||
let stray = workspace.layout.location(&99).unwrap();
|
||||
workspace.hidden.push((98, stray));
|
||||
let mut layout = docked();
|
||||
layout.apply(Action::close(5)).unwrap();
|
||||
layout.apply(Action::close(12)).unwrap();
|
||||
layout.apply(Action::open_at(99, 2, DockPlacement::tab(None))).unwrap();
|
||||
let stray = layout.location(&99).unwrap();
|
||||
let mut workspace = Workspace::from_parts(layout, vec![(98, stray)], Vec::new());
|
||||
let registered = |p: &u32| *p < 90;
|
||||
workspace.reconcile(registered, allow, &default);
|
||||
workspace.validate().unwrap();
|
||||
// Unregistered panels wait in `hidden` and come back once registered.
|
||||
assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::<Vec<_>>(), [98, 99]);
|
||||
assert_eq!(sorted(&workspace.layout), ALL);
|
||||
assert_eq!(workspace.hidden().iter().map(|(p, _)| *p).collect::<Vec<_>>(), [98, 99]);
|
||||
assert_eq!(sorted(workspace.layout()), ALL);
|
||||
workspace.set_visible(99, true, None, false, allow).unwrap();
|
||||
assert_eq!(group_members(&workspace.layout, 2), [2, 3, 99]);
|
||||
assert_eq!(end_dock(&workspace.layout).len(), 2);
|
||||
assert_eq!(group_members(&workspace.layout, 11), [11, 12]);
|
||||
assert_eq!(group_members(workspace.layout(), 2), [2, 3, 99]);
|
||||
assert_eq!(end_dock(workspace.layout()).len(), 2);
|
||||
assert_eq!(group_members(workspace.layout(), 11), [11, 12]);
|
||||
|
||||
let mut broken = default.clone();
|
||||
broken.layout.floating[0].rect = Rect::from_min_size(pos2(100.0, 100.0), vec2(-1.0, 400.0));
|
||||
let mut layout = docked();
|
||||
layout.floating[0].rect = Rect::from_min_size(pos2(100.0, 100.0), vec2(-1.0, 400.0));
|
||||
let mut broken = Workspace::new(layout);
|
||||
broken.reconcile(registered, allow, &default);
|
||||
assert_eq!(broken.layout, default.layout);
|
||||
assert_eq!(broken.layout(), default.layout());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workspace_set_with_a_floating_group_round_trips_through_json() {
|
||||
let layout = Layout::new(Some(Node::tabs(vec![1u32, 2], 0)), vec![Floating::single(vec![3u32], 0, rect(1.0, 2.0, 300.0, 200.0)).with_id(5)]);
|
||||
let layout = Layout::new(Some(Node::tabs(vec![1u32, 2], 0)), vec![Floating::single(5, vec![3u32], 0, rect(1.0, 2.0, 300.0, 200.0))]);
|
||||
let mut set = WorkspaceSet::new(vec![NamedWorkspace::new("essentials", "Essentials", Workspace::default())]);
|
||||
set.save("Mine", Workspace::new(layout), WorkspaceChrome::default(), WorkspaceKeeps::new(false, true, true)).unwrap();
|
||||
let saved = serde_json::to_string(&set).unwrap();
|
||||
@@ -134,18 +135,18 @@ fn a_workspace_with_a_bottom_pane_opens_and_closes_it_on_switch() {
|
||||
]);
|
||||
let mut live = photography;
|
||||
set.select("motion", &mut live).unwrap();
|
||||
let bottom = live.layout.place(&TIMELINE).unwrap();
|
||||
let bottom = live.layout().place(&TIMELINE).unwrap();
|
||||
assert_eq!(bottom, PanelPlace::Node(vec![true]), "the Timeline is the second (bottom) frame of the split");
|
||||
set.select("photography", &mut live).unwrap();
|
||||
assert!(!live.layout.contains(&TIMELINE), "leaving Motion closes the Timeline");
|
||||
assert!(!live.layout().contains(&TIMELINE), "leaving Motion closes the Timeline");
|
||||
set.select("motion", &mut live).unwrap();
|
||||
assert!(live.layout.contains(&TIMELINE), "coming back opens it again");
|
||||
assert!(live.layout().contains(&TIMELINE), "coming back opens it again");
|
||||
}
|
||||
|
||||
/// Switching and resetting replace the live workspace and move it to a new revision; edits and selecting the shown
|
||||
/// workspace keep it, and the revision is neither saved nor compared.
|
||||
/// Switching and resetting replace the live workspace and move it to a new generation; edits and selecting the shown
|
||||
/// workspace keep it, and the generation is neither saved nor compared.
|
||||
#[test]
|
||||
fn only_a_replacement_changes_the_live_revision() {
|
||||
fn only_a_replacement_changes_the_live_generation() {
|
||||
let essentials = Workspace::new(Layout::new(Some(tabs(&[1, 2], 0)), Vec::new()));
|
||||
let painting = Workspace::new(Layout::new(Some(tabs(&[3], 0)), Vec::new()));
|
||||
let mut set = WorkspaceSet::new(vec![
|
||||
@@ -153,20 +154,20 @@ fn only_a_replacement_changes_the_live_revision() {
|
||||
NamedWorkspace::new("painting", "Painting", painting),
|
||||
]);
|
||||
let mut live = essentials.clone();
|
||||
let start = live.revision();
|
||||
let start = live.generation();
|
||||
live.apply(Action::activate(2), false, allow).unwrap();
|
||||
live.set_visible(1, false, None, false, allow).unwrap();
|
||||
set.select("essentials", &mut live).unwrap();
|
||||
assert_eq!(live.revision(), start, "edits and selecting the shown workspace keep the revision");
|
||||
assert_eq!(live.generation(), start, "edits and selecting the shown workspace keep the generation");
|
||||
set.select("painting", &mut live).unwrap();
|
||||
let switched = live.revision();
|
||||
assert!(switched != start && live.layout.contains(&3), "a switch replaces the live workspace");
|
||||
let switched = live.generation();
|
||||
assert!(switched != start && live.layout().contains(&3), "a switch replaces the live workspace");
|
||||
set.reset(&mut live).unwrap();
|
||||
assert!(live.revision() != switched, "a reset replaces it again");
|
||||
assert!(live.generation() != switched, "a reset replaces it again");
|
||||
set.select("essentials", &mut live).unwrap();
|
||||
assert!(!live.layout.contains(&1), "the switch back shows the edited essentials");
|
||||
assert!(!live.layout().contains(&1), "the switch back shows the edited essentials");
|
||||
let loaded: Workspace<u32> = serde_json::from_str(&serde_json::to_string(&live).unwrap()).unwrap();
|
||||
assert_eq!(loaded, live, "the revision is not saved and not part of equality");
|
||||
assert_eq!(loaded, live, "the generation is not saved and not part of equality");
|
||||
}
|
||||
|
||||
/// Open of a hidden panel follows its record: a floating panel returns to its window; a record whose anchor is gone
|
||||
@@ -175,39 +176,39 @@ fn only_a_replacement_changes_the_live_revision() {
|
||||
fn opening_a_closed_floating_panel_restores_its_window_place() {
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply(Action::close(8), false, allow).unwrap();
|
||||
assert!(workspace.layout.place(&8).is_none());
|
||||
assert!(workspace.layout().place(&8).is_none());
|
||||
workspace.apply(Action::open(8, Some(11)), false, allow).unwrap();
|
||||
assert!(matches!(workspace.layout.place(&8), Some(PanelPlace::Floating { .. })), "back in its window");
|
||||
assert!(workspace.hidden.is_empty());
|
||||
assert!(matches!(workspace.layout().place(&8), Some(PanelPlace::Floating { .. })), "back in its window");
|
||||
assert!(workspace.hidden().is_empty());
|
||||
|
||||
let mut stray = workspace.layout.location(&5).unwrap();
|
||||
let mut stray = workspace.layout().location(&5).unwrap();
|
||||
stray.anchor = Some(99);
|
||||
workspace.hidden.push((50, stray));
|
||||
let mut workspace = Workspace::from_parts(workspace.layout().clone(), vec![(50, stray)], Vec::new());
|
||||
workspace.apply(Action::open(50, Some(11)), false, allow).unwrap();
|
||||
assert_eq!(group_members(&workspace.layout, 11), [11, 12, 50]);
|
||||
assert_eq!(group_members(workspace.layout(), 11), [11, 12, 50]);
|
||||
}
|
||||
|
||||
/// A panel that floats keeps its docked place until it docks or closes; floating again from the float keeps the first.
|
||||
#[test]
|
||||
fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() {
|
||||
let mut workspace = Workspace::new(docked());
|
||||
let docked_at = workspace.layout.location(&2).unwrap();
|
||||
let docked_at = workspace.layout().location(&2).unwrap();
|
||||
workspace.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
assert_eq!(workspace.floated, [(2, docked_at.clone())]);
|
||||
assert_eq!(workspace.floated(), [(2, docked_at.clone())]);
|
||||
workspace.apply(Action::float(2, rect(30.0, 30.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
assert_eq!(workspace.floated, [(2, docked_at)], "floating again from the float keeps the first record");
|
||||
assert_eq!(workspace.floated(), [(2, docked_at)], "floating again from the float keeps the first record");
|
||||
workspace.apply(Action::move_beside(2, 11, DockPlacement::tab(None)), false, allow).unwrap();
|
||||
assert!(workspace.floated.is_empty(), "docking drops the record");
|
||||
assert!(workspace.floated().is_empty(), "docking drops the record");
|
||||
workspace.apply(Action::float(3, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
assert_eq!(workspace.floated.len(), 1);
|
||||
assert_eq!(workspace.floated().len(), 1);
|
||||
workspace.apply(Action::close(3), false, allow).unwrap();
|
||||
assert!(workspace.floated.is_empty(), "closing drops the record");
|
||||
assert!(workspace.floated().is_empty(), "closing drops the record");
|
||||
}
|
||||
|
||||
/// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6].
|
||||
fn columns() -> Layout<u32> {
|
||||
let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]);
|
||||
Layout::new(Some(Node::split(Axis::X, SplitSize::FixedSecond(300.0), tabs(&[1], 0), dock)), vec![Floating::single(vec![6], 0, window())])
|
||||
Layout::new(Some(Node::split(Axis::X, SplitSize::FixedSecond(300.0), tabs(&[1], 0), dock)), vec![Floating::single(101, vec![6], 0, window())])
|
||||
}
|
||||
|
||||
fn floats(layout: &Layout<u32>, panel: u32) -> bool {
|
||||
@@ -318,12 +319,13 @@ fn a_panel_that_does_not_collapse_keeps_its_column_expanded() {
|
||||
layout.apply_with_permissions(Action::set_iconic(3, false), rigid).unwrap();
|
||||
layout.apply_with_permissions(Action::move_group(2, Target::at(3, DockPlacement::group(true, None))), rigid).unwrap();
|
||||
|
||||
let mut saved = Workspace::new(columns());
|
||||
saved.layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap();
|
||||
assert!(column_of(&saved.layout, 2).iconic);
|
||||
let mut layout = columns();
|
||||
layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap();
|
||||
let mut saved = Workspace::new(layout);
|
||||
assert!(column_of(saved.layout(), 2).iconic);
|
||||
saved.reconcile(|_| true, rigid, &Workspace::new(columns()));
|
||||
assert!(!column_of(&saved.layout, 2).iconic, "reconcile expands the column");
|
||||
assert_eq!(group_members(&saved.layout, 2), [2]);
|
||||
assert!(!column_of(saved.layout(), 2).iconic, "reconcile expands the column");
|
||||
assert_eq!(group_members(saved.layout(), 2), [2]);
|
||||
}
|
||||
|
||||
/// A panel that shares no column (a toolbar) refuses every placement that puts it beside other panels in a column
|
||||
@@ -348,11 +350,12 @@ fn a_panel_that_shares_no_column_moves_only_to_a_column_of_its_own() {
|
||||
assert_eq!(column_of(&moved, 2).panels().count(), 1, "{to:?}");
|
||||
}
|
||||
|
||||
let mut saved = Workspace::new(columns());
|
||||
saved.layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap();
|
||||
let mut layout = columns();
|
||||
layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap();
|
||||
let mut saved = Workspace::new(layout);
|
||||
saved.reconcile(|_| true, alone, &Workspace::new(columns()));
|
||||
assert_eq!(column_of(&saved.layout, 2).panels().collect::<Vec<_>>(), [&2], "reconcile gives it a column of its own");
|
||||
assert_eq!(sorted(&saved.layout), [1, 2, 3, 4, 6]);
|
||||
assert_eq!(column_of(saved.layout(), 2).panels().collect::<Vec<_>>(), [&2], "reconcile gives it a column of its own");
|
||||
assert_eq!(sorted(saved.layout()), [1, 2, 3, 4, 6]);
|
||||
}
|
||||
|
||||
/// A panel that docks only in dock columns (a toolbar, photocraft#12517) refuses every placement that leaves it in a
|
||||
@@ -395,9 +398,9 @@ fn a_panel_that_docks_only_in_columns_never_lands_in_a_frame() {
|
||||
other.apply_with_permissions(Action::move_group(6, Target::at(3, DockPlacement::column(false))), strip).unwrap();
|
||||
let mut saved = Workspace::new(split);
|
||||
saved.reconcile(|_| true, strip, &Workspace::new(columns()));
|
||||
assert!(matches!(saved.layout.place(&2), Some(PanelPlace::Dock { .. })), "reconcile docks it in a column: {:?}", saved.layout);
|
||||
assert_eq!(column_of(&saved.layout, 2).panels().collect::<Vec<_>>(), [&2]);
|
||||
assert_eq!(sorted(&saved.layout), [1, 2, 3, 4, 6]);
|
||||
assert!(matches!(saved.layout().place(&2), Some(PanelPlace::Dock { .. })), "reconcile docks it in a column: {:?}", saved.layout());
|
||||
assert_eq!(column_of(saved.layout(), 2).panels().collect::<Vec<_>>(), [&2]);
|
||||
assert_eq!(sorted(saved.layout()), [1, 2, 3, 4, 6]);
|
||||
}
|
||||
|
||||
/// A stepped column (a toolbar's) keeps its step count docked, floating and through JSON, and its width moves only
|
||||
@@ -420,3 +423,117 @@ fn a_stepped_column_keeps_its_step_count_and_refuses_a_width() {
|
||||
let saved: Layout<u32> = serde_json::from_str(&serde_json::to_string(&layout).unwrap()).unwrap();
|
||||
assert_eq!(saved, layout);
|
||||
}
|
||||
|
||||
/// The names of the `pub fn` methods in `source` whose receiver is `&mut self`.
|
||||
fn mutating_methods(source: &str) -> Vec<&str> {
|
||||
let mut names: Vec<&str> = source
|
||||
.split("pub fn ")
|
||||
.skip(1)
|
||||
.filter_map(|rest| {
|
||||
let name = &rest[..rest.find(|c: char| !(c.is_alphanumeric() || c == '_'))?];
|
||||
let receiver = rest[rest.find('(')? + 1..].trim_start();
|
||||
receiver.starts_with("&mut self").then_some(name)
|
||||
})
|
||||
.collect();
|
||||
names.sort_unstable();
|
||||
names
|
||||
}
|
||||
|
||||
/// Every method that writes a workspace moves its revision, and only `replace` moves its generation. The trial reads
|
||||
/// the workspace's source for its `&mut self` methods, so a new one fails here until it is walked.
|
||||
#[test]
|
||||
fn every_workspace_mutator_moves_the_revision() {
|
||||
let mut walked: Vec<&str> = Vec::new();
|
||||
let mut moves = |name: &'static str, edit: &dyn Fn(&mut Workspace<u32>)| {
|
||||
let mut workspace = Workspace::new(docked());
|
||||
let (revision, generation) = (workspace.revision(), workspace.generation());
|
||||
edit(&mut workspace);
|
||||
assert_ne!(workspace.revision(), revision, "`{name}` moves the revision");
|
||||
assert_eq!(workspace.generation() != generation, name == "replace", "only `replace` moves the generation, `{name}` included");
|
||||
walked.push(name);
|
||||
};
|
||||
moves("replace", &|workspace| workspace.replace(Workspace::new(columns())));
|
||||
moves("apply", &|workspace| drop(workspace.apply(Action::activate(6), false, allow).unwrap()));
|
||||
moves("apply_all", &|workspace| drop(workspace.apply_all([Action::close(5), Action::close(4)], false, allow).unwrap()));
|
||||
moves("set_visible", &|workspace| workspace.set_visible(5, false, None, false, allow).unwrap());
|
||||
moves("reconcile", &|workspace| workspace.reconcile(|panel| *panel != 5, allow, &Workspace::new(docked())));
|
||||
moves("raise_window_floor", &|workspace| workspace.raise_window_floor(1000));
|
||||
moves("forget_hidden", &|workspace| {
|
||||
workspace.apply(Action::close(5), false, allow).unwrap();
|
||||
let revision = workspace.revision();
|
||||
workspace.forget_hidden(|panel| *panel == 5);
|
||||
assert_ne!(workspace.revision(), revision, "`forget_hidden` moves the revision by itself");
|
||||
});
|
||||
walked.sort_unstable();
|
||||
assert_eq!(walked, mutating_methods(include_str!("../src/dock/workspace.rs")), "every `&mut self` method of `Workspace` is walked");
|
||||
|
||||
let workspace = Workspace::new(docked());
|
||||
assert_ne!(workspace.clone().revision(), workspace.revision(), "a clone is a new source");
|
||||
let mut settled = Workspace::new(docked());
|
||||
let revision = settled.revision();
|
||||
settled.reconcile(|_| true, allow, &Workspace::new(docked()));
|
||||
assert_eq!(settled.revision(), revision, "a reconcile that changes nothing keeps the revision");
|
||||
}
|
||||
|
||||
fn window_ids(workspace: &Workspace<u32>) -> Vec<u64> {
|
||||
workspace.layout().floating.iter().map(|window| window.id).collect()
|
||||
}
|
||||
|
||||
/// Window ids come from a counter each layout owns: two workspaces edited side by side each keep their windows' ids
|
||||
/// unique, a closed window's id is never drawn again, and a replacement's windows take ids the old layout never gave.
|
||||
#[test]
|
||||
fn window_ids_stay_unique_within_each_layout_and_are_never_reused() {
|
||||
let (mut a, mut b) = (Workspace::new(docked()), Workspace::new(docked()));
|
||||
for workspace in [&mut a, &mut b] {
|
||||
workspace.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
workspace.apply(Action::float(5, rect(30.0, 30.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
let mut ids = window_ids(workspace);
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), 3, "three windows, three ids: {:?}", window_ids(workspace));
|
||||
}
|
||||
|
||||
let seen = window_ids(&a);
|
||||
a.apply(Action::close(5), false, allow).unwrap();
|
||||
a.apply(Action::float(3, rect(50.0, 50.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
let fresh: Vec<u64> = window_ids(&a).into_iter().filter(|id| !seen.contains(id)).collect();
|
||||
assert!(fresh.len() == 1 && fresh[0] > seen.iter().copied().max().unwrap(), "a new window takes a new id: {fresh:?} after {seen:?}");
|
||||
|
||||
let held: Vec<u64> = seen.iter().chain(&fresh).copied().collect();
|
||||
a.replace(Workspace::new(docked()));
|
||||
let replaced = window_ids(&a);
|
||||
assert!(replaced.iter().all(|id| !held.contains(id)), "the replacement's window takes an id no earlier window had: {replaced:?} after {held:?}");
|
||||
|
||||
let saved = r#"{"layout":{"root":null,"floating":[{"id":7,"panels":[1],"active":0,"rect":[0,0,100,100]},{"id":7,"panels":[2],"active":0,"rect":[0,0,100,100]},{"panels":[3],"active":0,"rect":[0,0,100,100]}]}}"#;
|
||||
let loaded: Workspace<u32> = serde_json::from_str(saved).unwrap();
|
||||
assert_eq!(window_ids(&loaded), [7, 8, 9], "a load keeps the first of a duplicate id and numbers the rest above every saved id");
|
||||
|
||||
// A loaded layout draws above the ids it loaded with, not only the ones it drew: a closed window's id stays used.
|
||||
let saved = r#"{"layout":{"root":{"Tabs":{"panels":[4,5],"active":0}},"floating":[{"id":7,"panels":[1],"active":0,"rect":[0,0,100,100]},{"id":9,"panels":[3],"active":0,"rect":[0,0,100,100]}]}}"#;
|
||||
let mut loaded: Workspace<u32> = serde_json::from_str(saved).unwrap();
|
||||
loaded.apply(Action::close(3), false, allow).unwrap();
|
||||
loaded.apply(Action::float(4, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
assert_eq!(window_ids(&loaded), [7, 10], "the new window does not take the closed window's id 9");
|
||||
|
||||
// An undo brings back an older workspace whose counter is lower: raised to the floor the dock has shown, it draws
|
||||
// no id a later window had.
|
||||
let older = Workspace::new(docked());
|
||||
let mut later = older.clone();
|
||||
later.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
let drawn: Vec<u64> = window_ids(&later).into_iter().filter(|id| !window_ids(&older).contains(id)).collect();
|
||||
let mut undone = older.clone();
|
||||
undone.raise_window_floor(later.layout().window_floor());
|
||||
undone.apply(Action::float(5, rect(30.0, 30.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
assert!(window_ids(&undone).iter().all(|id| !drawn.contains(id)), "the undone workspace draws past {drawn:?}: {:?}", window_ids(&undone));
|
||||
|
||||
// A saved id at the top of the range loads without overflow, and the windows still get unique ids.
|
||||
let saved = format!(
|
||||
r#"{{"layout":{{"root":null,"floating":[{{"id":{},"panels":[1],"active":0,"rect":[0,0,100,100]}},{{"panels":[2],"active":0,"rect":[0,0,100,100]}}]}}}}"#,
|
||||
u64::MAX
|
||||
);
|
||||
let loaded: Workspace<u32> = serde_json::from_str(&saved).unwrap();
|
||||
assert_eq!(window_ids(&loaded), [u64::MAX, 0], "a window without an id takes the least free one once the range above is used");
|
||||
let mut layout = loaded.layout().clone();
|
||||
let fresh = layout.fresh_window_id();
|
||||
assert!(!window_ids(&loaded).contains(&fresh), "a draw past the top of the range takes a free id: {fresh}");
|
||||
}
|
||||
@@ -240,11 +240,11 @@ impl Default for EsignDialog {
|
||||
}
|
||||
|
||||
/// A send operation id no other send in this process has used, from a random
|
||||
/// start so one saved by an earlier process is unlikely to repeat either.
|
||||
/// Mirrors `docking::model::fresh_window_id`: a counter kept on one
|
||||
/// [`EsignDialog`] repeats across two dialog instances (two windows, or one
|
||||
/// replaced after a document closes), and two sends sharing an idempotency
|
||||
/// key have a conforming provider return the first envelope for the second.
|
||||
/// start so one saved by an earlier process is unlikely to repeat either. A
|
||||
/// counter kept on one [`EsignDialog`] would repeat across two dialog instances
|
||||
/// (two windows, or one replaced after a document closes), and two sends
|
||||
/// sharing an idempotency key have a conforming provider return the first
|
||||
/// envelope for the second.
|
||||
fn fresh_send_id() -> u64 {
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use super::{PairWell, SwatchPair, Well};
|
||||
use craft_behavior::Mixed;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Show as _, Validity};
|
||||
use craft_ui::contract::{Show as _, Tracked, Validity};
|
||||
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
|
||||
@@ -101,7 +101,7 @@ fn swatch_pair_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
#[story(SwatchPair<'static>, covers = [], drive = Drive::Never)]
|
||||
fn swatch_pair_tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (active, active_at) = data.value_at("active", Well::Primary);
|
||||
let (slots, last): (Vec<ToolSlot<u8>>, LastUsed<u8>) = (Vec::new(), LastUsed::default());
|
||||
let (slots, last): (Tracked<Vec<ToolSlot<u8>>>, Tracked<LastUsed<u8>>) = (Tracked::default(), Tracked::default());
|
||||
let wells = [PairWell::new("Foreground colour", Srgba::rgb(0.0, 0.0, 0.0)), PairWell::new("Background colour", Srgba::rgb(1.0, 1.0, 1.0))];
|
||||
let mut shown = None;
|
||||
ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |ui, _| {
|
||||
|
||||
@@ -200,8 +200,6 @@ 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 dock node id counter is hidden state.
|
||||
("crates/behavior/src/dock/node.rs", "NEXT"),
|
||||
// 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.
|
||||
|
||||
@@ -62,7 +62,7 @@ use craft_ui::buttons::IconButton;
|
||||
use craft_ui::canvas::{HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick};
|
||||
use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff};
|
||||
use craft_ui::canvas_controls::{Marquee, MarqueeLook};
|
||||
use craft_ui::contract::{Bind, BodyCx, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft_ui::contract::{Bind, BodyCx, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, Tracked, clicked};
|
||||
use craft_ui::dialog::{
|
||||
DialogResult, DialogWords, FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView,
|
||||
FullWindowWorkspace, RasterOverlay, SideFooter, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
|
||||
@@ -238,7 +238,8 @@ pub struct ContentAwareFillWorkspace {
|
||||
preview_view: FullWindowView,
|
||||
framing: PreviewFraming,
|
||||
tool: FillTool,
|
||||
last_used: LastUsed<FillTool>,
|
||||
last_used: Tracked<LastUsed<FillTool>>,
|
||||
slots: Tracked<Vec<ToolSlot<FillTool>>>,
|
||||
options: FillToolOptions,
|
||||
canvas: FillCanvas,
|
||||
hand: HandTool,
|
||||
@@ -294,7 +295,8 @@ impl ContentAwareFillWorkspace {
|
||||
preview_view: FullWindowView::new(),
|
||||
framing: PreviewFraming::default(),
|
||||
tool: FillTool::SamplingBrush,
|
||||
last_used: LastUsed::default(),
|
||||
last_used: Tracked::new(LastUsed::default()),
|
||||
slots: Tracked::new(FillTool::slots()),
|
||||
canvas: FillCanvas::new(),
|
||||
hand: HandTool::new(navigation),
|
||||
zoom: ZoomTool::new(navigation),
|
||||
@@ -388,7 +390,6 @@ impl ContentAwareFillWorkspace {
|
||||
let params = env.words::<ParamDialogWords>();
|
||||
let title =
|
||||
FullWindowTitle::new(env.words::<FillWords>().name.clone()).subject(self.subject.clone()).zoom(self.view.zoom_percent()).label(&env);
|
||||
let slots = FillTool::slots();
|
||||
let mut reset_all = false;
|
||||
let this = RefCell::new(&mut *self);
|
||||
|
||||
@@ -410,7 +411,7 @@ impl ContentAwareFillWorkspace {
|
||||
})
|
||||
.show(ui, |ui, cx| {
|
||||
let mut guard = this.borrow_mut();
|
||||
guard.show_body(ui, cx, &env, &slots, source);
|
||||
guard.show_body(ui, cx, &env, source);
|
||||
});
|
||||
|
||||
let work = this.into_inner();
|
||||
@@ -604,7 +605,7 @@ impl ContentAwareFillWorkspace {
|
||||
}
|
||||
|
||||
/// The body: the steps and keys, the options bar, the tool strip and the canvas; then the preview job.
|
||||
fn show_body(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, env: &Env, slots: &[ToolSlot<FillTool>], source: &dyn FillSource) {
|
||||
fn show_body(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, env: &Env, source: &dyn FillSource) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let words = env.words::<FillWords>();
|
||||
while let Some((command, _)) = cx.take_command::<ViewCommands>() {
|
||||
@@ -623,7 +624,7 @@ impl ContentAwareFillWorkspace {
|
||||
if fired.phase == FirePhase::Release {
|
||||
continue;
|
||||
}
|
||||
let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
|
||||
let slot = self.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
|
||||
let tools: Vec<&RailTool<FillTool>> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect();
|
||||
let picked = slot.and_then(|slot| {
|
||||
tool_pick(&tools, slot.id, &self.tool, &self.last_used, PickStep::of(&fired), |_| true).map(|entry| (slot.id, entry.id))
|
||||
@@ -652,9 +653,9 @@ impl ContentAwareFillWorkspace {
|
||||
}
|
||||
|
||||
Row::new().fill().show(ui, |ui, _| {
|
||||
let rail = ToolRail::new(words.tools.clone(), slots, &self.tool, &self.last_used).show_column(ui, |_, _| {});
|
||||
let rail = ToolRail::new(words.tools.clone(), &self.slots, &self.tool, &self.last_used).show_column(ui, |_, _| {});
|
||||
if let Some(next) = rail.last_used {
|
||||
self.last_used = next;
|
||||
*self.last_used = next;
|
||||
}
|
||||
if let Some(tool) = rail.select {
|
||||
self.pick(Some(&ctx), tool);
|
||||
|
||||
@@ -18,7 +18,7 @@ use super::session::{FillLimit, FillLimits, FillSession, FillStrokeEvent, Sampli
|
||||
use crate::ui::select_mask::EditMode;
|
||||
|
||||
/// The tools of Content-Aware Fill's strip: Sampling Brush (B), Lasso (L), Hand (H), Zoom (Z).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum FillTool {
|
||||
/// The Sampling Brush.
|
||||
|
||||
@@ -72,14 +72,14 @@ use craft_behavior::{CancelReason, Cursor, EditEvent, EditHistory, Mixed};
|
||||
use craft_ui::canvas::{NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, tool_pick};
|
||||
use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff};
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Pattern, Props as _, Show as _, ShowContainer as _, Tracked};
|
||||
use craft_ui::dialog::{
|
||||
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay,
|
||||
WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
|
||||
};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::primitives::Checker;
|
||||
use craft_ui::rails::{LastUsed, ToolRail};
|
||||
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot};
|
||||
use craft_ui::runtime::commands::{CommandSet as _, Commands as _, FirePhase};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::runtime::memory::{SaveKey, saved_value, set_saved_value};
|
||||
@@ -223,15 +223,28 @@ pub struct LiquifyDone {
|
||||
|
||||
/// What the workspace keeps between passes besides the session: the view, the strip's memory and the tool in progress. None of it is
|
||||
/// the app's, and none of it is in the history.
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Clone)]
|
||||
struct LiquifyView {
|
||||
view: FullWindowView,
|
||||
last_used: LastUsed<LiquifyTool>,
|
||||
last_used: Tracked<LastUsed<LiquifyTool>>,
|
||||
slots: Tracked<Vec<ToolSlot<LiquifyTool>>>,
|
||||
canvas: LiquifyCanvas,
|
||||
/// The canvas the tools run under, to cancel their gestures outside a pass.
|
||||
canvas_id: Option<Id>,
|
||||
}
|
||||
|
||||
impl Default for LiquifyView {
|
||||
fn default() -> Self {
|
||||
LiquifyView {
|
||||
view: FullWindowView::default(),
|
||||
last_used: Tracked::default(),
|
||||
slots: Tracked::new(LiquifyTool::slots()),
|
||||
canvas: LiquifyCanvas::default(),
|
||||
canvas_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Liquify workspace: the session and its history and the settings, as one value the app keeps while Liquify
|
||||
/// is open, with the view, the strip's memory and the stroke in progress.
|
||||
///
|
||||
@@ -441,7 +454,6 @@ impl LiquifyWorkspace {
|
||||
self.edit.events.push(LiquifyEvent::BackdropWanted(of));
|
||||
self.asked = Some(of);
|
||||
}
|
||||
let slots = LiquifyTool::slots();
|
||||
let preview_label = words.preview.clone();
|
||||
let this = RefCell::new(&mut *self);
|
||||
|
||||
@@ -499,7 +511,7 @@ impl LiquifyWorkspace {
|
||||
if fired.phase == FirePhase::Release {
|
||||
continue;
|
||||
}
|
||||
let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
|
||||
let slot = work.view.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
|
||||
let tools: Vec<_> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect();
|
||||
let picked = slot.and_then(|slot| {
|
||||
tool_pick(&tools, slot.id, &work.edit.settings.tool, &work.view.last_used, PickStep::of(&fired), |_| true)
|
||||
@@ -543,10 +555,10 @@ impl LiquifyWorkspace {
|
||||
let shown = Row::new()
|
||||
.fill()
|
||||
.show(ui, |ui, _| {
|
||||
let rail =
|
||||
ToolRail::new(words.tools.clone(), &slots, &work.edit.settings.tool, &state.last_used).show_column(ui, |_, _| {});
|
||||
let rail = ToolRail::new(words.tools.clone(), &state.slots, &work.edit.settings.tool, &state.last_used)
|
||||
.show_column(ui, |_, _| {});
|
||||
if let Some(next) = rail.last_used {
|
||||
state.last_used = next;
|
||||
*state.last_used = next;
|
||||
}
|
||||
if let Some(tool) = rail.select {
|
||||
work.edit.pick(Some(&ctx), state, tool);
|
||||
|
||||
@@ -11,7 +11,7 @@ use super::session::{LiquifyStroke, StrokeEvent};
|
||||
/// The tools of Liquify's strip, in strip order, with Photoshop's letters. Serialised with the
|
||||
/// engine's names (`forwardWarp`, `twirlCw`, `lassoMask`, …) so a [`LiquifyStroke`] passes to
|
||||
/// PhotoCraft's engine unchanged.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum LiquifyTool {
|
||||
|
||||
@@ -68,14 +68,14 @@ use craft_theme::Srgba;
|
||||
use craft_ui::buttons::IconButton;
|
||||
use craft_ui::canvas::{NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick};
|
||||
use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff};
|
||||
use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, Tracked, clicked};
|
||||
use craft_ui::dialog::{
|
||||
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace,
|
||||
SideFooter, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
|
||||
};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::primitives::Checker;
|
||||
use craft_ui::rails::{LastUsed, ToolRail};
|
||||
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot};
|
||||
use craft_ui::runtime::commands::{CommandSet as _, Commands as _, FirePhase};
|
||||
use craft_ui::runtime::edit::next_gesture_id;
|
||||
use craft_ui::runtime::env::Env;
|
||||
@@ -295,7 +295,8 @@ pub struct SelectMaskWorkspace {
|
||||
view: FullWindowView,
|
||||
mask_view: MaskViewState,
|
||||
tool: SelectMaskTool,
|
||||
last_used: LastUsed<SelectMaskTool>,
|
||||
last_used: Tracked<LastUsed<SelectMaskTool>>,
|
||||
slots: Tracked<Vec<ToolSlot<SelectMaskTool>>>,
|
||||
options: SelectMaskToolOptions,
|
||||
canvas: SelectMaskCanvas,
|
||||
zoom_tool: ZoomTool,
|
||||
@@ -351,7 +352,8 @@ impl SelectMaskWorkspace {
|
||||
checkerboard: open.checkerboard,
|
||||
view: FullWindowView::new(),
|
||||
tool: SelectMaskTool::Quick,
|
||||
last_used: LastUsed::default(),
|
||||
last_used: Tracked::new(LastUsed::default()),
|
||||
slots: Tracked::new(SelectMaskTool::slots()),
|
||||
options: SelectMaskToolOptions::default(),
|
||||
canvas,
|
||||
zoom_tool: ZoomTool::new(open.navigation),
|
||||
@@ -486,7 +488,6 @@ impl SelectMaskWorkspace {
|
||||
let words = env.words::<SelectMaskWords>();
|
||||
let common = env.words::<CommonWords>();
|
||||
let title = FullWindowTitle::new(words.name.clone()).subject(self.subject.clone()).zoom(self.zoom_percent).label(&env);
|
||||
let slots = SelectMaskTool::slots();
|
||||
self.start_pass(ui.ctx());
|
||||
let request = self.request_now();
|
||||
let key = format!("{request:?}");
|
||||
@@ -552,7 +553,7 @@ impl SelectMaskWorkspace {
|
||||
if fired.phase == FirePhase::Release {
|
||||
continue;
|
||||
}
|
||||
let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
|
||||
let slot = work.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
|
||||
let tools: Vec<_> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect();
|
||||
let picked = slot.and_then(|slot| {
|
||||
tool_pick(&tools, slot.id, &work.tool, &work.last_used, PickStep::of(&fired), |_| true).map(|entry| (slot.id, entry.id))
|
||||
@@ -590,9 +591,9 @@ impl SelectMaskWorkspace {
|
||||
let preview = falloff.as_ref().and_then(|falloff| work.canvas.resize().preview(falloff));
|
||||
|
||||
let shown = Row::new().fill().show(ui, |ui, _| {
|
||||
let rail = ToolRail::new(words.tools.clone(), &slots, &work.tool, &work.last_used).show_column(ui, |_, _| {});
|
||||
let rail = ToolRail::new(words.tools.clone(), &work.slots, &work.tool, &work.last_used).show_column(ui, |_, _| {});
|
||||
if let Some(next) = rail.last_used {
|
||||
work.last_used = next;
|
||||
*work.last_used = next;
|
||||
}
|
||||
if let Some(tool) = rail.select {
|
||||
work.pick(Some(&ctx), tool);
|
||||
|
||||
@@ -84,7 +84,7 @@ impl<T> EditPhase<T> {
|
||||
|
||||
/// The tools of Select and Mask's strip, with Photoshop's letters. Quick Selection and Object
|
||||
/// Selection share the W slot, Lasso and Polygonal Lasso the L slot.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum SelectMaskTool {
|
||||
/// W.
|
||||
|
||||
@@ -47,7 +47,7 @@ pub enum VanishingPointStripTool {
|
||||
}
|
||||
|
||||
/// A slot of the strip.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
pub(super) enum Pick {
|
||||
EditPlane,
|
||||
CreatePlane,
|
||||
|
||||
@@ -52,7 +52,7 @@ use craft_behavior::edit_history::Step;
|
||||
use craft_behavior::{CancelReason, EditEvent, EditHistory, Mixed};
|
||||
use craft_ui::bars::StatusMessage;
|
||||
use craft_ui::canvas::{HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick};
|
||||
use craft_ui::contract::{Bind, Job, Pending, Remember as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Job, Pending, Remember as _, Show as _, ShowContainer as _, Tracked};
|
||||
use craft_ui::dialog::{
|
||||
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace,
|
||||
RasterOverlay, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
|
||||
@@ -187,14 +187,21 @@ pub enum VanishingPointEvent {
|
||||
}
|
||||
|
||||
/// What the dialog's body keeps between passes: the view, the strip's memory and the canvas the tools run under.
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Clone)]
|
||||
struct VanishingView {
|
||||
view: FullWindowView,
|
||||
last_used: LastUsed<Pick>,
|
||||
last_used: Tracked<LastUsed<Pick>>,
|
||||
slots: Tracked<Vec<ToolSlot<Pick>>>,
|
||||
/// The canvas the tools run under, to cancel their gestures outside a pass.
|
||||
canvas: Option<Id>,
|
||||
}
|
||||
|
||||
impl Default for VanishingView {
|
||||
fn default() -> Self {
|
||||
VanishingView { view: FullWindowView::default(), last_used: Tracked::default(), slots: Tracked::new(slots()), canvas: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The New Plane form's state.
|
||||
#[derive(Clone, Default)]
|
||||
struct NewPlaneState {
|
||||
@@ -368,7 +375,6 @@ impl FullWindowWorkspace for VanishingPointWorkspace {
|
||||
let words = env.words::<VanishingPointWords>();
|
||||
let common = env.words::<CommonWords>();
|
||||
let title = FullWindowTitle::new(words.name.clone()).subject(self.subject.clone()).zoom(self.zoom_percent).label(&env);
|
||||
let slots = slots();
|
||||
let status: RefCell<Option<Pending<PreviewDone, String>>> = RefCell::new(None);
|
||||
let events = RefCell::new(Vec::<VanishingPointEvent>::new());
|
||||
let shown_canvas = std::cell::Cell::new(None);
|
||||
@@ -416,7 +422,7 @@ impl FullWindowWorkspace for VanishingPointWorkspace {
|
||||
}
|
||||
// A tool key's release picks nothing.
|
||||
let Some(pick) = command.pick().filter(|_| fired.phase != FirePhase::Release) else { continue };
|
||||
let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == pick));
|
||||
let slot = state.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == pick));
|
||||
let tools: Vec<_> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect();
|
||||
let current = Pick::of(work.strip, work.editor.tool());
|
||||
let picked = slot.and_then(|slot| {
|
||||
@@ -464,9 +470,9 @@ impl FullWindowWorkspace for VanishingPointWorkspace {
|
||||
let shown = Row::new()
|
||||
.fill()
|
||||
.show(ui, |ui, _| {
|
||||
let rail = ToolRail::new(words.tools.clone(), &slots, ¤t, &state.last_used).show_column(ui, |_, _| {});
|
||||
let rail = ToolRail::new(words.tools.clone(), &state.slots, ¤t, &state.last_used).show_column(ui, |_, _| {});
|
||||
if let Some(next) = rail.last_used {
|
||||
state.last_used = next;
|
||||
*state.last_used = next;
|
||||
}
|
||||
chosen = rail.select.filter(|pick| *pick != current);
|
||||
let mut canvas = FullWindowCanvas::new(Bind::bound(&mut state.view), image)
|
||||
|
||||
@@ -37,7 +37,7 @@ use std::time::Duration;
|
||||
use craft_behavior::edit_history::Step;
|
||||
use craft_behavior::{CancelReason, EditEvent, EditHistory, Mixed};
|
||||
use craft_ui::canvas::{CanvasTool, HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick};
|
||||
use craft_ui::contract::{Bind, Pattern, Remember as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Pattern, Remember as _, Show as _, ShowContainer as _, Tracked};
|
||||
use craft_ui::dialog::{
|
||||
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace,
|
||||
WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
|
||||
@@ -58,7 +58,7 @@ use serde_json::Value;
|
||||
use crate::ui::live_preview::settings_hash;
|
||||
|
||||
/// The tools of the strip.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum WideAngleTool {
|
||||
/// A.
|
||||
@@ -146,11 +146,12 @@ pub enum WideAngleEvent {
|
||||
}
|
||||
|
||||
/// The state the dialog body keeps between passes: what the app does not read.
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Clone)]
|
||||
struct Body {
|
||||
view: Option<FullWindowView>,
|
||||
tool: WideAngleTool,
|
||||
last_used: LastUsed<WideAngleTool>,
|
||||
last_used: Tracked<LastUsed<WideAngleTool>>,
|
||||
slots: Tracked<Vec<ToolSlot<WideAngleTool>>>,
|
||||
constraint: ConstraintTool,
|
||||
hand: Option<HandTool>,
|
||||
zoom: Option<ZoomTool>,
|
||||
@@ -162,6 +163,24 @@ struct Body {
|
||||
adding: bool,
|
||||
}
|
||||
|
||||
impl Default for Body {
|
||||
fn default() -> Self {
|
||||
let slots = TOOL_SLOT.iter().zip(0..).map(|(&(tool, command), slot)| ToolSlot::new(slot, vec![RailTool::new(tool, command)])).collect();
|
||||
Body {
|
||||
view: None,
|
||||
tool: WideAngleTool::default(),
|
||||
last_used: Tracked::default(),
|
||||
slots: Tracked::new(slots),
|
||||
constraint: ConstraintTool::default(),
|
||||
hand: None,
|
||||
zoom: None,
|
||||
canvas: None,
|
||||
menu: None,
|
||||
adding: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A change the passes ask of the session, applied after the dialog has been shown.
|
||||
enum Action {
|
||||
/// The panel's correction edit.
|
||||
@@ -349,11 +368,9 @@ impl FullWindowWorkspace for WideAngleWorkspace {
|
||||
end_gesture(&ctx, &mut body, CancelReason::UndoDuringGesture);
|
||||
}
|
||||
|
||||
let slots: Vec<ToolSlot<WideAngleTool>> =
|
||||
TOOL_SLOT.iter().zip(0..).map(|(&(tool, command), slot)| ToolSlot::new(slot, vec![RailTool::new(tool, command)])).collect();
|
||||
let mut next = None;
|
||||
while let Some((command, fired)) = cx.take_command::<WideAngleCommands>() {
|
||||
next = pick(&slots, command, &fired, &body).or(next);
|
||||
next = pick(command, &fired, &body).or(next);
|
||||
}
|
||||
|
||||
let image = source.source();
|
||||
@@ -369,10 +386,10 @@ impl FullWindowWorkspace for WideAngleWorkspace {
|
||||
}
|
||||
|
||||
Row::new().fill().show(ui, |ui, _| {
|
||||
let rail = ToolRail::new(words.tools.clone(), &slots, &body.tool, &body.last_used).show_column(ui, |_, _| {});
|
||||
let rail = ToolRail::new(words.tools.clone(), &body.slots, &body.tool, &body.last_used).show_column(ui, |_, _| {});
|
||||
next = rail.select.or(next);
|
||||
if let Some(last_used) = rail.last_used {
|
||||
body.last_used = last_used;
|
||||
*body.last_used = last_used;
|
||||
}
|
||||
if let Some(tool) = next.take().filter(|tool| *tool != body.tool) {
|
||||
end_gesture(&ctx, &mut body, CancelReason::Removed);
|
||||
@@ -566,12 +583,12 @@ fn edit_name<'a>(words: &'a WideAngleWords, edit: &WideAngleConstraintEdit) -> &
|
||||
}
|
||||
|
||||
/// The tool a fired tool command picks, through its slot's pick rule; a tool key's release picks nothing.
|
||||
fn pick(slots: &[ToolSlot<WideAngleTool>], command: WideAngleCommands, fired: &Fired, body: &Body) -> Option<WideAngleTool> {
|
||||
fn pick(command: WideAngleCommands, fired: &Fired, body: &Body) -> Option<WideAngleTool> {
|
||||
if fired.phase == FirePhase::Release {
|
||||
return None;
|
||||
}
|
||||
let tool = TOOL_SLOT.iter().find(|(_, c)| *c == command)?.0;
|
||||
let slot = slots.iter().find(|slot| slot.tools.iter().any(|t| t.id == tool))?;
|
||||
let slot = body.slots.iter().find(|slot| slot.tools.iter().any(|t| t.id == tool))?;
|
||||
let visible: Vec<&RailTool<WideAngleTool>> = slot.tools.iter().collect();
|
||||
tool_pick(&visible, slot.id, &body.tool, &body.last_used, PickStep::of(fired), |_| true).map(|t| t.id)
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ craft-xml = { workspace = true }
|
||||
egui = { workspace = true, optional = true }
|
||||
craft-i18n = { workspace = true }
|
||||
craft-host = { workspace = true }
|
||||
# Chords and command refs are held in `Tracked` models.
|
||||
craft-tracked = { workspace = true }
|
||||
craft-ui-macros = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# `serde` for setting `RawInput` fields only the suite's egui fork has.
|
||||
|
||||
@@ -23,7 +23,7 @@ macro_rules! keys {
|
||||
/// A key on the keyboard, independent of any UI toolkit.
|
||||
///
|
||||
/// Digits are the main row; numeric keypad keys map to the same keys.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, craft_ui_macros::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum Key {
|
||||
$(#[allow(missing_docs)] $variant),*
|
||||
@@ -388,7 +388,7 @@ impl<'de> Deserialize<'de> for Key {
|
||||
}
|
||||
|
||||
/// Modifier keys held with a chord's key.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, craft_ui_macros::PlainData)]
|
||||
pub struct Mods {
|
||||
/// The command modifier: ⌘ on macOS, Ctrl on Windows and Linux.
|
||||
pub cmd: bool,
|
||||
@@ -453,7 +453,7 @@ impl Mods {
|
||||
}
|
||||
|
||||
/// A key with modifiers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, craft_ui_macros::PlainData)]
|
||||
pub struct Chord {
|
||||
/// The modifiers held with the key.
|
||||
pub mods: Mods,
|
||||
|
||||
@@ -10,13 +10,14 @@ use serde_json::Value;
|
||||
pub const MAX_KEY: usize = 256;
|
||||
|
||||
/// A command id with the parameters a binding runs it with.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CommandRef {
|
||||
/// The command's id.
|
||||
pub id: String,
|
||||
/// `Null` for no parameters.
|
||||
#[serde(default)]
|
||||
#[plain_data(assume = "a JSON value owns its data and has no interior mutability")]
|
||||
pub params: Value,
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ pub(crate) mod stories;
|
||||
use craft_behavior::{EditEvent, IconId, Mixed, SelectionChange};
|
||||
use craft_theme::{ControlSize, LabelColor};
|
||||
use craft_ui::buttons::ToggleButton;
|
||||
use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::contract::{Bind, Entry, MemoProps, NoValue, Outcome, PlainData, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::list::{ListWords, label_color_label};
|
||||
use craft_ui::pickers::Select;
|
||||
@@ -26,7 +26,7 @@ use super::tree::{LayerInfo, LayerKind, LayerPart, LayerTree};
|
||||
|
||||
/// What the Layers panel filters by: the filter bar's type select, Photoshop's types in its order
|
||||
/// (Selected waits for the feature that needs 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, MemoProps)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum FilterBy {
|
||||
@@ -73,7 +73,7 @@ impl FilterBy {
|
||||
}
|
||||
|
||||
/// A layer kind the Kind filter toggles.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum FilterKind {
|
||||
@@ -125,7 +125,7 @@ impl LayerKind {
|
||||
|
||||
/// A layer effect kind, as the Effect filter picks it and [`LayerInfo::effect_kinds`] reports it,
|
||||
/// in Photoshop's order. `Overlay` stands for Color, Gradient and Pattern Overlay.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, PlainData, MemoProps)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum EffectKind {
|
||||
@@ -177,7 +177,7 @@ impl EffectKind {
|
||||
|
||||
/// A layer attribute the Attribute filter picks, or its opposite: Photoshop's nine attributes,
|
||||
/// then their opposites. Each opposite lists the layers (and groups) its attribute doesn't.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum LayerAttribute {
|
||||
@@ -303,7 +303,7 @@ impl LayerAttribute {
|
||||
}
|
||||
|
||||
/// Where a smart object's contents come from, as [`LayerInfo::smart`] reports it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum SmartSource {
|
||||
/// A file outside the document.
|
||||
@@ -313,7 +313,7 @@ pub enum SmartSource {
|
||||
}
|
||||
|
||||
/// A kind of smart object the Smart Object filter toggles.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum SmartKind {
|
||||
@@ -335,7 +335,7 @@ impl SmartKind {
|
||||
/// document) and passes it to [`LayersPanel::filter`](super::panel::LayersPanel::filter); every
|
||||
/// field has a serde default. Each type reads its own field; the others keep their values while
|
||||
/// another type is picked.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, MemoProps)]
|
||||
#[serde(default)]
|
||||
#[non_exhaustive]
|
||||
pub struct LayerFilter {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
//! `FakeLayers`: a `LayerTree` for stories and tests.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use craft_theme::LabelColor;
|
||||
use craft_ui::contract::Entry;
|
||||
use craft_ui::contract::{Entry, PlainData};
|
||||
use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut as S, blend_entries};
|
||||
use craft_ui::runtime::env::Label;
|
||||
|
||||
@@ -15,7 +13,7 @@ use super::tree::{
|
||||
};
|
||||
|
||||
/// One layer of a [`FakeLayers`] tree.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct FakeLayer {
|
||||
/// The layer's id.
|
||||
@@ -36,7 +34,7 @@ pub struct FakeLayer {
|
||||
|
||||
/// A fake document's layers, kept in plain vectors: the tests' and stories' `LayerTree`. Ids are
|
||||
/// `u32`; the app's state (open groups, selection, effects open) is a field the test sets.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
#[derive(Clone, Debug, Default, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct FakeLayers {
|
||||
/// Every layer, each group before its children, topmost first among siblings.
|
||||
@@ -45,15 +43,11 @@ pub struct FakeLayers {
|
||||
pub selection: LayerSelection<u32>,
|
||||
/// The layer under the pointer on the canvas.
|
||||
pub hovered: Option<u32>,
|
||||
/// The revision the tree reports; `None` walks every pass.
|
||||
pub revision: Option<u64>,
|
||||
/// The layers with no visible pixels, which only the app knows: the Attribute filter's Empty.
|
||||
pub empty: Vec<u32>,
|
||||
/// The linked smart objects whose file is not there, which only the app knows: the Smart Object
|
||||
/// filter's Missing.
|
||||
pub missing: Vec<u32>,
|
||||
info_calls: Cell<usize>,
|
||||
sub_rows_calls: Cell<usize>,
|
||||
}
|
||||
|
||||
impl FakeLayers {
|
||||
@@ -301,16 +295,6 @@ impl FakeLayers {
|
||||
tree.selection.sub_row = Some(LayerRowKey::Filters(smart, Some(0)));
|
||||
tree
|
||||
}
|
||||
|
||||
/// How many times `info` was called since the last [`take_info_calls`](Self::take_info_calls).
|
||||
pub fn take_info_calls(&self) -> usize {
|
||||
self.info_calls.replace(0)
|
||||
}
|
||||
|
||||
/// How many times `sub_rows` was called since the last [`take_sub_rows_calls`](Self::take_sub_rows_calls).
|
||||
pub fn take_sub_rows_calls(&self) -> usize {
|
||||
self.sub_rows_calls.replace(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl FakeLayers {
|
||||
@@ -380,7 +364,6 @@ impl LayerTree for FakeLayers {
|
||||
}
|
||||
|
||||
fn info(&self, id: &u32) -> LayerInfo {
|
||||
self.info_calls.set(self.info_calls.get() + 1);
|
||||
self.layer(id).map(|layer| layer.info.clone()).unwrap_or_else(|| LayerInfo::new(String::new(), LayerKind::Pixel))
|
||||
}
|
||||
|
||||
@@ -400,7 +383,6 @@ impl LayerTree for FakeLayers {
|
||||
}
|
||||
|
||||
fn sub_rows(&self, id: &u32, group: SubRowGroup) -> Option<SubRows> {
|
||||
self.sub_rows_calls.set(self.sub_rows_calls.get() + 1);
|
||||
let layer = self.layer(id)?;
|
||||
match group {
|
||||
SubRowGroup::Effects => layer.effects.clone(),
|
||||
@@ -468,10 +450,6 @@ impl LayerTree for FakeLayers {
|
||||
self.hovered
|
||||
}
|
||||
|
||||
fn revision(&self) -> Option<u64> {
|
||||
self.revision
|
||||
}
|
||||
|
||||
fn footer(&self) -> LayersFooterState {
|
||||
let active = self.selection.active.is_some();
|
||||
LayersFooterState {
|
||||
|
||||
@@ -77,7 +77,7 @@ pub(super) fn show_body<T: LayerTree>(
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.can_rename(|key| matches!(key, LayerRowKey::Layer(id) if tree.info(id).renamable))
|
||||
.accepts(|drag: &ListDrag<LayerRowKey<T::Id>>, _over, insert| {
|
||||
accepts_drop(tree, drag, &order, insert, craft_ui::runtime::pointer::frame(&ctx).mods)
|
||||
accepts_drop(tree, drag, order, insert, craft_ui::runtime::pointer::frame(&ctx).mods)
|
||||
})
|
||||
.drag_payload({
|
||||
let document = cx.document;
|
||||
@@ -98,7 +98,7 @@ pub(super) fn show_body<T: LayerTree>(
|
||||
hovered = Some(id.clone());
|
||||
}
|
||||
let row = build_row(cx, key).cells(item.cells()).state(item.row.clone());
|
||||
match rows.rows.get(item.at) {
|
||||
match rows.rows().get(item.at) {
|
||||
Some(shown) if shown.has_children => row.depth(shown.paint_depth).group(shown.open),
|
||||
Some(shown) => row.depth(shown.paint_depth),
|
||||
None => row,
|
||||
@@ -107,7 +107,7 @@ pub(super) fn show_body<T: LayerTree>(
|
||||
|
||||
let mut events: Vec<LayersEvent<T::Id>> = reveal.opens.iter().cloned().map(LayersEvent::Open).collect();
|
||||
let drop_preview = match &out.pending_drop {
|
||||
Some(PendingDrop::Reorder(mv)) if cx.options.preview_on_canvas_when_reordering => match layer_drop(mv, &order, &parent_of, filtered) {
|
||||
Some(PendingDrop::Reorder(mv)) if cx.options.preview_on_canvas_when_reordering => match layer_drop(mv, order, &parent_of, filtered) {
|
||||
Some(LayerDrop::Layers(layers)) => Some(layers),
|
||||
_ => None,
|
||||
},
|
||||
@@ -115,7 +115,7 @@ pub(super) fn show_body<T: LayerTree>(
|
||||
};
|
||||
let selection_changed = out.events.iter().any(|event| matches!(event, CollectionEvent::Selection(_)));
|
||||
let list_events = out.events;
|
||||
map_events(cx, &order, &parent_of, filtered, lock_name, session, list_events, &mut events);
|
||||
map_events(cx, order, &parent_of, filtered, lock_name, session, list_events, &mut events);
|
||||
if selection_changed {
|
||||
let mut layers: Vec<T::Id> = Vec::new();
|
||||
for key in &selection.items {
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
use craft_behavior::{ColumnKey, DisplayOrder, ItemSource, Selection};
|
||||
use craft_keymap::Mods;
|
||||
use craft_ui::contract::{OpenChange, SweepApply};
|
||||
use craft_ui::contract::{BodyCx, MemoKey, MemoProps, OpenChange, Revision, SweepApply, Tracked};
|
||||
use craft_ui::list::{ThumbTarget, tree_steps};
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::super::context::PanelContext;
|
||||
use super::super::events::LayerColumn;
|
||||
@@ -27,55 +28,91 @@ pub(in crate::ui::panel) struct DisplayRow<Id> {
|
||||
pub(super) open: bool,
|
||||
}
|
||||
|
||||
/// The rows of the tree as the list shows them: layers, and under each layer whose effects are open
|
||||
/// the Smart Filter and effect rows.
|
||||
pub(in crate::ui::panel) struct LayerRows<'t, T: LayerTree> {
|
||||
tree: &'t T,
|
||||
pub(in crate::ui::panel) rows: Vec<DisplayRow<T::Id>>,
|
||||
/// The filter left a layer out: rows list at their shown depth, so a drop finds its place by its neighbours.
|
||||
pub(in crate::ui::panel) filtered: bool,
|
||||
revision: Option<u64>,
|
||||
/// 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) tree: Revision,
|
||||
pub(in crate::ui::panel) filter: &'a LayerFilter,
|
||||
pub(in crate::ui::panel) opened: &'a [Id],
|
||||
}
|
||||
|
||||
impl<'t, T: LayerTree> LayerRows<'t, T> {
|
||||
/// The rows for `filter`, with the groups in `opened` shown open besides the tree's own.
|
||||
pub(in crate::ui::panel) fn new(tree: &'t T, filter: &LayerFilter, opened: &[T::Id]) -> Self {
|
||||
/// The display order of the tree, derived from a [`RowsKey`] and kept across passes.
|
||||
pub(in crate::ui::panel) struct RowsModel<Id> {
|
||||
pub(in crate::ui::panel) rows: Vec<DisplayRow<Id>>,
|
||||
/// The row keys in display order.
|
||||
keys: Vec<LayerRowKey<Id>>,
|
||||
/// The filter left a layer out: rows list at their shown depth, so a drop finds its place by its neighbours.
|
||||
pub(in crate::ui::panel) filtered: bool,
|
||||
/// The number the list keeps its display order by: it follows the key.
|
||||
revision: u64,
|
||||
}
|
||||
|
||||
impl<Id: Clone + PartialEq> RowsModel<Id> {
|
||||
/// The rows of `tree` for `filter`, with the groups in `opened` shown open besides the tree's own.
|
||||
fn walk<T: LayerTree<Id = Id>>(tree: &T, filter: &LayerFilter, opened: &[Id], revision: u64) -> Self {
|
||||
let active = filter.active();
|
||||
let mut walk = Walk { tree, filter, active, open_all: active && filter.lists_closed_contents(), opened, left_out: false };
|
||||
let mut rows = Vec::new();
|
||||
push_level(&mut walk, tree.children(None), Level { shown: 0, true_depth: 0 }, &mut rows);
|
||||
let revision = tree.revision().filter(|_| !active && opened.is_empty());
|
||||
LayerRows { tree, rows, filtered: walk.left_out, revision }
|
||||
let keys = rows.iter().map(|row| row.key.clone()).collect();
|
||||
RowsModel { rows, keys, filtered: walk.left_out, revision }
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the tree as the list shows them: layers, and under each layer whose effects are open
|
||||
/// the Smart Filter and effect rows.
|
||||
pub(in crate::ui::panel) struct LayerRows<'t, T: LayerTree> {
|
||||
tree: &'t T,
|
||||
model: Arc<RowsModel<T::Id>>,
|
||||
}
|
||||
|
||||
impl<'t, T: LayerTree> LayerRows<'t, T> {
|
||||
/// The rows for `filter` and `opened`, derived by the body `cx` from the tracked `tree`.
|
||||
pub(in crate::ui::panel) fn new(cx: &BodyCx<'_>, tree: &'t Tracked<T>, filter: &LayerFilter, opened: &[T::Id]) -> Self {
|
||||
let key = RowsKey { tree: tree.revision(), filter, opened };
|
||||
// The low half of the key's hash tells the list when the order changed.
|
||||
let revision = MemoKey::of(&key) as u64;
|
||||
let model = cx.derived(&key, || RowsModel::walk(&**tree, filter, opened, revision));
|
||||
LayerRows { tree: &**tree, model }
|
||||
}
|
||||
|
||||
pub(in crate::ui::panel) fn keys(&self) -> Vec<LayerRowKey<T::Id>> {
|
||||
self.rows.iter().map(|row| row.key.clone()).collect()
|
||||
pub(in crate::ui::panel) fn rows(&self) -> &[DisplayRow<T::Id>] {
|
||||
&self.model.rows
|
||||
}
|
||||
|
||||
pub(in crate::ui::panel) fn filtered(&self) -> bool {
|
||||
self.model.filtered
|
||||
}
|
||||
|
||||
pub(in crate::ui::panel) fn keys(&self) -> &[LayerRowKey<T::Id>] {
|
||||
&self.model.keys
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: LayerTree> DisplayOrder<LayerRowKey<T::Id>> for LayerRows<'_, T> {
|
||||
fn len(&self) -> usize {
|
||||
self.rows.len()
|
||||
self.model.rows.len()
|
||||
}
|
||||
|
||||
fn key(&self, at: usize) -> LayerRowKey<T::Id> {
|
||||
self.rows[at].key.clone()
|
||||
self.model.rows[at].key.clone()
|
||||
}
|
||||
|
||||
fn depth(&self, at: usize) -> usize {
|
||||
self.rows[at].depth
|
||||
self.model.rows[at].depth
|
||||
}
|
||||
|
||||
fn has_children(&self, at: usize) -> bool {
|
||||
self.rows[at].has_children
|
||||
self.model.rows[at].has_children
|
||||
}
|
||||
|
||||
fn open(&self, at: usize) -> bool {
|
||||
self.rows[at].open
|
||||
self.model.rows[at].open
|
||||
}
|
||||
|
||||
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
|
||||
match &self.rows[at].key {
|
||||
match &self.model.rows[at].key {
|
||||
LayerRowKey::Layer(id) | LayerRowKey::Mask(id, _) => Some(Cow::Owned(self.tree.info(id).name)),
|
||||
LayerRowKey::Effects(id, index) => sub_label(self.tree, id, SubRowGroup::Effects, *index),
|
||||
LayerRowKey::Filters(id, index) => sub_label(self.tree, id, SubRowGroup::SmartFilters, *index),
|
||||
@@ -83,13 +120,13 @@ impl<T: LayerTree> DisplayOrder<LayerRowKey<T::Id>> for LayerRows<'_, T> {
|
||||
}
|
||||
|
||||
fn revision(&self) -> Option<u64> {
|
||||
self.revision
|
||||
Some(self.model.revision)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: LayerTree> ItemSource<LayerRowKey<T::Id>> for LayerRows<'_, T> {
|
||||
fn toggled(&self, at: usize, column: &ColumnKey) -> bool {
|
||||
match &self.rows[at].key {
|
||||
match &self.model.rows[at].key {
|
||||
LayerRowKey::Layer(id) if *column == EYE => self.tree.info(id).visible,
|
||||
LayerRowKey::Layer(id) if *column == LOCK => self.tree.info(id).locks.any(),
|
||||
LayerRowKey::Effects(id, index) if *column == EYE => sub_on(self.tree, id, SubRowGroup::Effects, *index),
|
||||
@@ -99,7 +136,7 @@ impl<T: LayerTree> ItemSource<LayerRowKey<T::Id>> for LayerRows<'_, T> {
|
||||
}
|
||||
|
||||
fn sub_row(&self, at: usize) -> Option<usize> {
|
||||
self.rows[at].sub_steps
|
||||
self.model.rows[at].sub_steps
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ pub(crate) use row::FX_BADGE;
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use craft_ui::contract::{Bind, CommandSet as _, Commands as _, NoValue, Outcome, Show, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, CommandSet as _, Commands as _, NoValue, Outcome, Show, ShowContainer as _, Tracked};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::list::ListWords;
|
||||
use craft_ui::primitives::textures::{ThumbSource, Thumbnails};
|
||||
@@ -160,7 +160,7 @@ impl<Id> Default for Session<Id> {
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
#[pattern(probe(LayersPanel<'static, crate::ui::mock::FakeLayers>))]
|
||||
pub struct LayersPanel<'a, T: LayerTree> {
|
||||
tree: &'a T,
|
||||
tree: &'a Tracked<T>,
|
||||
settings: Option<&'a LayersSettings>,
|
||||
thumbnails: Option<ThumbHost<'a, T::Id>>,
|
||||
filter: Option<Bind<'a, LayerFilter>>,
|
||||
@@ -213,8 +213,9 @@ impl<Id> Outcome for LayersOutput<Id> {
|
||||
}
|
||||
|
||||
impl<'a, T: LayerTree> LayersPanel<'a, T> {
|
||||
/// The panel showing `tree`.
|
||||
pub fn new(tree: &'a T) -> Self {
|
||||
/// The panel showing `tree`. The panel derives the display order from the tracked revision, so an edit of the tree
|
||||
/// through the `Tracked` is what makes it walk the tree again.
|
||||
pub fn new(tree: &'a Tracked<T>) -> Self {
|
||||
Self {
|
||||
tree,
|
||||
settings: None,
|
||||
@@ -339,7 +340,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
|
||||
/// rows, the footer. Events are reported in that order.
|
||||
pub fn show(self, ui: &mut Ui) -> LayersOutput<T::Id> {
|
||||
let LayersPanel {
|
||||
tree,
|
||||
tree: tracked,
|
||||
settings,
|
||||
thumbnails,
|
||||
mut filter,
|
||||
@@ -355,6 +356,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
|
||||
rename,
|
||||
document,
|
||||
} = self;
|
||||
let tree: &T = tracked;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<LayersPanelWords>();
|
||||
let list_words = env.words::<ListWords>();
|
||||
@@ -440,13 +442,13 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
|
||||
})
|
||||
.show(ui, |ui, stack| {
|
||||
let filter = current.borrow().clone();
|
||||
let session = stack.memory::<Session<T::Id>>();
|
||||
let plan = reveal_plan(tree, reveal.clone());
|
||||
let rows = LayerRows::new(tree, &filter, &plan.opened());
|
||||
let rows = LayerRows::new(stack, tracked, &filter, &plan.opened());
|
||||
let session = stack.memory::<Session<T::Id>>();
|
||||
if let Some(layer) = rename.clone() {
|
||||
start_rename(ui, list, layer);
|
||||
}
|
||||
let body = show_body(ui, &cx, &rows, session, &plan, rows.filtered, &unlock_label);
|
||||
let body = show_body(ui, &cx, &rows, session, &plan, rows.filtered(), &unlock_label);
|
||||
let menus = show_row_menus(ui, &cx, &body.response, row_menu.as_deref(), session);
|
||||
let mut reported = body.events;
|
||||
reported.extend(menus);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! tree; extra columns; effects and Smart Filters open; filtered by Artboard and by Group, which keep each group open or
|
||||
//! closed.
|
||||
|
||||
use craft_ui::contract::Tracked;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
@@ -35,14 +36,14 @@ fn layers_panel_tree(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = selected();
|
||||
// PhotoCraft's Hide Layers key, which the app hands the panel.
|
||||
let hide_layers = craft_keymap::Chord::new(craft_keymap::Mods::CMD, craft_keymap::Key::Comma);
|
||||
let shown = LayersPanel::new(&tree).visibility_key(hide_layers).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).visibility_key(hide_layers).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
#[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)]
|
||||
fn layers_panel_no_active_layer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = FakeLayers::sample();
|
||||
let shown = LayersPanel::new(&tree).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
@@ -50,7 +51,7 @@ fn layers_panel_no_active_layer(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu
|
||||
fn layers_panel_filtered(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = selected();
|
||||
let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Name, name: String::from("o"), ..LayerFilter::default() });
|
||||
let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).filter(filter_at.bind(filter)).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
@@ -59,14 +60,14 @@ fn layers_panel_filtered(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
fn layers_panel_target_cell(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = selected();
|
||||
let target = |_: &u32, info: &LayerInfo| Icon::new(IconSpec::svg(IconId::new(if info.visible { "target" } else { "circle" })));
|
||||
let shown = LayersPanel::new(&tree).trailing(target, |_, _| {}).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).trailing(target, |_, _| {}).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
#[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)]
|
||||
fn layers_panel_extra_columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = selected();
|
||||
let shown = LayersPanel::new(&tree).lock_column(true).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).lock_column(true).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
@@ -75,7 +76,7 @@ fn layers_panel_extra_columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput
|
||||
#[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)]
|
||||
fn layers_panel_row_kinds(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = FakeLayers::row_kinds();
|
||||
let shown = LayersPanel::new(&tree).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
@@ -84,7 +85,7 @@ fn layers_panel_row_kinds(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
fn layers_panel_frame_selected(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let mut tree = FakeLayers::row_kinds();
|
||||
tree.selection = LayerSelection::new(vec![2], Some(2), LayerPart::Pixels);
|
||||
let shown = LayersPanel::new(&tree).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
@@ -96,7 +97,7 @@ fn layers_panel_effects_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
for layer in &mut tree.layers {
|
||||
layer.effects_open = layer.effects.is_some() || layer.smart_filters.is_some();
|
||||
}
|
||||
let shown = LayersPanel::new(&tree).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
@@ -105,7 +106,7 @@ fn layers_panel_effects_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
fn layers_panel_by_artboard(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = FakeLayers::boards();
|
||||
let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Artboard, ..LayerFilter::default() });
|
||||
let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).filter(filter_at.bind(filter)).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
@@ -114,6 +115,6 @@ fn layers_panel_by_artboard(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
fn layers_panel_by_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = FakeLayers::fifty();
|
||||
let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Group, ..LayerFilter::default() });
|
||||
let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui);
|
||||
let shown = LayersPanel::new(&Tracked::new(tree)).filter(filter_at.bind(filter)).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
@@ -11,17 +11,20 @@ use std::hash::Hash;
|
||||
use craft_behavior::IconId;
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::LabelColor;
|
||||
use craft_ui::contract::{Entry, ReorderMove};
|
||||
use craft_ui::contract::{Entry, MemoProps, PlainData, ReorderMove};
|
||||
use craft_ui::list::ThumbTarget;
|
||||
|
||||
use super::filter::{EffectKind, LayerFilter, SmartSource};
|
||||
use super::panel::MenuTarget;
|
||||
|
||||
/// The app's view of its layers, built per pass over its document (no copies of the layers).
|
||||
/// The app's model of its layers, held in a [`Tracked`](craft_ui::contract::Tracked) the panel reads
|
||||
/// (`LayersPanel::new(&Tracked<T>)`). It is plain data, so every edit moves the tracked revision, which keys what
|
||||
/// the panel derives from the tree.
|
||||
///
|
||||
/// ```ignore
|
||||
/// struct PhotoLayers<'a> { doc: &'a Document, ui: &'a UiState }
|
||||
/// impl LayerTree for PhotoLayers<'_> {
|
||||
/// #[derive(PlainData)]
|
||||
/// struct PhotoLayers { layers: LayerIndex, open: HashSet<LayerId> }
|
||||
/// impl LayerTree for PhotoLayers {
|
||||
/// type Id = LayerId;
|
||||
/// fn children(&self, parent: Option<&LayerId>) -> Vec<LayerId> { /* top of the stack first */ }
|
||||
/// /* … */
|
||||
@@ -30,11 +33,12 @@ use super::panel::MenuTarget;
|
||||
///
|
||||
/// The panel calls [`info`](Self::info) only for the rows it draws (the rows in view and one
|
||||
/// above and below), so a tree of 10,000 layers costs what its visible rows cost.
|
||||
/// [`children`](Self::children) and [`is_open`](Self::is_open) are walked once per pass to build
|
||||
/// the display order, unless [`revision`](Self::revision) says nothing changed.
|
||||
pub trait LayerTree {
|
||||
/// The app's layer id: the key of a row, of its thumbnails and of every event.
|
||||
type Id: Clone + Eq + Hash + Debug + Send + Sync + 'static;
|
||||
/// [`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;
|
||||
|
||||
/// 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.
|
||||
@@ -107,18 +111,10 @@ pub trait LayerTree {
|
||||
fn hovered(&self) -> Option<Self::Id> {
|
||||
None
|
||||
}
|
||||
|
||||
/// A number that changes whenever rows are added, removed, moved, opened or closed, or an
|
||||
/// effects or Smart Filters row is added or removed; with it
|
||||
/// the panel keeps its display order between passes instead of walking the tree each pass.
|
||||
/// `None` (the default) walks every pass.
|
||||
fn revision(&self) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// What one layer row shows. Build it with [`LayerInfo::new`] and set the fields that differ.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct LayerInfo {
|
||||
/// The layer's name, shown on one line with an ellipsis.
|
||||
@@ -240,7 +236,7 @@ impl LayerInfo {
|
||||
|
||||
/// The mark in a layer thumbnail's corner ([`LayerInfo::thumb_badge`]), in the badge box the mask
|
||||
/// badges use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum ThumbBadge {
|
||||
/// A smart object: a window glyph.
|
||||
@@ -250,7 +246,7 @@ pub enum ThumbBadge {
|
||||
}
|
||||
|
||||
/// What a layer is.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum LayerKind {
|
||||
/// Pixels (PhotoCraft's raster layer).
|
||||
@@ -284,7 +280,7 @@ pub enum LayerKind {
|
||||
}
|
||||
|
||||
/// The part of a layer edits go to, and the thumbnail that stands for it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum LayerPart {
|
||||
/// The layer's own pixels; a frame as a whole, its shape and content together.
|
||||
@@ -303,7 +299,7 @@ pub enum LayerPart {
|
||||
}
|
||||
|
||||
/// One mask of a layer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct MaskInfo {
|
||||
/// [`LayerPart::LayerMask`] or [`LayerPart::VectorMask`].
|
||||
@@ -316,7 +312,7 @@ pub struct MaskInfo {
|
||||
}
|
||||
|
||||
/// A layer's locks. Start from `LayerLocks::default()` (nothing locked) and set the fields that are on.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct LayerLocks {
|
||||
/// Lock transparent pixels.
|
||||
@@ -378,7 +374,7 @@ impl LockKind {
|
||||
}
|
||||
|
||||
/// The selection as the app keeps it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct LayerSelection<Id> {
|
||||
/// The selected layers, in the order they were selected.
|
||||
@@ -406,7 +402,7 @@ impl<Id> Default for LayerSelection<Id> {
|
||||
}
|
||||
|
||||
/// The key of one row of the panel, and of what a drag carries.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum LayerRowKey<Id> {
|
||||
/// A layer's row.
|
||||
@@ -446,7 +442,7 @@ pub enum SubRowGroup {
|
||||
}
|
||||
|
||||
/// The effects or Smart Filter rows of a layer: a header row, then the items, top first.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct SubRows {
|
||||
/// The "Effects" or "Smart Filters" row; its eye shows or hides them all.
|
||||
@@ -463,7 +459,7 @@ impl SubRows {
|
||||
}
|
||||
|
||||
/// One effects or Smart Filter row.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct SubRow {
|
||||
/// The row's text: "Effects", "Drop Shadow", "Gaussian Blur".
|
||||
|
||||
@@ -5,6 +5,7 @@ pub(crate) mod comps;
|
||||
pub(crate) mod panel_drag_menu;
|
||||
pub(crate) mod panel_filter;
|
||||
pub(crate) mod panel_input;
|
||||
pub(crate) mod panel_memo;
|
||||
pub(crate) mod panel_order;
|
||||
pub(crate) mod panel_reveal;
|
||||
pub(crate) mod panel_rows;
|
||||
|
||||
@@ -9,7 +9,7 @@ use craft_layers::ui::mock::FakeLayers;
|
||||
use craft_layers::ui::panel::{LayerDrop, LayerSelect, LayersDrag, LayersEvent, LayersPanel, MaskMove};
|
||||
use craft_layers::ui::tree::{LayerPart, LayerRowKey, LayerTree as _};
|
||||
use craft_theme::LabelColor;
|
||||
use craft_ui::contract::Entry;
|
||||
use craft_ui::contract::{Entry, Tracked};
|
||||
use craft_ui::testing::{Fixture, Target, pointer, trial};
|
||||
use egui::{Modifiers, Pos2, Vec2};
|
||||
use std::cell::RefCell;
|
||||
@@ -27,7 +27,7 @@ const PANEL: Vec2 = Vec2::new(420.0, 560.0);
|
||||
fn rig() -> (Fixture, Seen, Asked) {
|
||||
let (seen, asked): (Seen, Asked) = (Rc::default(), Rc::default());
|
||||
let (sink, menus) = (Rc::clone(&seen), Rc::clone(&asked));
|
||||
let tree = FakeLayers::sample();
|
||||
let tree = Tracked::new(FakeLayers::sample());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = LayersPanel::new(&tree)
|
||||
.row_menu(|target| {
|
||||
|
||||
@@ -6,7 +6,7 @@ use craft_layers::ui::filter::{EffectKind, FilterBy, FilterKind, LayerAttribute,
|
||||
use craft_layers::ui::mock::FakeLayers;
|
||||
use craft_layers::ui::panel::{LayersEvent, LayersPanel};
|
||||
use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerSelection};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::contract::{Bind, Tracked};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::Vec2;
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -23,14 +23,14 @@ type Shared<T> = Rc<RefCell<T>>;
|
||||
/// A panel over the artboard tree and a filter the trial sets; Find Layers runs in the pass after `find` is set.
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
tree: Shared<FakeLayers>,
|
||||
tree: Shared<Tracked<FakeLayers>>,
|
||||
filter: Shared<LayerFilter>,
|
||||
find: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
/// The rig, its filter set by `start`.
|
||||
fn rig(start: impl FnOnce(&mut LayerFilter)) -> Rig {
|
||||
let tree = Rc::new(RefCell::new(FakeLayers::boards()));
|
||||
let tree = Rc::new(RefCell::new(Tracked::new(FakeLayers::boards())));
|
||||
let mut filter = LayerFilter::default();
|
||||
start(&mut filter);
|
||||
let filter = Rc::new(RefCell::new(filter));
|
||||
@@ -196,7 +196,7 @@ fn find_layers_puts_the_caret_in_the_name_field_with_its_text_selected() {
|
||||
/// Kind, reported as a filter event so the app stores it.
|
||||
#[trial]
|
||||
fn the_type_select_lists_only_the_offered_types() {
|
||||
let tree = Rc::new(RefCell::new(FakeLayers::boards()));
|
||||
let tree = Rc::new(RefCell::new(Tracked::new(FakeLayers::boards())));
|
||||
let mut start = LayerFilter::default();
|
||||
start.by = FilterBy::Artboard;
|
||||
let filter = Rc::new(RefCell::new(start));
|
||||
@@ -226,7 +226,7 @@ fn the_type_select_lists_only_the_offered_types() {
|
||||
fn a_filter_the_bar_applies_deselects_what_it_hides() {
|
||||
let mut tree = FakeLayers::sample();
|
||||
tree.selection = LayerSelection::new(vec![3, 2, 4], Some(3), LayerPart::Pixels);
|
||||
let tree = Rc::new(RefCell::new(tree));
|
||||
let tree = Rc::new(RefCell::new(Tracked::new(tree)));
|
||||
let filter = Rc::new(RefCell::new(LayerFilter::default()));
|
||||
let find = Rc::new(Cell::new(false));
|
||||
let seen: Shared<Vec<LayersEvent<u32>>> = Rc::default();
|
||||
|
||||
@@ -5,7 +5,7 @@ use craft_behavior::{EditEvent, EditHistory, Mixed, SelectionChange};
|
||||
use craft_layers::ui::mock::FakeLayers;
|
||||
use craft_layers::ui::panel::{LayerColumn, LayerDrop, LayerPosition, LayerToggle, LayersEvent, LayersPanel};
|
||||
use craft_layers::ui::tree::{LayerKind, LayerPart, LayerSelection};
|
||||
use craft_ui::contract::{MemoProps, MemoView, Outbox, PlainData, Tracked};
|
||||
use craft_ui::contract::{MemoProps, MemoView, Outbox, Tracked};
|
||||
use craft_ui::testing::access::focused_key;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, Target, pointer, trial};
|
||||
@@ -15,7 +15,7 @@ use std::rc::Rc;
|
||||
|
||||
/// The app around the panel: the tree it shows and what it reported.
|
||||
struct App {
|
||||
tree: FakeLayers,
|
||||
tree: Tracked<FakeLayers>,
|
||||
events: Vec<LayersEvent<u32>>,
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ fn apply(tree: &mut FakeLayers, event: &LayersEvent<u32>) {
|
||||
|
||||
fn show(ui: &mut Ui, app: &mut App) {
|
||||
let App { tree, events } = app;
|
||||
let out = LayersPanel::new(&*tree).show(ui);
|
||||
let out = LayersPanel::new(tree).show(ui);
|
||||
for event in &out.events {
|
||||
apply(tree, event);
|
||||
}
|
||||
@@ -77,7 +77,7 @@ fn show(ui: &mut Ui, app: &mut App) {
|
||||
|
||||
/// The panel over `tree`, in a room tall enough for every row.
|
||||
fn rig(tree: FakeLayers) -> (Fixture, Shared) {
|
||||
let app = Rc::new(RefCell::new(App { tree, events: Vec::new() }));
|
||||
let app = Rc::new(RefCell::new(App { tree: Tracked::new(tree), events: Vec::new() }));
|
||||
let shared = Rc::clone(&app);
|
||||
let mut fixture = Fixture::new(move |ui| show(ui, &mut shared.borrow_mut()));
|
||||
fixture.room(PANEL);
|
||||
@@ -246,24 +246,17 @@ fn shift_right_and_left_open_and_close_the_active_layers_effects() {
|
||||
assert_eq!(fx(take(&app)), [(7, false)], "Shift+Left closes them");
|
||||
}
|
||||
|
||||
/// The tree a memoized view of the panel shows, as the app's model.
|
||||
#[derive(PlainData)]
|
||||
struct Model {
|
||||
#[plain_data(assume = "a mock tree: its only interior mutability is call counters, which no view shows")]
|
||||
tree: FakeLayers,
|
||||
}
|
||||
|
||||
/// A memoized view of the panel over the app's model; it applies what the panel reports to the model and sends it on.
|
||||
#[derive(MemoProps)]
|
||||
struct PanelView<'a> {
|
||||
model: &'a mut Tracked<Model>,
|
||||
model: &'a mut Tracked<FakeLayers>,
|
||||
events: Outbox<'a, LayersEvent<u32>>,
|
||||
}
|
||||
|
||||
fn panel_view(props: &mut PanelView<'_>, ui: &mut Ui) {
|
||||
let out = LayersPanel::new(&props.model.tree).show(ui);
|
||||
let out = LayersPanel::new(props.model).show(ui);
|
||||
for event in out.events {
|
||||
props.model.edit(|model| apply(&mut model.tree, &event));
|
||||
apply(props.model, &event);
|
||||
props.events.send(event);
|
||||
}
|
||||
}
|
||||
@@ -274,7 +267,7 @@ fn panel_view(props: &mut PanelView<'_>, ui: &mut Ui) {
|
||||
#[trial]
|
||||
fn a_rows_access_focus_action_leads_the_focused_rows_to_it() {
|
||||
let settled = || {
|
||||
let mut model = Tracked::new(Model { tree: FakeLayers::sample() });
|
||||
let mut model = Tracked::new(FakeLayers::sample());
|
||||
let mut events = Vec::new();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
MemoView::new("layers", PanelView { model: &mut model, events: Outbox::new(&mut events) }, panel_view).show(ui);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! `LayersPanel` in a host's memoized view: what the panel derives from its tracked tree, and when.
|
||||
|
||||
use craft_layers::ui::filter::{FilterBy, LayerFilter};
|
||||
use craft_layers::ui::mock::FakeLayers;
|
||||
use craft_layers::ui::panel::{LayersEvent, LayersPanel};
|
||||
use craft_ui::contract::{Bind, MemoProps, MemoView, Outbox, Tracked};
|
||||
use craft_ui::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, pointer, trial};
|
||||
use egui::{Ui, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// The panel's room: wide enough for a row's parts, tall enough for the sample tree and the footer.
|
||||
const PANEL: Vec2 = Vec2::new(420.0, 560.0);
|
||||
|
||||
type Shared<T> = Rc<RefCell<T>>;
|
||||
|
||||
/// What a host's view of the panel reads: the tracked tree, the filter the app stores, and an outbox for the events.
|
||||
#[derive(MemoProps)]
|
||||
struct Host<'a> {
|
||||
tree: &'a Tracked<FakeLayers>,
|
||||
filter: Bind<'a, LayerFilter>,
|
||||
events: Outbox<'a, LayersEvent<u32>>,
|
||||
}
|
||||
|
||||
fn host(props: &mut Host<'_>, ui: &mut Ui) {
|
||||
let out = LayersPanel::new(props.tree).filter(props.filter.reborrowed()).show(ui);
|
||||
for event in out.events {
|
||||
props.events.send(event);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixture showing the panel over `tree` in a host view, with the shared tree, filter and delivered events.
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
tree: Shared<Tracked<FakeLayers>>,
|
||||
filter: Shared<LayerFilter>,
|
||||
seen: Shared<Vec<LayersEvent<u32>>>,
|
||||
}
|
||||
|
||||
fn rig(tree: FakeLayers) -> Rig {
|
||||
let tree = Rc::new(RefCell::new(Tracked::new(tree)));
|
||||
let filter: Shared<LayerFilter> = Rc::default();
|
||||
let seen: Shared<Vec<LayersEvent<u32>>> = Rc::default();
|
||||
let (shown, by, sink) = (Rc::clone(&tree), Rc::clone(&filter), Rc::clone(&seen));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let tree = shown.borrow();
|
||||
let mut filter = by.borrow_mut();
|
||||
let mut events = sink.borrow_mut();
|
||||
MemoView::new("layers", Host { tree: &tree, filter: Bind::bound(&mut filter), events: Outbox::new(&mut events) }, host).show(ui);
|
||||
});
|
||||
fixture.room(PANEL);
|
||||
fixture.settle().idle(2);
|
||||
Rig { fixture, tree, filter, seen }
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
/// The builds of every pass of the last frame.
|
||||
fn builds(&self) -> u32 {
|
||||
last_frame_derived_builds(self.fixture.ctx()).iter().map(|(_, builds)| builds).sum()
|
||||
}
|
||||
|
||||
/// The host view's runs and replays in the last frame.
|
||||
fn host_runs(&self) -> (u32, u32) {
|
||||
let runs = last_frame_memo_runs(self.fixture.ctx());
|
||||
let count = |wanted: MemoRun| runs.iter().filter(|(name, _, run)| name.contains("Host") && *run == wanted).count() as u32;
|
||||
(count(MemoRun::Ran), count(MemoRun::Replayed))
|
||||
}
|
||||
|
||||
/// One frame with no input, after the edit of the trial.
|
||||
fn frame(&mut self) -> &mut Self {
|
||||
self.fixture.frame(Vec::new());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// An idle panel of 50 layers builds nothing and replays; so do the frames after it.
|
||||
#[trial]
|
||||
fn an_idle_panel_builds_nothing_and_replays() {
|
||||
let mut rig = rig(FakeLayers::fifty());
|
||||
for _ in 0..3 {
|
||||
rig.frame();
|
||||
assert_eq!(rig.builds(), 0, "an idle frame builds no display order");
|
||||
assert_eq!(rig.host_runs(), (0, 1), "the host view replays");
|
||||
}
|
||||
}
|
||||
|
||||
/// One layer edit through the `Tracked` builds the display order once and runs the view once, then it replays.
|
||||
#[trial]
|
||||
fn one_layer_edit_builds_once() {
|
||||
let mut rig = rig(FakeLayers::fifty());
|
||||
rig.tree.borrow_mut().layers[3].info.name = String::from("Renamed");
|
||||
rig.frame();
|
||||
assert_eq!(rig.builds(), 1, "the edit builds the display order once");
|
||||
assert_eq!(rig.host_runs().0, 1, "and runs the view once");
|
||||
rig.frame();
|
||||
assert_eq!(rig.builds(), 0, "the next pass builds nothing");
|
||||
assert_eq!(rig.host_runs(), (0, 1), "and replays");
|
||||
}
|
||||
|
||||
/// A filter change builds the display order once.
|
||||
#[trial]
|
||||
fn a_filter_change_builds_once() {
|
||||
let mut rig = rig(FakeLayers::fifty());
|
||||
{
|
||||
let mut filter = rig.filter.borrow_mut();
|
||||
filter.by = FilterBy::Name;
|
||||
filter.name = String::from("mark");
|
||||
}
|
||||
rig.frame();
|
||||
assert_eq!(rig.builds(), 1, "the filter builds the display order once");
|
||||
rig.frame();
|
||||
assert_eq!(rig.builds(), 0, "the next pass builds nothing");
|
||||
assert_eq!(rig.host_runs(), (0, 1), "and the view replays");
|
||||
}
|
||||
|
||||
/// A pass that runs the view for another reason, the pointer over it, keeps the display order.
|
||||
#[trial]
|
||||
fn a_pass_that_runs_the_view_for_the_pointer_builds_nothing() {
|
||||
let mut rig = rig(FakeLayers::fifty());
|
||||
rig.fixture.frame(vec![pointer::moved(egui::Pos2::new(100.0, 200.0))]);
|
||||
assert_eq!(rig.host_runs().0, 1, "the pointer over the panel runs the view");
|
||||
assert_eq!(rig.builds(), 0, "and the display order is kept");
|
||||
}
|
||||
|
||||
/// An event from a click reaches the host once, in the run that produced it, and not again while the view replays.
|
||||
#[trial]
|
||||
fn a_clicks_event_is_delivered_once_across_the_run_and_the_replays() {
|
||||
let mut rig = rig(FakeLayers::sample());
|
||||
let row = rig.fixture.by_label("Title").expect("the Title row shows");
|
||||
rig.seen.borrow_mut().clear();
|
||||
rig.fixture.click(&row).idle(4);
|
||||
let selects = rig.seen.borrow().iter().filter(|event| matches!(event, LayersEvent::Select(_))).count();
|
||||
assert_eq!(selects, 1, "{:?}", rig.seen.borrow());
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
//! `LayersPanel`: the order of the rows, a filter over them and where a Smart Filter drop lands.
|
||||
|
||||
use craft_behavior::EditEvent;
|
||||
use craft_layers::ui::filter::{FilterKind, LayerFilter};
|
||||
use craft_layers::ui::filter::LayerFilter;
|
||||
use craft_layers::ui::mock::FakeLayers;
|
||||
use craft_layers::ui::panel::{LayerDrop, LayerPosition, LayersEvent, LayersPanel};
|
||||
use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerRowKey, LayerTree, SubRowGroup};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_layers::ui::tree::{LayerRowKey, LayerTree, SubRowGroup};
|
||||
use craft_ui::contract::{Bind, PlainData, Tracked};
|
||||
use craft_ui::testing::{Fixture, Target, pointer, trial};
|
||||
use egui::{Pos2, Vec2};
|
||||
use std::cell::RefCell;
|
||||
@@ -22,17 +22,16 @@ const ONE_PANEL: Vec2 = by(400.0, 560.0);
|
||||
type Seen = Rc<RefCell<Vec<LayersEvent<u32>>>>;
|
||||
type Shared<T> = Rc<RefCell<T>>;
|
||||
|
||||
/// What a rig holds: the fixture, the events its panel reported, the tree and the filter it shows.
|
||||
struct Rig<T> {
|
||||
/// What a rig holds: the fixture, the events its panel reported, and the tracked tree it shows.
|
||||
struct Rig<T: PlainData> {
|
||||
fixture: Fixture,
|
||||
seen: Seen,
|
||||
tree: Shared<T>,
|
||||
filter: Shared<LayerFilter>,
|
||||
tree: Shared<Tracked<T>>,
|
||||
}
|
||||
|
||||
fn rig_of<T: LayerTree<Id = u32> + 'static>(tree: T) -> Rig<T> {
|
||||
let seen: Seen = Rc::default();
|
||||
let tree = Rc::new(RefCell::new(tree));
|
||||
let tree = Rc::new(RefCell::new(Tracked::new(tree)));
|
||||
let filter: Shared<LayerFilter> = Rc::default();
|
||||
let (sink, shown, by) = (Rc::clone(&seen), Rc::clone(&tree), Rc::clone(&filter));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
@@ -43,14 +42,14 @@ fn rig_of<T: LayerTree<Id = u32> + 'static>(tree: T) -> Rig<T> {
|
||||
});
|
||||
fixture.room(ONE_PANEL);
|
||||
fixture.settle();
|
||||
Rig { fixture, seen, tree, filter }
|
||||
Rig { fixture, seen, tree }
|
||||
}
|
||||
|
||||
fn rig() -> Rig<FakeLayers> {
|
||||
rig_of(FakeLayers::sample())
|
||||
}
|
||||
|
||||
impl<T> Rig<T> {
|
||||
impl<T: PlainData> Rig<T> {
|
||||
fn row(&self, label: &str) -> Target {
|
||||
self.fixture.by_label(label).unwrap_or_else(|| panic!("no row named {label}"))
|
||||
}
|
||||
@@ -140,19 +139,6 @@ fn rows_are_listed_top_first_and_closed_groups_hide_their_layers() {
|
||||
assert_eq!(rig.order(&all), all);
|
||||
}
|
||||
|
||||
/// A filter reads fields the tree revision does not cover, so it applies even while the revision stands.
|
||||
#[trial]
|
||||
fn a_filter_applies_even_while_the_tree_revision_stands() {
|
||||
let mut rig = rig();
|
||||
rig.tree.borrow_mut().revision = Some(1);
|
||||
rig.filter.borrow_mut().kinds = vec![FilterKind::Pixel];
|
||||
rig.fixture.idle(3);
|
||||
assert!(rig.fixture.by_label("Clipped").is_some());
|
||||
rig.tree.borrow_mut().layers[1].info = LayerInfo::new("Clipped", LayerKind::Text);
|
||||
rig.fixture.idle(3);
|
||||
assert!(rig.fixture.by_label("Clipped").is_none(), "a kind change shows at the same revision");
|
||||
}
|
||||
|
||||
/// A Smart Filter moves within its own object, with the slot counted after taking it out; effects keep their order.
|
||||
#[trial]
|
||||
fn smart_filters_reorder_within_their_object_and_effects_keep_their_order() {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
use craft_layers::ui::mock::FakeLayers;
|
||||
use craft_layers::ui::panel::{Groups, LayersEvent, LayersPanel};
|
||||
use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerSelection};
|
||||
use craft_ui::contract::Tracked;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Rect, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -49,7 +50,7 @@ fn short() -> FakeLayers {
|
||||
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
docs: Vec<Shared<FakeLayers>>,
|
||||
docs: Vec<Shared<Tracked<FakeLayers>>>,
|
||||
/// The document shown, by its position in `docs`.
|
||||
shown: Rc<Cell<usize>>,
|
||||
reveal: Rc<Cell<Option<(u32, Groups)>>>,
|
||||
@@ -59,7 +60,7 @@ struct Rig {
|
||||
/// The panel over the documents `docs`, each keyed by its position when there are several. The host applies the
|
||||
/// panel's opens in the pass that reports them, as an app does.
|
||||
fn rig(docs: Vec<FakeLayers>) -> Rig {
|
||||
let docs: Vec<Shared<FakeLayers>> = docs.into_iter().map(|tree| Rc::new(RefCell::new(tree))).collect();
|
||||
let docs: Vec<Shared<Tracked<FakeLayers>>> = docs.into_iter().map(|tree| Rc::new(RefCell::new(Tracked::new(tree)))).collect();
|
||||
let keyed = docs.len() > 1;
|
||||
let shown: Rc<Cell<usize>> = Rc::default();
|
||||
let reveal: Rc<Cell<Option<(u32, Groups)>>> = Rc::default();
|
||||
|
||||
@@ -6,6 +6,7 @@ use craft_layers::testing;
|
||||
use craft_layers::ui::mock::{FakeLayers, sub_row};
|
||||
use craft_layers::ui::panel::{ActivateOn, LayerDrop, LayersEvent, LayersPanel, MaskMove};
|
||||
use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerRowKey, LayerSelection, MaskInfo, SubRow, SubRowGroup, SubRows};
|
||||
use craft_ui::contract::Tracked;
|
||||
use craft_ui::testing::{Fixture, Target, pointer, trial};
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
use std::cell::RefCell;
|
||||
@@ -19,7 +20,7 @@ const SMART: u32 = 2;
|
||||
|
||||
/// The app around the panel: the tree it shows, what it reported and the layer it last called hovered.
|
||||
struct App {
|
||||
tree: FakeLayers,
|
||||
tree: Tracked<FakeLayers>,
|
||||
events: Vec<LayersEvent<u32>>,
|
||||
hovered: Option<u32>,
|
||||
}
|
||||
@@ -58,12 +59,12 @@ fn apply(tree: &mut FakeLayers, event: &LayersEvent<u32>) {
|
||||
}
|
||||
|
||||
fn rig(tree: FakeLayers) -> (Fixture, Shared) {
|
||||
let app = Rc::new(RefCell::new(App { tree, events: Vec::new(), hovered: None }));
|
||||
let app = Rc::new(RefCell::new(App { tree: Tracked::new(tree), events: Vec::new(), hovered: None }));
|
||||
let shared = Rc::clone(&app);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut app = shared.borrow_mut();
|
||||
let App { tree, events, hovered } = &mut *app;
|
||||
let out = LayersPanel::new(&*tree).show(ui);
|
||||
let out = LayersPanel::new(tree).show(ui);
|
||||
for event in &out.events {
|
||||
apply(tree, event);
|
||||
}
|
||||
@@ -400,12 +401,11 @@ fn long(count: usize) -> (FakeLayers, u32) {
|
||||
layer.effects_open = true;
|
||||
layer.smart_filters = Some(SubRows::new(SubRow::new("Smart Filters"), vec![sub_row("Gaussian Blur"), sub_row("Sharpen")]));
|
||||
tree.selection = LayerSelection::new(vec![1], Some(1), LayerPart::Pixels);
|
||||
tree.revision = Some(1);
|
||||
(tree, id)
|
||||
}
|
||||
|
||||
/// FW15: a long layer list asks the app only for the rows in view: a settled frame makes as many `info` and
|
||||
/// `sub_rows` calls for 2,000 layers as for 200, and an off-screen group or Smart Filter row lays out nothing.
|
||||
/// FW15: a long layer list builds only the rows in view: a settled frame builds as many rows for 2,000 layers as
|
||||
/// for 200, and an off-screen group or Smart Filter row lays out nothing.
|
||||
/// Scrolled into view they show; a filter selected there stays selected after it scrolls away again.
|
||||
#[trial]
|
||||
fn a_long_layer_list_asks_only_for_the_rows_in_view() {
|
||||
@@ -413,9 +413,8 @@ fn a_long_layer_list_asks_only_for_the_rows_in_view() {
|
||||
for count in [200, 2_000] {
|
||||
let (tree, smart) = long(count);
|
||||
let (mut fixture, app) = rig(tree);
|
||||
let _ = (app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls());
|
||||
fixture.frame(vec![]);
|
||||
calls.push((app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls()));
|
||||
calls.push(craft_ui::testing::row_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum::<u32>());
|
||||
for name in ["Closed Group", "Smart Object", "Gaussian Blur", "Sharpen"] {
|
||||
assert!(fixture.by_label(name).is_none(), "{count} layers: the off-screen row {name:?} lays out nothing");
|
||||
}
|
||||
@@ -444,5 +443,6 @@ fn a_long_layer_list_asks_only_for_the_rows_in_view() {
|
||||
assert!(take(&app).iter().all(|event| !matches!(event, LayersEvent::Select(_))), "{count} layers: scrolling selects nothing");
|
||||
assert_eq!(app.borrow().tree.selection.sub_row, selected, "{count} layers: the filter stays selected");
|
||||
}
|
||||
assert_eq!(calls[0], calls[1], "a settled frame asks for as many rows for 2,000 layers as for 200 (info, sub_rows)");
|
||||
assert!(calls[0] > 0, "the rows in view are built");
|
||||
assert_eq!(calls[0], calls[1], "a settled frame builds as many rows for 2,000 layers as for 200");
|
||||
}
|
||||
+9
-10
@@ -96,7 +96,8 @@ items.
|
||||
Each frame, `apply_state(&mut bar, |command| ItemState { enabled, checked })` sets enabled and
|
||||
checked from the app's state. `checked: Some(..)` makes a plain item a check item and selects or
|
||||
clears a radio item; `None` leaves the kind as it is. The built-in items and the open documents
|
||||
are left alone. Both run on the app's bar, before the layout.
|
||||
are left alone. Both run on the app's bar, before the layout. The bar is held in a `Tracked<MenuBar>`; both write it only when an item changes, so
|
||||
its revision (the key of the in-window bar's kept labels and of `sync_with`) moves only then.
|
||||
|
||||
## Keyboard Shortcuts dialog
|
||||
|
||||
@@ -240,7 +241,7 @@ Each frame, in this order:
|
||||
2. `set_gate`, with the app's state for this frame.
|
||||
3. `take_clicks`, and run the commands it returns: the clicks since the last frame that the gate
|
||||
allows now. Minimize and Quit are already handled.
|
||||
4. `sync_with`, which lays the menus out again only when the app's state changed or a menu event
|
||||
4. `sync_with`, which lays the menus out again only when its key changed or a menu event
|
||||
arrived, and re-syncs them in place when the gate changed.
|
||||
|
||||
```rust
|
||||
@@ -256,14 +257,13 @@ if let Some(menu) = &mut self.native_menu {
|
||||
for command in menu.take_clicks(ctx) {
|
||||
self.run_command(ctx, &command);
|
||||
}
|
||||
let state = self.menu_state_hash(craft_menu::had_input(ctx).then_some(ctx.cumulative_frame_nr()));
|
||||
for c in menu.sync_with(state, || craft_menu::mac_layout(&self.menu_bar(), &LayoutOptions::new("PhotoCraft"))) {
|
||||
for c in menu.sync_with(&(&self.menu_bar, &self.workspace), || craft_menu::mac_layout(&self.menu_bar(), &LayoutOptions::new("PhotoCraft"))) {
|
||||
log::info!("menu: {} is {} on macOS and {} in the app; {}", c.shortcut, c.system, c.command, c.resolution);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`sync_with` builds the layout only when `state` changed or a menu event arrived, because
|
||||
`sync_with` builds the layout only when its key changed or a menu event arrived, because
|
||||
building the rows usually walks every command's enabled state. The backend then updates labels,
|
||||
enabled and checked in place and rebuilds only when `structure_key` (or, for the open
|
||||
documents, `window_key`) changes. Adding or removing an item in a dynamic list (recent files,
|
||||
@@ -271,11 +271,10 @@ workspaces, plugins) changes `structure_key`; relabelling one doesn't. An item t
|
||||
item once stays one, unchecked, when the app's state stops giving it a checked state, so that
|
||||
doesn't rebuild the menus.
|
||||
|
||||
`state` must cover everything the menus show. A change that comes without input, such as a load
|
||||
or save finishing on a worker or a timer, leaves the menus stale until the next input or menu
|
||||
event unless it is in the hash. An app that can't keep the hash complete calls
|
||||
`menu.sync(layout)` instead, with the layout built every frame: it is compared with the last
|
||||
one and synced only when it differs.
|
||||
The key is a `MemoProps` value: the menu model held in a `Tracked<MenuBar>` (`apply_state` and
|
||||
`apply_keymap` write it only when an item changes, so its revision moves only then) and whatever
|
||||
else the layout reads, each as a checked input, so a change that comes without input (a load
|
||||
finishing on a worker) reaches the menus the frame it lands.
|
||||
|
||||
An app that needs a click while egui is idle (to wake its own loop, or hand the command to a
|
||||
worker) sets `menu.on_command(Box::new(|command| ..))`. The hook runs from the menu event
|
||||
|
||||
+44
-10
@@ -11,8 +11,10 @@
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
use craft_host::target::Os;
|
||||
use craft_i18n::Words;
|
||||
use craft_keymap::{CommandRef, Platform};
|
||||
use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless};
|
||||
use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless, Tracked};
|
||||
use craft_ui::menu::{MenuBar as Bar, MenuHelp, MenuTitle};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use egui::{Rect, Ui};
|
||||
@@ -87,7 +89,7 @@ pub type EnglishFn = fn(Labeled<'_>) -> Option<String>;
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
#[pattern(probe(MenuBarUi<'static, EnglishFn>))]
|
||||
pub struct MenuBarUi<'a, E = EnglishFn> {
|
||||
bar: &'a MenuBar,
|
||||
bar: &'a Tracked<MenuBar>,
|
||||
/// The platform set with [`target`](Self::target); the shell's when none is.
|
||||
target: Option<Target>,
|
||||
english: Option<Stateless<E>>,
|
||||
@@ -99,7 +101,7 @@ pub struct MenuBarUi<'a, E = EnglishFn> {
|
||||
/// Every input of the bar's view.
|
||||
#[derive(MemoProps)]
|
||||
struct BarProps<'a, #[memo_props(stateless)] E> {
|
||||
bar: &'a MenuBar,
|
||||
bar: &'a Tracked<MenuBar>,
|
||||
target: Target,
|
||||
english: Option<Stateless<E>>,
|
||||
preferred: &'a [(&'a str, char)],
|
||||
@@ -110,7 +112,7 @@ struct BarProps<'a, #[memo_props(stateless)] E> {
|
||||
|
||||
impl<'a> MenuBarUi<'a> {
|
||||
/// The bar for `bar`, already laid out ([`crate::layout`]), on the shell's platform ([`Target::of_shell`]).
|
||||
pub fn new(bar: &'a MenuBar) -> MenuBarUi<'a> {
|
||||
pub fn new(bar: &'a Tracked<MenuBar>) -> MenuBarUi<'a> {
|
||||
MenuBarUi { bar, target: None, english: None, preferred: &[], keyboard: None, help_search: false }
|
||||
}
|
||||
}
|
||||
@@ -184,13 +186,32 @@ fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut B
|
||||
});
|
||||
let english: Option<&EnglishHook<'_>> = hook.as_ref().map(|hook| hook as &EnglishHook<'_>);
|
||||
let rows = Rows::new(props.target).english(english).preferred(props.preferred);
|
||||
let labels =
|
||||
rows.labels(&props.bar.menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| rows.english_of(Labeled::Title(&menu.title)));
|
||||
let shared = &rows;
|
||||
let titles: Vec<MenuTitle<'_>> =
|
||||
props.bar.menus.iter().zip(labels).map(|(menu, label)| MenuTitle::new(label, move |ui| shared.show(ui, &menu.children))).collect();
|
||||
let env = Env::of(ui);
|
||||
let os = env.view().shell().os;
|
||||
// The text of every menu is worked out once for these inputs and kept: a pass that shows an open menu again writes none of it.
|
||||
let key = LabelKey {
|
||||
bar: props.bar,
|
||||
target: props.target,
|
||||
os,
|
||||
preferred: props.preferred,
|
||||
english: props.english,
|
||||
words: &env.words,
|
||||
keymap: craft_ui::runtime::commands::keymap_generation(ui.ctx()),
|
||||
};
|
||||
let labels = craft_ui::runtime::derived::derived(ui.ctx(), ui.scope_id().with("menu-labels"), &key, || {
|
||||
rows.bar_labels(&props.bar.menus, keymap_platform(props.target, os))
|
||||
});
|
||||
let (shared, labels) = (&rows, &*labels);
|
||||
let titles: Vec<MenuTitle<'_>> = props
|
||||
.bar
|
||||
.menus
|
||||
.iter()
|
||||
.zip(&labels.titles)
|
||||
.zip(&labels.menus)
|
||||
.map(|((menu, title), level)| MenuTitle::new(title.clone(), move |ui| shared.show(ui, &menu.children, level)))
|
||||
.collect();
|
||||
// Collecting the search's commands walks every row of every menu: the bar does it only while Help is open.
|
||||
let bar_model = props.bar;
|
||||
let bar_model: &MenuBar = props.bar;
|
||||
let entries = move || entries_of(bar_model, english);
|
||||
let mut bar = Bar::new(props.label.clone(), titles).keyboard(props.keyboard);
|
||||
if let Some(menu) = props.help {
|
||||
@@ -198,3 +219,16 @@ fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut B
|
||||
}
|
||||
MenuBarOutput { titles: bar.show(ui).titles }
|
||||
}
|
||||
|
||||
/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the mnemonic and English
|
||||
/// hooks, the language and the keymap.
|
||||
#[derive(MemoProps)]
|
||||
struct LabelKey<'a, #[memo_props(stateless)] E> {
|
||||
bar: &'a Tracked<MenuBar>,
|
||||
target: Target,
|
||||
os: Os,
|
||||
preferred: &'a [(&'a str, char)],
|
||||
english: Option<Stateless<E>>,
|
||||
words: &'a Words,
|
||||
keymap: u64,
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
//! Stories of the in-window bar over a small model.
|
||||
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
use craft_ui::contract::Tracked;
|
||||
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use crate::{Document, Item, LayoutOptions, Menu, MenuBar, MenuBarUi, MenuRole, Node, Target, layout};
|
||||
|
||||
fn model() -> MenuBar {
|
||||
fn build() -> MenuBar {
|
||||
let item = |id: &str, label: &str| Item::new(id, label);
|
||||
let bar = MenuBar {
|
||||
menus: vec![
|
||||
@@ -37,6 +40,12 @@ fn model() -> MenuBar {
|
||||
layout(&bar, Target::Linux, &LayoutOptions::new("Sample")).bar
|
||||
}
|
||||
|
||||
/// The stories' model, made once: a model made again each pass is a new source, and the bar would run each time.
|
||||
fn model() -> Arc<Tracked<MenuBar>> {
|
||||
static MODEL: LazyLock<Arc<Tracked<MenuBar>>> = LazyLock::new(|| Arc::new(Tracked::new(build())));
|
||||
MODEL.clone()
|
||||
}
|
||||
|
||||
#[story(MenuBarUi<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn menu_bar_ui(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
MenuBarUi::new(&model()).target(Target::Linux).show(ui);
|
||||
|
||||
+56
-10
@@ -26,7 +26,32 @@ use crate::model::{Builtin, Item, ItemKind, Node};
|
||||
/// AppKit's own items ([`Node::Standard`]) are left out. The chord of a row without a binding is the item's own
|
||||
/// shortcut, written for the shell's operating system.
|
||||
pub fn rows(ui: &mut Ui, nodes: &[Node]) {
|
||||
Rows::new(Target::of_shell(Env::of(ui).view().shell())).show(ui, nodes);
|
||||
let rows = Rows::new(Target::of_shell(Env::of(ui).view().shell()));
|
||||
let labels = rows.level_labels(nodes, rows.platform(ui));
|
||||
rows.show(ui, nodes, &labels);
|
||||
}
|
||||
|
||||
/// The text a menu level shows for its nodes, parallel to them: what [`LevelLabels::build`] works out once for a
|
||||
/// model, so a pass that shows the menu again writes none of it.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub(crate) struct LevelLabels {
|
||||
rows: Vec<RowLabels>,
|
||||
}
|
||||
|
||||
/// One node's text: its label as the menu shows it (markers escaped, mnemonic marked), the item's shortcut text, and the
|
||||
/// text of a submenu's own level. Separators and AppKit's items hold empty text.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct RowLabels {
|
||||
label: String,
|
||||
shortcut: Option<String>,
|
||||
children: LevelLabels,
|
||||
}
|
||||
|
||||
/// The text of a bar: its titles as the bar shows them and the text of each menu's rows.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) struct BarLabels {
|
||||
pub(crate) titles: Vec<String>,
|
||||
pub(crate) menus: Vec<LevelLabels>,
|
||||
}
|
||||
|
||||
/// How the rows of a menu are written: the target that names the shortcuts, the app's English labels and its
|
||||
@@ -120,12 +145,35 @@ impl<'a> Rows<'a> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Shows `nodes` as the rows of the menu body `ui` is in.
|
||||
pub(crate) fn show(&self, ui: &mut Ui, nodes: &[Node]) {
|
||||
/// The text of `nodes` and of every submenu below them, with shortcuts written for `platform`.
|
||||
pub(crate) fn level_labels(&self, nodes: &[Node], platform: Platform) -> LevelLabels {
|
||||
let labels = self.node_labels(nodes);
|
||||
for (node, label) in nodes.iter().zip(labels) {
|
||||
let rows = nodes
|
||||
.iter()
|
||||
.zip(labels)
|
||||
.map(|(node, label)| match node {
|
||||
Node::Item(item) => {
|
||||
RowLabels { label, shortcut: item.shortcut.as_ref().map(|chord| chord.display(platform)), children: LevelLabels::default() }
|
||||
}
|
||||
Node::Submenu { children, .. } => RowLabels { label, shortcut: None, children: self.level_labels(children, platform) },
|
||||
Node::Separator | Node::Standard { .. } => RowLabels::default(),
|
||||
})
|
||||
.collect();
|
||||
LevelLabels { rows }
|
||||
}
|
||||
|
||||
/// The text of a whole bar: the titles and each menu's rows.
|
||||
pub(crate) fn bar_labels(&self, menus: &[crate::model::Menu], platform: Platform) -> BarLabels {
|
||||
let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| self.english_of(Labeled::Title(&menu.title)));
|
||||
BarLabels { titles, menus: menus.iter().map(|menu| self.level_labels(&menu.children, platform)).collect() }
|
||||
}
|
||||
|
||||
/// Shows `nodes` as the rows of the menu body `ui` is in, with their `labels`.
|
||||
pub(crate) fn show(&self, ui: &mut Ui, nodes: &[Node], labels: &LevelLabels) {
|
||||
for (node, text) in nodes.iter().zip(&labels.rows) {
|
||||
let label = text.label.clone();
|
||||
match node {
|
||||
Node::Item(item) => self.item(ui, item, label),
|
||||
Node::Item(item) => self.item(ui, item, label, text.shortcut.clone()),
|
||||
Node::Separator => {
|
||||
Divider::horizontal().show(ui);
|
||||
}
|
||||
@@ -133,7 +181,7 @@ impl<'a> Rows<'a> {
|
||||
if is_dead(children) {
|
||||
MenuItem::submenu(label).enabled(false).show(ui);
|
||||
} else {
|
||||
Menu::submenu_row(ui, label, |ui, _| self.show(ui, children));
|
||||
Menu::submenu_row(ui, label, |ui, _| self.show(ui, children, &text.children));
|
||||
}
|
||||
}
|
||||
Node::Standard { .. } => {}
|
||||
@@ -141,9 +189,7 @@ impl<'a> Rows<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn item(&self, ui: &mut Ui, item: &Item, label: String) {
|
||||
let platform = self.platform(ui);
|
||||
let shortcut = item.shortcut.as_ref().map(|chord| chord.display(platform));
|
||||
fn item(&self, ui: &mut Ui, item: &Item, label: String, shortcut: Option<String>) {
|
||||
match Builtin::of(&item.command) {
|
||||
Some(Builtin::Quit) => {
|
||||
if local(ui, item, label, shortcut).ran {
|
||||
@@ -162,7 +208,7 @@ impl<'a> Rows<'a> {
|
||||
}
|
||||
|
||||
/// The platform whose key names the shortcut column shows.
|
||||
fn platform(&self, ui: &Ui) -> Platform {
|
||||
pub(crate) fn platform(&self, ui: &Ui) -> Platform {
|
||||
keymap_platform(self.target, Env::of(ui).view().shell().os)
|
||||
}
|
||||
}
|
||||
|
||||
+13
-41
@@ -5,7 +5,7 @@ use std::collections::HashSet;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
use craft_keymap::{Chord, CommandRef, Key, Mods};
|
||||
use craft_ui::contract::MemoProps;
|
||||
use craft_ui::contract::{MemoKey, MemoProps};
|
||||
use craft_ui::runtime::windows::{KeyEquivalent, WindowAction, WindowHost};
|
||||
|
||||
use crate::layout::{Clash, Layout};
|
||||
@@ -203,8 +203,8 @@ pub trait Backend {
|
||||
/// The native menu bar, while the app uses one (its in-window menus are hidden then).
|
||||
pub struct NativeMenu {
|
||||
backend: Box<dyn Backend>,
|
||||
/// The state the menus were last built from.
|
||||
state: Option<u64>,
|
||||
/// The key the menus were last built from.
|
||||
state: Option<u128>,
|
||||
clicks: Vec<CommandRef>,
|
||||
/// An event arrived (AppKit may have toggled a check item itself): re-sync.
|
||||
dirty: bool,
|
||||
@@ -388,23 +388,18 @@ impl NativeMenu {
|
||||
out
|
||||
}
|
||||
|
||||
/// Bring the native menu up to date. `state` is a hash of what the menus show (see
|
||||
/// [`had_input`]); `build` lays them out ([`crate::mac_layout`]) and runs only when `state`
|
||||
/// changed or a menu event arrived since the last sync, since building the rows usually walks
|
||||
/// every command's enabled state. A menu event re-syncs because AppKit flips a check or radio
|
||||
/// item's state itself when it is chosen: the sync sets it back to the app's state. A gate
|
||||
/// change ([`NativeMenu::set_gate`]) re-syncs the menus last laid out, greyed or not, without
|
||||
/// calling `build`.
|
||||
///
|
||||
/// `state` must cover everything the menus show. A change that comes without input, such as
|
||||
/// a load or save finishing on a worker or a timer, leaves the menus stale until the next
|
||||
/// input or menu event unless it is in the hash. An app that can't keep the hash complete
|
||||
/// uses [`NativeMenu::sync`] instead.
|
||||
/// Bring the native menu up to date. `key` is everything the layout reads, as a [`MemoProps`] value (the
|
||||
/// app's `Tracked` menu model, the language's `Words`, the keymap generation): `build` lays the menus out
|
||||
/// ([`crate::mac_layout`]) and runs only when the key changed or a menu event arrived since the last sync, since
|
||||
/// building the rows usually walks every command's enabled state. A menu event re-syncs because AppKit flips a
|
||||
/// check or radio item's state itself when it is chosen: the sync sets it back to the app's state. A gate change
|
||||
/// ([`NativeMenu::set_gate`]) re-syncs the menus last laid out, greyed or not, without calling `build`.
|
||||
///
|
||||
/// Returns the layout's clashes when they differ from the last ones returned, for the app to
|
||||
/// log; otherwise nothing.
|
||||
pub fn sync_with(&mut self, state: u64, build: impl FnOnce() -> Layout) -> Vec<Clash> {
|
||||
let relayout = self.state != Some(state) || self.dirty;
|
||||
pub fn sync_with<K: MemoProps + ?Sized>(&mut self, key: &K, build: impl FnOnce() -> Layout) -> Vec<Clash> {
|
||||
let key = MemoKey::of(key);
|
||||
let relayout = self.state != Some(key) || self.dirty;
|
||||
if !relayout && self.synced_gate == Some(self.gate) {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -413,27 +408,12 @@ impl NativeMenu {
|
||||
let mut layout = build();
|
||||
self.keep_kinds(&mut layout.bar);
|
||||
clashes = self.keep(layout);
|
||||
self.state = Some(state);
|
||||
self.state = Some(key);
|
||||
}
|
||||
self.push();
|
||||
clashes
|
||||
}
|
||||
|
||||
/// [`NativeMenu::sync_with`] without a state hash: the app lays the menus out every frame
|
||||
/// and they are synced when the layout differs from the last one (or a menu event or gate
|
||||
/// change calls for it), so they never go stale. It costs a layout per frame.
|
||||
pub fn sync(&mut self, mut layout: Layout) -> Vec<Clash> {
|
||||
self.keep_kinds(&mut layout.bar);
|
||||
if !self.dirty && self.bar.as_ref() == Some(&layout.bar) && self.clashes == layout.clashes && self.synced_gate == Some(self.gate) {
|
||||
return Vec::new();
|
||||
}
|
||||
let clashes = self.keep(layout);
|
||||
// A later `sync_with` lays the menus out again.
|
||||
self.state = None;
|
||||
self.push();
|
||||
clashes
|
||||
}
|
||||
|
||||
/// An item that was a check item once stays one, unchecked: switching its kind would change
|
||||
/// [`crate::structure_key`] and rebuild the menus.
|
||||
fn keep_kinds(&mut self, bar: &mut MenuBar) {
|
||||
@@ -514,11 +494,3 @@ fn text_editing_key(c: &Chord) -> bool {
|
||||
pub(crate) fn native_ok(c: &Chord) -> bool {
|
||||
c.has_command()
|
||||
}
|
||||
|
||||
/// A key press, typed text or click this frame. It may have changed state an app's menu hash
|
||||
/// doesn't list, so apps fold it into the `state` passed to [`NativeMenu::sync_with`], for
|
||||
/// example as `had_input(ctx).then_some(ctx.cumulative_frame_nr())`. Keys come from the key
|
||||
/// stage (`keys::keyed`), which also counts the presses a focused component took from egui.
|
||||
pub fn had_input(ctx: &egui::Context) -> bool {
|
||||
craft_ui::runtime::keys::keyed(ctx) || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. })))
|
||||
}
|
||||
+51
-23
@@ -2,8 +2,9 @@
|
||||
//! enabled and checked update.
|
||||
|
||||
use craft_keymap::{CommandKind, CommandRef, Keymap};
|
||||
use craft_ui::contract::Tracked;
|
||||
|
||||
use crate::model::{Builtin, ItemKind, MenuBar};
|
||||
use crate::model::{Builtin, Item, ItemKind, MenuBar};
|
||||
|
||||
/// Give each item the shortcut its command has in `keymap`, the user's overrides included, and
|
||||
/// make the items of toggle commands (kind [`CommandKind::Toggle`]) check items.
|
||||
@@ -12,14 +13,23 @@ use crate::model::{Builtin, ItemKind, MenuBar};
|
||||
/// one in its home scope first, so a chord another command wins is not shown. A command with no
|
||||
/// such binding loses its shortcut, and an item whose command the keymap doesn't know keeps its
|
||||
/// own. A toggle's check item keeps its checked state; radio items stay radio items. Call it on
|
||||
/// the app's bar, before the layout.
|
||||
pub fn apply_keymap(bar: &mut MenuBar, keymap: &Keymap) {
|
||||
bar.for_each_item_mut(|it| {
|
||||
let Some(bindable) = keymap.bindable(&it.command) else { return };
|
||||
it.shortcut = keymap.shown_chord(&it.command);
|
||||
if bindable.kind == CommandKind::Toggle && it.kind == ItemKind::Plain {
|
||||
it.kind = ItemKind::Check(false);
|
||||
}
|
||||
/// the app's bar, before the layout. The bar is written, and its revision moves, only when an item changes.
|
||||
pub fn apply_keymap(bar: &mut Tracked<MenuBar>, keymap: &Keymap) {
|
||||
let wanted = |it: &Item| {
|
||||
let bindable = keymap.bindable(&it.command)?;
|
||||
let kind = if bindable.kind == CommandKind::Toggle && it.kind == ItemKind::Plain { ItemKind::Check(false) } else { it.kind };
|
||||
Some((keymap.shown_chord(&it.command), kind))
|
||||
};
|
||||
if !bar.items().into_iter().any(|it| wanted(it).is_some_and(|(shortcut, kind)| shortcut != it.shortcut || kind != it.kind)) {
|
||||
return;
|
||||
}
|
||||
bar.edit(|bar| {
|
||||
bar.for_each_item_mut(|it| {
|
||||
if let Some((shortcut, kind)) = wanted(it) {
|
||||
it.shortcut = shortcut;
|
||||
it.kind = kind;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -56,20 +66,38 @@ impl Default for ItemState {
|
||||
|
||||
/// Set every item's enabled and checked state from `state`, called once per item of the app's
|
||||
/// commands. `checked: Some(..)` makes a plain item a check item and sets a radio item's
|
||||
/// selection. The built-in items and the open documents are left alone.
|
||||
pub fn apply_state(bar: &mut MenuBar, mut state: impl FnMut(&CommandRef) -> ItemState) {
|
||||
let documents: Vec<CommandRef> = bar.documents.iter().map(|d| d.command.clone()).collect();
|
||||
bar.for_each_item_mut(|it| {
|
||||
if Builtin::of(&it.command).is_some() || documents.contains(&it.command) {
|
||||
return;
|
||||
}
|
||||
let s = state(&it.command);
|
||||
it.enabled = s.enabled;
|
||||
if let Some(on) = s.checked {
|
||||
it.kind = match it.kind {
|
||||
ItemKind::Radio(_) => ItemKind::Radio(on),
|
||||
ItemKind::Plain | ItemKind::Check(_) => ItemKind::Check(on),
|
||||
/// selection. The built-in items and the open documents are left alone. The bar is written, and
|
||||
/// its revision moves, only when an item changes.
|
||||
pub fn apply_state(bar: &mut Tracked<MenuBar>, mut state: impl FnMut(&CommandRef) -> ItemState) {
|
||||
let skipped = |it: &Item| Builtin::of(&it.command).is_some() || bar.is_document(&it.command);
|
||||
// One entry per item, depth first, as `for_each_item_mut` walks them.
|
||||
let wanted: Vec<Option<(bool, ItemKind)>> = bar
|
||||
.items()
|
||||
.into_iter()
|
||||
.map(|it| {
|
||||
if skipped(it) {
|
||||
return None;
|
||||
}
|
||||
let s = state(&it.command);
|
||||
let kind = match (s.checked, it.kind) {
|
||||
(None, kind) => kind,
|
||||
(Some(on), ItemKind::Radio(_)) => ItemKind::Radio(on),
|
||||
(Some(on), ItemKind::Plain | ItemKind::Check(_)) => ItemKind::Check(on),
|
||||
};
|
||||
}
|
||||
Some((s.enabled, kind))
|
||||
})
|
||||
.collect();
|
||||
let differs = bar.items().into_iter().zip(&wanted).any(|(it, want)| want.is_some_and(|(enabled, kind)| enabled != it.enabled || kind != it.kind));
|
||||
if !differs {
|
||||
return;
|
||||
}
|
||||
bar.edit(|bar| {
|
||||
let mut wanted = wanted.into_iter();
|
||||
bar.for_each_item_mut(|it| {
|
||||
if let Some((enabled, kind)) = wanted.next().flatten() {
|
||||
it.enabled = enabled;
|
||||
it.kind = kind;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -389,7 +389,9 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar {
|
||||
Node::Standard { .. } if !appkit => None,
|
||||
other => Some(other.clone()),
|
||||
});
|
||||
tidy(shown.collect())
|
||||
let mut kept: Vec<Node> = shown.collect();
|
||||
tidy(&mut kept);
|
||||
kept
|
||||
}
|
||||
let on = target.platforms();
|
||||
let menus = bar.menus.iter().map(|m| Menu { children: keep(&m.children, on, target == Target::Mac), ..m.clone() }).collect();
|
||||
@@ -428,7 +430,7 @@ fn ensure_menu<'b>(bar: &'b mut MenuBar, role: MenuRole, english: &'static str,
|
||||
/// Tidy every menu and drop the ones the moves emptied, unless `keep_empty`.
|
||||
fn finish(bar: &mut MenuBar, keep_empty: impl Fn(&Menu) -> bool) {
|
||||
for m in &mut bar.menus {
|
||||
m.children = tidy(std::mem::take(&mut m.children));
|
||||
tidy(&mut m.children);
|
||||
}
|
||||
bar.menus.retain(|m| !m.children.is_empty() || keep_empty(m));
|
||||
}
|
||||
|
||||
@@ -88,8 +88,8 @@
|
||||
//! [`NativeMenu::on_command`] sees each allowed click as it arrives, also while egui is idle.
|
||||
//!
|
||||
//! Per frame: [`NativeMenu::poll`], then [`NativeMenu::set_gate`], [`NativeMenu::take_clicks`] and run the commands, then
|
||||
//! [`NativeMenu::sync_with`], which lays the menus out again only when the app's state changed
|
||||
//! (or [`NativeMenu::sync`], which compares a layout built every frame).
|
||||
//! [`NativeMenu::sync_with`], which lays the menus out again only when its key changed (the menu model's
|
||||
//! `Tracked` revision and the other inputs of the layout).
|
||||
//! The input filter also keeps a click or Escape that closes an open native menu away
|
||||
//! from egui.
|
||||
#![warn(missing_docs)]
|
||||
@@ -118,7 +118,7 @@ pub use bar::{EnglishHook, Labeled, MenuBarOutput, MenuBarUi};
|
||||
pub use craft_keymap::{Chord, CommandRef};
|
||||
pub use customize::Customization;
|
||||
pub use documents::DOCUMENT_COMMAND_PREFIX;
|
||||
pub use driver::{Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu, had_input};
|
||||
pub use driver::{Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu};
|
||||
pub use help::{HelpCommand, HelpLabels, HelpLink, HelpMenu};
|
||||
pub use keymap::{ItemState, apply_keymap, apply_state};
|
||||
pub use keytips::{KeytipControl, Keytips, KeytipsOutput};
|
||||
|
||||
+68
-62
@@ -1,6 +1,7 @@
|
||||
//! The menu tree, the flat rows it can be built from, and the keys that tell a backend what
|
||||
//! changed.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::ops::BitOr;
|
||||
|
||||
@@ -8,7 +9,7 @@ use craft_keymap::{Chord, CommandRef, Mods};
|
||||
use craft_theme::Srgba;
|
||||
|
||||
/// The app's menus, in order, and its open documents.
|
||||
#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct MenuBar {
|
||||
/// The top-level menus, left to right.
|
||||
@@ -18,7 +19,7 @@ pub struct MenuBar {
|
||||
}
|
||||
|
||||
/// An open document, listed in the Window menu.
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct Document {
|
||||
/// What choosing it runs (bring the document to the front).
|
||||
@@ -51,7 +52,7 @@ impl Document {
|
||||
}
|
||||
|
||||
/// A top-level menu.
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct Menu {
|
||||
/// The title in the bar.
|
||||
@@ -64,7 +65,7 @@ pub struct Menu {
|
||||
|
||||
/// What a top-level menu is for, set by the app. macOS treats the app, Window and Help menus
|
||||
/// specially; File is where the system Close Window item goes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum MenuRole {
|
||||
/// Any menu without a fixed place.
|
||||
@@ -85,7 +86,7 @@ pub enum MenuRole {
|
||||
}
|
||||
|
||||
/// The platforms an item or submenu is shown on. All of them by default.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
pub struct Platforms(u8);
|
||||
|
||||
impl Platforms {
|
||||
@@ -132,7 +133,7 @@ impl BitOr for Platforms {
|
||||
}
|
||||
|
||||
/// One entry of a menu.
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum Node {
|
||||
/// An item the user can choose.
|
||||
@@ -162,7 +163,7 @@ pub enum Node {
|
||||
}
|
||||
|
||||
/// One menu item: a command with its label, shortcut and state.
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct Item {
|
||||
/// What the item runs: the app's command (`file.open`), with its parameters
|
||||
@@ -198,7 +199,7 @@ pub struct Item {
|
||||
|
||||
/// The command a row runs while `mods` are held as it is chosen (Alt on Merge Visible runs Stamp
|
||||
/// Visible).
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct Alternate {
|
||||
/// The modifiers that select the alternate.
|
||||
@@ -222,7 +223,7 @@ impl Alternate {
|
||||
}
|
||||
|
||||
/// A plain item, or one with a checked state.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum ItemKind {
|
||||
/// An ordinary item.
|
||||
@@ -247,7 +248,7 @@ impl ItemKind {
|
||||
|
||||
/// Items the layouts put in fixed places. The app tags its own About, Settings, Quit, Appearance
|
||||
/// and Language items; the Mac layout adds Hide and Minimize.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum ItemRole {
|
||||
/// The About item.
|
||||
@@ -268,7 +269,7 @@ pub enum ItemRole {
|
||||
}
|
||||
|
||||
/// The items AppKit provides.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum Standard {
|
||||
#[allow(missing_docs)]
|
||||
@@ -307,7 +308,7 @@ pub(crate) fn label_or_system(label: &str, english: &str, system: impl FnOnce(&s
|
||||
|
||||
/// The commands of the items the crate adds itself. The crate runs them; an app sees them only
|
||||
/// in a layout's result.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum Builtin {
|
||||
/// Hide the app: a custom item, because AppKit's own always takes ⌘H, which apps often bind.
|
||||
@@ -653,73 +654,78 @@ impl Row {
|
||||
|
||||
/// The menus as a tree, from flat rows, in the order an in-window bar draws them: one menu per
|
||||
/// entry of `tops`, and at each depth leaves and separators in order, with a submenu where its
|
||||
/// first row is. The result is [`tidy`].
|
||||
/// first row is. The result is [`tidy`]. Each row is visited once per depth of its path.
|
||||
pub fn from_items(tops: &[&str], rows: &[Row]) -> MenuBar {
|
||||
/// One entry of a level in order: a row of the level itself, or the group of rows under a submenu name.
|
||||
enum Slot<'r> {
|
||||
Leaf(&'r Row),
|
||||
Group(&'r str, Vec<&'r Row>),
|
||||
}
|
||||
fn level(rows: &[&Row], depth: usize) -> Vec<Node> {
|
||||
let mut out = Vec::new();
|
||||
let mut shown: Vec<&str> = Vec::new();
|
||||
let mut slots: Vec<Slot<'_>> = Vec::new();
|
||||
let mut groups: HashMap<&str, usize> = HashMap::new();
|
||||
for it in rows {
|
||||
if it.path.len() == depth {
|
||||
if it.label == "---" {
|
||||
out.push(Node::Separator);
|
||||
} else {
|
||||
out.push(Node::Item(Item {
|
||||
shortcut: it.shortcut,
|
||||
enabled: it.enabled,
|
||||
kind: it.kind,
|
||||
tint: it.tint,
|
||||
tooltip: it.tooltip.clone(),
|
||||
alternate: it.alternate.clone(),
|
||||
..Item::new(it.command.clone(), it.label.clone())
|
||||
}));
|
||||
}
|
||||
slots.push(Slot::Leaf(it));
|
||||
} else if let Some(name) = it.path.get(depth) {
|
||||
let name = name.as_str();
|
||||
if shown.contains(&name) {
|
||||
continue;
|
||||
let at = *groups.entry(name.as_str()).or_insert_with(|| {
|
||||
slots.push(Slot::Group(name.as_str(), Vec::new()));
|
||||
slots.len() - 1
|
||||
});
|
||||
if let Slot::Group(_, members) = &mut slots[at] {
|
||||
members.push(it);
|
||||
}
|
||||
shown.push(name);
|
||||
let child: Vec<&Row> = rows.iter().copied().filter(|c| c.path.get(depth).map(String::as_str) == Some(name)).collect();
|
||||
out.push(Node::submenu(name, level(&child, depth + 1)));
|
||||
}
|
||||
}
|
||||
tidy(out)
|
||||
let mut out = Vec::with_capacity(slots.len());
|
||||
for slot in slots {
|
||||
match slot {
|
||||
Slot::Leaf(it) if it.label == "---" => out.push(Node::Separator),
|
||||
Slot::Leaf(it) => out.push(Node::Item(Item {
|
||||
shortcut: it.shortcut,
|
||||
enabled: it.enabled,
|
||||
kind: it.kind,
|
||||
tint: it.tint,
|
||||
tooltip: it.tooltip.clone(),
|
||||
alternate: it.alternate.clone(),
|
||||
..Item::new(it.command.clone(), it.label.clone())
|
||||
})),
|
||||
Slot::Group(name, members) => out.push(Node::submenu(name, level(&members, depth + 1))),
|
||||
}
|
||||
}
|
||||
tidy(&mut out);
|
||||
out
|
||||
}
|
||||
let menus = tops
|
||||
.iter()
|
||||
.map(|top| {
|
||||
let rows: Vec<&Row> = rows.iter().filter(|r| r.path.first().map(String::as_str) == Some(*top)).collect();
|
||||
Menu::new(*top, level(&rows, 1))
|
||||
})
|
||||
.collect();
|
||||
let mut by_top: HashMap<&str, Vec<&Row>> = HashMap::new();
|
||||
for row in rows {
|
||||
if let Some(top) = row.path.first() {
|
||||
by_top.entry(top.as_str()).or_default().push(row);
|
||||
}
|
||||
}
|
||||
let menus = tops.iter().map(|top| Menu::new(*top, level(by_top.get(top).map_or(&[][..], Vec::as_slice), 1))).collect();
|
||||
MenuBar { menus, documents: Vec::new() }
|
||||
}
|
||||
|
||||
/// Drop separators at the start or end of a level and collapse runs of them, and drop empty
|
||||
/// submenus, at every depth. A submenu holding only a disabled placeholder (`No Recent Files`)
|
||||
/// submenus, at every depth, in place. A submenu holding only a disabled placeholder (`No Recent Files`)
|
||||
/// stays.
|
||||
pub fn tidy(nodes: Vec<Node>) -> Vec<Node> {
|
||||
let mut out: Vec<Node> = Vec::with_capacity(nodes.len());
|
||||
for n in nodes {
|
||||
let n = match n {
|
||||
Node::Submenu { label, children, role, platforms } => {
|
||||
let children = tidy(children);
|
||||
if children.is_empty() {
|
||||
continue;
|
||||
}
|
||||
Node::Submenu { label, children, role, platforms }
|
||||
pub fn tidy(nodes: &mut Vec<Node>) {
|
||||
let mut previous_separator = true;
|
||||
nodes.retain_mut(|node| {
|
||||
if let Node::Submenu { children, .. } = node {
|
||||
tidy(children);
|
||||
if children.is_empty() {
|
||||
return false;
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
if matches!(n, Node::Separator) && matches!(out.last(), None | Some(Node::Separator)) {
|
||||
continue;
|
||||
}
|
||||
out.push(n);
|
||||
let separator = matches!(node, Node::Separator);
|
||||
let keep = !(separator && previous_separator);
|
||||
previous_separator = separator;
|
||||
keep
|
||||
});
|
||||
while matches!(nodes.last(), Some(Node::Separator)) {
|
||||
nodes.pop();
|
||||
}
|
||||
while matches!(out.last(), Some(Node::Separator)) {
|
||||
out.pop();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A hash of everything a native menu can only change by rebuilding: menus, roles, item
|
||||
|
||||
@@ -131,7 +131,8 @@ impl ThemeMenu {
|
||||
nodes.extend(self.mode_groups(|_| true));
|
||||
nodes.push(Node::Separator);
|
||||
nodes.push(Node::Item(Item::new(ThemeChoice::NextMode.command(), labels.toggle.as_str())));
|
||||
tidy(nodes)
|
||||
tidy(&mut nodes);
|
||||
nodes
|
||||
}
|
||||
|
||||
/// The rows for a quick menu: the Appearance Settings row running `settings`, then the
|
||||
@@ -139,7 +140,8 @@ impl ThemeMenu {
|
||||
pub fn favorite_items(&self, labels: &ThemeLabels, settings: CommandRef) -> Vec<Node> {
|
||||
let mut nodes = vec![Node::Item(Item::new(settings, labels.settings.as_str())), Node::Separator];
|
||||
nodes.extend(self.mode_groups(|r| self.favorites.contains(&r.id)));
|
||||
tidy(nodes)
|
||||
tidy(&mut nodes);
|
||||
nodes
|
||||
}
|
||||
|
||||
/// The "Appearance" submenu, tagged [`crate::ItemRole::Appearance`].
|
||||
|
||||
@@ -133,11 +133,11 @@ pub(super) fn run() {
|
||||
};
|
||||
assert!(new_enabled(&main), "no dialog: New is enabled");
|
||||
menu.set_gate(Gate::default().modal(true));
|
||||
menu.sync_with(1, || layout(1));
|
||||
menu.sync_with(&1_u64, || layout(1));
|
||||
assert!(Retained::as_ptr(&main) == Retained::as_ptr(&main_menu()), "the gate updated the menu, not rebuilt it");
|
||||
assert!(!new_enabled(&main_menu()), "a dialog greys New");
|
||||
menu.set_gate(Gate::default());
|
||||
menu.sync_with(1, || layout(1));
|
||||
menu.sync_with(&1_u64, || layout(1));
|
||||
assert!(new_enabled(&main_menu()), "New is enabled again");
|
||||
|
||||
// A key equivalent: ⌘R reaches egui as the key press ⌘R, once, and is no click.
|
||||
@@ -179,7 +179,7 @@ pub(super) fn run() {
|
||||
|
||||
// Window ends with the open documents. Opening one rebuilds only the Window menu, which AppKit still knows as
|
||||
// its Window menu; choosing a row brings that document forward.
|
||||
menu.sync_with(2, || layout(2));
|
||||
menu.sync_with(&2_u64, || layout(2));
|
||||
assert!(Retained::as_ptr(&main) == Retained::as_ptr(&main_menu()), "a new document rebuilt only the Window menu");
|
||||
let window = submenu(&main_menu(), "Window");
|
||||
assert!(nsapp.windowsMenu().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)), "AppKit knows the new Window menu");
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! `from_items` groups flat rows by menu path in one pass; the tree is the one the row-by-row walk made: submenus where their
|
||||
//! first row is, separators tidied at every depth.
|
||||
|
||||
use craft_menu::{CommandRef, MenuBar, Node, Row, from_items, tidy};
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
/// The row-by-row walk `from_items` replaced: every submenu filters all rows of its level again.
|
||||
fn reference(tops: &[&str], rows: &[Row]) -> MenuBar {
|
||||
fn level(rows: &[&Row], depth: usize) -> Vec<Node> {
|
||||
let mut out = Vec::new();
|
||||
let mut shown: Vec<&str> = Vec::new();
|
||||
for it in rows {
|
||||
if it.path.len() == depth {
|
||||
out.push(if it.label == "---" { Node::Separator } else { Node::Item(craft_menu::Item::new(it.command.clone(), it.label.clone())) });
|
||||
} else if let Some(name) = it.path.get(depth) {
|
||||
let name = name.as_str();
|
||||
if shown.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
shown.push(name);
|
||||
let child: Vec<&Row> = rows.iter().copied().filter(|c| c.path.get(depth).map(String::as_str) == Some(name)).collect();
|
||||
out.push(Node::submenu(name, level(&child, depth + 1)));
|
||||
}
|
||||
}
|
||||
old_tidy(out)
|
||||
}
|
||||
let menus = tops
|
||||
.iter()
|
||||
.map(|top| {
|
||||
let rows: Vec<&Row> = rows.iter().filter(|r| r.path.first().map(String::as_str) == Some(*top)).collect();
|
||||
craft_menu::Menu::new(*top, level(&rows, 1))
|
||||
})
|
||||
.collect();
|
||||
MenuBar::new(menus)
|
||||
}
|
||||
|
||||
/// The tidy `from_items` used before it worked in place.
|
||||
fn old_tidy(nodes: Vec<Node>) -> Vec<Node> {
|
||||
let mut out: Vec<Node> = Vec::with_capacity(nodes.len());
|
||||
for mut n in nodes {
|
||||
if let Node::Submenu { children, .. } = &mut n {
|
||||
*children = old_tidy(std::mem::take(children));
|
||||
if children.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if matches!(n, Node::Separator) && matches!(out.last(), None | Some(Node::Separator)) {
|
||||
continue;
|
||||
}
|
||||
out.push(n);
|
||||
}
|
||||
while matches!(out.last(), Some(Node::Separator)) {
|
||||
out.pop();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn row(path: &[&str], id: &str) -> Row {
|
||||
Row::new(path, CommandRef::new(id), id)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn from_items_builds_the_tree_the_row_by_row_walk_built() {
|
||||
let rows = [
|
||||
Row::separator(&["File"]),
|
||||
row(&["File"], "file.new"),
|
||||
row(&["File", "Recent"], "file.a"),
|
||||
Row::separator(&["File"]),
|
||||
Row::separator(&["File"]),
|
||||
row(&["File", "Recent", "More"], "file.deep"),
|
||||
row(&["File", "Recent"], "file.b"),
|
||||
row(&["File"], "file.save"),
|
||||
Row::separator(&["File", "Recent"]),
|
||||
row(&["File", "Export"], "file.png"),
|
||||
Row::separator(&["File"]),
|
||||
row(&["Edit"], "edit.undo"),
|
||||
row(&["Stray"], "stray"),
|
||||
row(&["Edit", "Find", "In Files"], "edit.find"),
|
||||
Row::separator(&["Edit"]),
|
||||
Row::separator(&["Edit", "Empty"]),
|
||||
];
|
||||
let tops = ["File", "Edit", "View"];
|
||||
assert_eq!(from_items(&tops, &rows), reference(&tops, &rows));
|
||||
let bar = from_items(&tops, &rows);
|
||||
assert_eq!(bar.menus.len(), 3, "a top with no rows stays an empty menu");
|
||||
assert!(bar.menus[2].children.is_empty());
|
||||
let Node::Submenu { label, .. } = &bar.menus[0].children[1] else { panic!("the submenu sits where its first row is") };
|
||||
assert_eq!(label, "Recent");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn tidy_drops_edge_and_repeated_separators_and_empty_submenus_in_place() {
|
||||
let mut nodes = vec![
|
||||
Node::Separator,
|
||||
Node::Separator,
|
||||
Node::Item(craft_menu::Item::new("a", "A")),
|
||||
Node::submenu("Empty", vec![Node::Separator]),
|
||||
Node::Separator,
|
||||
Node::Separator,
|
||||
Node::submenu("Kept", vec![Node::Separator, Node::Item(craft_menu::Item::new("b", "B")), Node::Separator]),
|
||||
Node::Separator,
|
||||
];
|
||||
tidy(&mut nodes);
|
||||
let labels: Vec<&str> = nodes
|
||||
.iter()
|
||||
.map(|n| match n {
|
||||
Node::Item(it) => it.label.as_str(),
|
||||
Node::Submenu { label, children, .. } => {
|
||||
assert_eq!(children.len(), 1, "the submenu's own separators are tidied");
|
||||
label.as_str()
|
||||
}
|
||||
_ => "-",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(labels, ["A", "-", "Kept"]);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod appkit;
|
||||
pub(crate) mod from_items;
|
||||
pub(crate) mod keytips;
|
||||
pub(crate) mod layout;
|
||||
pub(crate) mod memo;
|
||||
|
||||
@@ -3,17 +3,23 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_host::target::Os;
|
||||
use craft_keymap::Overrides;
|
||||
use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items};
|
||||
use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_frame_memo_runs, trial};
|
||||
use craft_ui::contract::Tracked;
|
||||
use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_key_bytes, trial};
|
||||
use egui::{Event, Key, Modifiers};
|
||||
|
||||
fn model(title: &str) -> MenuBar {
|
||||
from_items(&[title, "Edit"], &[Row::new(&[title], CommandRef::new("file.new"), "New"), Row::new(&["Edit"], CommandRef::new("edit.undo"), "Undo")])
|
||||
fn model(title: &str) -> Tracked<MenuBar> {
|
||||
Tracked::new(from_items(
|
||||
&[title, "Edit"],
|
||||
&[Row::new(&[title], CommandRef::new("file.new"), "New"), Row::new(&["Edit"], CommandRef::new("edit.undo"), "Undo")],
|
||||
))
|
||||
}
|
||||
|
||||
fn fixture(bar: &Rc<RefCell<MenuBar>>) -> Fixture {
|
||||
fn fixture(bar: &Rc<RefCell<Tracked<MenuBar>>>) -> Fixture {
|
||||
let bar = Rc::clone(bar);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
MenuBarUi::new(&bar.borrow()).target(Target::Linux).show(ui);
|
||||
@@ -40,7 +46,7 @@ fn an_idle_menu_bar_replays_and_a_title_rename_runs_it_once() {
|
||||
}
|
||||
assert!(fixture.by_label("File").is_some(), "a replayed bar keeps its titles' nodes");
|
||||
|
||||
*bar.borrow_mut() = model("Document");
|
||||
bar.borrow_mut().edit(|bar| *bar = model("Document").into_inner());
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(counted(&fixture).0, 1, "a model change runs the bar once in that frame");
|
||||
assert!(fixture.by_label("Document").is_some(), "and it shows the new title");
|
||||
@@ -81,3 +87,75 @@ fn an_open_menu_runs_the_bar_and_closing_it_replays_it() {
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(counted(&fixture), (0, 1), "after the menu closes and the keyboard leaves, the bar replays");
|
||||
}
|
||||
|
||||
/// The label builds of the last frame.
|
||||
fn label_builds(fixture: &Fixture) -> u32 {
|
||||
last_frame_derived_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum()
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_idle_bar_and_an_open_menu_build_no_labels() {
|
||||
let bar = Rc::new(RefCell::new(model("File")));
|
||||
let mut fixture = fixture(&bar);
|
||||
for _ in 0..3 {
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(label_builds(&fixture), 0, "an idle bar builds no labels");
|
||||
}
|
||||
fixture.key(Key::F, Modifiers::ALT);
|
||||
fixture.settle();
|
||||
assert!(fixture.by_label("New").is_some(), "Alt+F opened File");
|
||||
for _ in 0..3 {
|
||||
fixture.frame(vec![]);
|
||||
assert!(counted(&fixture).0 > 0, "the bar runs each pass while a menu is open");
|
||||
assert_eq!(label_builds(&fixture), 0, "and builds no labels");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_model_edit_builds_the_labels_once() {
|
||||
let bar = Rc::new(RefCell::new(model("File")));
|
||||
let mut fixture = fixture(&bar);
|
||||
bar.borrow_mut().edit(|bar| *bar = model("Document").into_inner());
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(label_builds(&fixture), 1, "one edit builds the labels once");
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(label_builds(&fixture), 0, "and the next frame none");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_locale_change_builds_the_labels_once() {
|
||||
let bar = Rc::new(RefCell::new(model("File")));
|
||||
let mut fixture = fixture(&bar);
|
||||
fixture.host(crate::mnemonic::turkish());
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(label_builds(&fixture), 1, "a language change builds the labels once");
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(label_builds(&fixture), 0, "and the next frame none");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_keymap_change_builds_the_labels_once() {
|
||||
let bar = Rc::new(RefCell::new(model("File")));
|
||||
let mut fixture = fixture(&bar);
|
||||
fixture.overrides(Arc::new(Overrides::default()));
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(label_builds(&fixture), 1, "a new keymap builds the labels once");
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(label_builds(&fixture), 0, "and the next frame none");
|
||||
}
|
||||
|
||||
/// The key bytes of an idle pass of a bar whose File menu has `rows` rows.
|
||||
fn idle_key_bytes(rows: usize) -> usize {
|
||||
let items: Vec<Row> = (0..rows).map(|row| Row::new(&["File"], CommandRef::new(format!("file.row{row}")), format!("Row {row}"))).collect();
|
||||
let bar = Rc::new(RefCell::new(Tracked::new(from_items(&["File"], &items))));
|
||||
let mut fixture = fixture(&bar);
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(label_builds(&fixture), 0, "an idle bar builds no labels");
|
||||
last_pass_memo_key_bytes(fixture.ctx())
|
||||
}
|
||||
|
||||
/// An idle bar feeds the same key bytes whatever its model's size.
|
||||
#[trial]
|
||||
fn a_menu_bars_idle_key_bytes_do_not_grow_with_its_rows() {
|
||||
assert_eq!(idle_key_bytes(20), idle_key_bytes(2_000), "the key follows the model's revision, not its rows");
|
||||
}
|
||||
@@ -6,12 +6,13 @@ use std::sync::Arc;
|
||||
use craft_host::target::Os;
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_menu::{CommandRef, Labeled, MenuBarUi, Row, from_items};
|
||||
use craft_ui::contract::Tracked;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
#[trial]
|
||||
fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() {
|
||||
let bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")]);
|
||||
let bar = Tracked::new(from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")]));
|
||||
let english = |labeled: Labeled<'_>| match labeled {
|
||||
Labeled::Title("文件") => Some("File".to_owned()),
|
||||
Labeled::Command(command) if *command == CommandRef::new("file.new") => Some("New".to_owned()),
|
||||
@@ -30,7 +31,7 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() {
|
||||
}
|
||||
|
||||
/// A host whose interface language is Turkish, with an empty catalog.
|
||||
fn turkish() -> Arc<Host> {
|
||||
pub(crate) fn turkish() -> Arc<Host> {
|
||||
let (i18n, _) = craft_i18n::I18n::from_owned([("tr".to_owned(), String::new(), String::new())], &["tr"]);
|
||||
let tr = i18n.from_code("tr").unwrap_or_else(|| panic!("tr is offered"));
|
||||
Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).lang(tr).build())
|
||||
@@ -39,8 +40,10 @@ fn turkish() -> Arc<Host> {
|
||||
/// The rows shown after Alt with `key` on a Linux bar titled `ix` and `ı` under a Turkish host: `One` is `ix`'s, `Two`
|
||||
/// is `ı`'s.
|
||||
fn opened_by(key: Key) -> (bool, bool) {
|
||||
let bar =
|
||||
from_items(&["ix", "ı"], &[Row::new(&["ix"], CommandRef::new("menu.one"), "One"), Row::new(&["ı"], CommandRef::new("menu.two"), "Two")]);
|
||||
let bar = Tracked::new(from_items(
|
||||
&["ix", "ı"],
|
||||
&[Row::new(&["ix"], CommandRef::new("menu.one"), "One"), Row::new(&["ı"], CommandRef::new("menu.two"), "Two")],
|
||||
));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
MenuBarUi::new(&bar).show(ui);
|
||||
});
|
||||
|
||||
@@ -8,10 +8,10 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use craft_keymap::Mods;
|
||||
use craft_menu::{
|
||||
Alternate, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, LayoutOptions, MenuBar, NativeMenu, mac_layout,
|
||||
structure_key,
|
||||
Alternate, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, ItemState, LayoutOptions, MenuBar, NativeMenu, apply_state,
|
||||
mac_layout, structure_key,
|
||||
};
|
||||
use craft_ui::contract::{Props as _, Show as _};
|
||||
use craft_ui::contract::{Props as _, Show as _, Tracked};
|
||||
use craft_ui::testing::focus::key_release;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::pointer::click;
|
||||
@@ -146,14 +146,14 @@ fn a_modal_gate_greys_the_apps_items() {
|
||||
builds.set(builds.get() + 1);
|
||||
mac_layout(&sample(false, true), &opts)
|
||||
};
|
||||
menu.sync_with(1, build);
|
||||
menu.sync_with(&1_u64, build);
|
||||
menu.set_gate(modal());
|
||||
menu.sync_with(1, build);
|
||||
menu.sync_with(1, build);
|
||||
menu.sync_with(&1_u64, build);
|
||||
menu.sync_with(&1_u64, build);
|
||||
menu.set_gate(Gate::default());
|
||||
menu.sync_with(1, build);
|
||||
menu.sync_with(&1_u64, build);
|
||||
menu.set_gate(typing(true));
|
||||
menu.sync_with(1, build);
|
||||
menu.sync_with(&1_u64, build);
|
||||
assert_eq!((builds.get(), synced.borrow().len()), (1, 4), "one layout; synced open, greyed, open, typing");
|
||||
|
||||
let synced = synced.borrow();
|
||||
@@ -309,3 +309,44 @@ fn an_option_click_runs_the_rows_alternate() {
|
||||
let key = dispatch.chosen(&merge, Some(&shortcut), false, true, held([true, false, true, true]), Some(&alternate));
|
||||
assert_eq!(key, Event::Key(chord("Cmd+Alt+Shift+E")), "a key equivalent is never swapped");
|
||||
}
|
||||
|
||||
/// The menus are laid out again only when the key moved or a menu event arrived: a model edit moves the `Tracked` key once.
|
||||
#[trial]
|
||||
fn sync_with_lays_the_menus_out_only_when_the_key_moves() {
|
||||
let (mut menu, _, events, _) = driver();
|
||||
let opts = LayoutOptions::new("Sample");
|
||||
let mut model = Tracked::new(sample(false, true));
|
||||
let builds = Cell::new(0);
|
||||
let build = |model: &Tracked<MenuBar>| {
|
||||
builds.set(builds.get() + 1);
|
||||
mac_layout(model, &opts)
|
||||
};
|
||||
for _ in 0..3 {
|
||||
menu.sync_with(&model, || build(&model));
|
||||
}
|
||||
assert_eq!(builds.get(), 1, "a key that did not move lays the menus out once");
|
||||
model.edit(|bar| bar.tag_menu("File", craft_menu::MenuRole::Other));
|
||||
menu.sync_with(&model, || build(&model));
|
||||
menu.sync_with(&model, || build(&model));
|
||||
assert_eq!(builds.get(), 2, "an edit moves the key once");
|
||||
events.borrow_mut().push(Event::Handled(cmd("file.new")));
|
||||
menu.poll(&egui::Context::default());
|
||||
menu.sync_with(&model, || build(&model));
|
||||
assert_eq!(builds.get(), 3, "a menu event lays them out again");
|
||||
}
|
||||
|
||||
/// `apply_state` writes the model only when an item's state differs, so a frame that changes nothing keeps its revision.
|
||||
#[trial]
|
||||
fn apply_state_with_no_change_keeps_the_revision() {
|
||||
let mut model = Tracked::new(sample(false, true));
|
||||
let state = |_: &CommandRef| ItemState::default();
|
||||
apply_state(&mut model, state);
|
||||
let kept = model.revision();
|
||||
apply_state(&mut model, state);
|
||||
assert_eq!(model.revision(), kept, "the same state writes nothing");
|
||||
apply_state(&mut model, |command| ItemState::default().enabled(*command != cmd("file.new")));
|
||||
assert_ne!(model.revision(), kept, "a changed state moves the revision");
|
||||
let moved = model.revision();
|
||||
apply_state(&mut model, |command| ItemState::default().enabled(*command != cmd("file.new")));
|
||||
assert_eq!(model.revision(), moved, "and the same changed state again does not");
|
||||
}
|
||||
@@ -10,6 +10,8 @@ repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
bitflags = { workspace = true }
|
||||
craft-tracked = { workspace = true }
|
||||
craft-ui-macros = { workspace = true }
|
||||
ecolor = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
smallvec = { workspace = true }
|
||||
|
||||
@@ -226,7 +226,7 @@ impl From<Rgba> for Oklch {
|
||||
|
||||
/// An encoded sRGB colour with float channels in 0..=1 and straight alpha: the value a colour
|
||||
/// picker edits. Eight bits lose the precision that HSB and OKLCH edits need.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui_macros::PlainData)]
|
||||
pub struct Srgba {
|
||||
/// Red, encoded.
|
||||
pub r: f32,
|
||||
|
||||
@@ -330,7 +330,7 @@ pub struct BorderColors {
|
||||
}
|
||||
|
||||
/// PhotoCraft's layer label colours (`LabelColor`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, craft_ui_macros::PlainData)]
|
||||
pub enum LabelColor {
|
||||
#[allow(missing_docs)]
|
||||
Red,
|
||||
|
||||
@@ -66,16 +66,17 @@ impl Library for Foundation {
|
||||
|
||||
fn build(&self, name: &str) -> SceneBuild {
|
||||
let (scene, equivalent): (Box<dyn Scene>, &'static str) = match name {
|
||||
"inspector-500-fields" => (
|
||||
Box::new(InspectorScene::new()),
|
||||
"inspector-500-fields" | "inspector-1000-fields" => (
|
||||
Box::new(InspectorScene::new(if name == "inspector-500-fields" { 500 } else { 1000 })),
|
||||
// F8-MERGE: family (Field row): the field's own side label stands in for the `Field` row.
|
||||
"500 rows alternating NumberField and TextField, each with its side label (no Field row component yet)",
|
||||
"500 (or 1000) rows alternating NumberField and TextField, each with its side label (no Field row component yet)",
|
||||
),
|
||||
"virtual-list-10000" => (Box::new(ListScene::new(Selected::None)), "List over 10,000 ListRow rows, one selected row"),
|
||||
"sheet-50x200" => (Box::new(SheetScene), "BenchList of 200 rows, each with 50 cell parts that paint their text"),
|
||||
// F8-MERGE: canvas: the canvas component and its declared controls.
|
||||
"canvas-50-controls" => (Box::new(CanvasScene), "a leaf with 50 control parts painted as knobs"),
|
||||
"menu-40-rows" => (Box::new(MenuScene), "a Menu open from the first frame over 40 MenuItem rows"),
|
||||
"menu-40-rows" => (Box::new(MenuScene { rows: 40 }), "a Menu open from the first frame over 40 MenuItem rows"),
|
||||
"menu-80-rows" => (Box::new(MenuScene { rows: 80 }), "a Menu open from the first frame over 80 MenuItem rows"),
|
||||
"table-1000x5" => (Box::new(TableScene), "a Table of 1,000 rows and 5 columns, text in every cell"),
|
||||
"tile-grid-500" => (Box::new(TileGridScene), "a TileGrid of 500 Tiles"),
|
||||
"text-field-100kb" => (Box::new(TextScene::new()), "TextField::lines(30) bound with Bind::bound over a 100 KB String"),
|
||||
@@ -114,8 +115,8 @@ struct InspectorScene {
|
||||
}
|
||||
|
||||
impl InspectorScene {
|
||||
fn new() -> Self {
|
||||
Self { values: (0..500).map(|i| Some(f64::from(i))).collect(), texts: (0..500).map(|i| format!("Value {i}")).collect() }
|
||||
fn new(count: i32) -> Self {
|
||||
Self { values: (0..count).map(|i| Some(f64::from(i))).collect(), texts: (0..count).map(|i| format!("Value {i}")).collect() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,7 +196,10 @@ impl Scene for CanvasScene {
|
||||
}
|
||||
}
|
||||
|
||||
struct MenuScene;
|
||||
/// A menu open over `rows` items.
|
||||
struct MenuScene {
|
||||
rows: usize,
|
||||
}
|
||||
|
||||
impl Scene for MenuScene {
|
||||
fn size(&self) -> Vec2 {
|
||||
@@ -205,7 +209,7 @@ impl Scene for MenuScene {
|
||||
fn show(&mut self, ui: &mut Ui, _frame: u64) {
|
||||
let mut open = true;
|
||||
let _ = Menu::new("Items").open(Bind::bound(&mut open)).id_salt("menu").show(ui, |ui, _| {
|
||||
for key in 0..40 {
|
||||
for key in 0..self.rows {
|
||||
let _ = MenuItem::new(format!("Item {key}")).id_salt(key).show(ui);
|
||||
}
|
||||
});
|
||||
@@ -533,8 +537,17 @@ impl Scene for ReadoutScene {
|
||||
}
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
let report = run_all(&Foundation { root: RootEnv::default() });
|
||||
// `--only <scenario>` runs one scenario and prints its row: for profiling, it writes no baseline and runs no gate.
|
||||
let mut args = std::env::args().skip(1);
|
||||
let only = match (args.next().as_deref(), args.next()) {
|
||||
(Some("--only"), Some(name)) => Some(name),
|
||||
_ => None,
|
||||
};
|
||||
let report = run_all(&Foundation { root: RootEnv::default() }, only.as_deref());
|
||||
print_table(&report);
|
||||
if only.is_some() {
|
||||
return std::process::ExitCode::SUCCESS;
|
||||
}
|
||||
let baseline = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("baseline");
|
||||
let outcome = write_json(&report, &baseline.join("foundation.json")).and_then(|()| read_json(&baseline.join("legacy.json")));
|
||||
let legacy = match outcome {
|
||||
|
||||
@@ -114,10 +114,11 @@ fn measure(library: &dyn Library, mut scene: Box<dyn Scene>) -> Measurement {
|
||||
)
|
||||
}
|
||||
|
||||
/// Measures every scenario of [`SCENARIOS`] on `library`.
|
||||
pub fn run_all(library: &dyn Library) -> Report {
|
||||
/// Measures every scenario of [`SCENARIOS`] on `library`, or only the one called `only`.
|
||||
pub fn run_all(library: &dyn Library, only: Option<&str>) -> Report {
|
||||
let scenarios = SCENARIOS
|
||||
.iter()
|
||||
.filter(|scenario| only.is_none_or(|name| scenario.name == name))
|
||||
.map(|scenario| {
|
||||
eprintln!("{}: {}", library.name(), scenario.name);
|
||||
let (equivalent, missing, measurement) = match library.build(scenario.name) {
|
||||
|
||||
@@ -15,10 +15,12 @@ pub struct Scenario {
|
||||
/// Every scenario, in report order.
|
||||
pub const SCENARIOS: &[Scenario] = &[
|
||||
Scenario { name: "inspector-500-fields", description: "an inspector of 500 Field rows", no_discard: false },
|
||||
Scenario { name: "inspector-1000-fields", description: "an inspector of 1,000 Field rows", no_discard: false },
|
||||
Scenario { name: "virtual-list-10000", description: "a 10,000-item virtual list", no_discard: false },
|
||||
Scenario { name: "sheet-50x200", description: "a sheet of 50 x 200 visible cells as row parts", no_discard: false },
|
||||
Scenario { name: "canvas-50-controls", description: "a canvas with 50 canvas controls", no_discard: false },
|
||||
Scenario { name: "menu-40-rows", description: "an open menu with 40 rows", no_discard: false },
|
||||
Scenario { name: "menu-80-rows", description: "an open menu with 80 rows", no_discard: false },
|
||||
Scenario { name: "table-1000x5", description: "a table of 1,000 rows and 5 columns", no_discard: false },
|
||||
Scenario { name: "tile-grid-500", description: "a tile grid of 500 tiles", no_discard: false },
|
||||
Scenario { name: "text-field-100kb", description: "a 100 KB multi-line text field, bound", no_discard: false },
|
||||
|
||||
@@ -203,6 +203,12 @@ impl<'a> BodyCx<'a> {
|
||||
}
|
||||
|
||||
impl BodyCx<'_> {
|
||||
/// The value this body derives from `key`: kept while `key` is unchanged, else built by `build`
|
||||
/// ([`runtime::derived`](crate::runtime::derived::derived), under the body's id).
|
||||
pub fn derived<K: crate::contract::MemoProps, V: Send + Sync + 'static>(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc<V> {
|
||||
crate::runtime::derived::derived(self.memory.ctx(), self.id, key, build)
|
||||
}
|
||||
|
||||
/// Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it
|
||||
/// is empty. `true` once per Escape; the enclosing scope (a dialog, a popover) then does not act on it.
|
||||
/// Components shown earlier in the body have run by the time the body asks.
|
||||
|
||||
@@ -958,6 +958,13 @@ impl MemoProps for craft_theme::variant::Tone {
|
||||
}
|
||||
}
|
||||
|
||||
/// Derived `Hash` over a unit enum.
|
||||
impl MemoProps for craft_theme::LabelColor {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
key.feed_hash(self);
|
||||
}
|
||||
}
|
||||
|
||||
/// Derived `Hash`.
|
||||
impl MemoProps for craft_theme::ComponentSet {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
@@ -1020,6 +1027,13 @@ impl MemoProps for craft_behavior::fit::FitKeep {
|
||||
}
|
||||
}
|
||||
|
||||
/// Derived `Hash` (`#[non_exhaustive]`).
|
||||
impl MemoProps for craft_host::target::Os {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
key.feed_hash(self);
|
||||
}
|
||||
}
|
||||
|
||||
/// Derived `Hash` (`#[non_exhaustive]`).
|
||||
impl MemoProps for craft_host::target::WindowKind {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
|
||||
@@ -1107,11 +1107,18 @@ pub(crate) fn edit_chords(ctx: &Context) -> Arc<[(EditCommand, Chord)]> {
|
||||
with(ctx, |board| board.keymap.as_ref().map(|cache| Arc::clone(&cache.edit_chords)).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The generation of the window's keymap: it moves each time a new keymap is built.
|
||||
pub(crate) fn keymap_generation(ctx: &Context) -> u64 {
|
||||
/// The generation of the window's keymap without noting a read: it moves each time a new keymap is built.
|
||||
pub(crate) fn keymap_built(ctx: &Context) -> u64 {
|
||||
with(ctx, |board| board.keymaps)
|
||||
}
|
||||
|
||||
/// The generation of the window's keymap, for a key that holds what is derived from its chords: it moves each time a
|
||||
/// new keymap is built. The caller's view reads the keymap, so a change of it runs the view.
|
||||
pub fn keymap_generation(ctx: &Context) -> u64 {
|
||||
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap);
|
||||
keymap_built(ctx)
|
||||
}
|
||||
|
||||
/// Whether the queue holds a command for one of `instances`: only a run of the view they registered in takes it.
|
||||
pub(crate) fn queued_for(ctx: &Context, instances: &[Id]) -> bool {
|
||||
!instances.is_empty() && with(ctx, |board| board.queue.iter().any(|fired| fired.target.is_some_and(|target| instances.contains(&target))))
|
||||
|
||||
@@ -31,12 +31,12 @@ pub(crate) use board::{
|
||||
begin, binds_scoped, edit_chords, end, install, note_focus, register_instance, set_input, take_delivered, take_fired, window_shortcuts,
|
||||
};
|
||||
#[doc(hidden)]
|
||||
pub use board::{bound_around, take_around};
|
||||
pub use board::{bound_around, keymap_generation, take_around};
|
||||
#[cfg(feature = "testing")]
|
||||
#[doc(hidden)]
|
||||
pub use board::{chord_text_builds, keymap_builds};
|
||||
pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped};
|
||||
pub(crate) use board::{keymap_generation, queued_for};
|
||||
pub(crate) use board::{keymap_built, queued_for};
|
||||
|
||||
use crate::contract::{MemoKey, MemoProps, PlainData, Revision, Tracked};
|
||||
use craft_behavior::CommandFlags;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Derived values: data a component computes from its inputs and keeps across passes. [`derived`] keeps one value per
|
||||
//! component id and value type, and builds it again only when its key changes. The key implements
|
||||
//! [`MemoProps`], so it can only be made of checked inputs (`Tracked` revisions, framework
|
||||
//! revisions, plain values), and a kept value is never stale while the key compiles.
|
||||
//!
|
||||
//! A value no pass asks for is dropped by the rule memoized views follow for absent entries (`lazy::absent_past_room`).
|
||||
|
||||
use crate::contract::{MemoKey, MemoProps};
|
||||
use crate::runtime::egui::pass;
|
||||
use crate::runtime::frame::PerViewport;
|
||||
use egui::{Context, Id, IdMap};
|
||||
use std::any::{Any, TypeId};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A kept value: the key it was built from and the frame a pass last asked for it.
|
||||
struct Entry {
|
||||
key: u128,
|
||||
value: Arc<dyn Any + Send + Sync>,
|
||||
touched: u64,
|
||||
}
|
||||
|
||||
/// The kept values of one viewport.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Store {
|
||||
entries: IdMap<Entry>,
|
||||
/// The frame the entries were last pruned in.
|
||||
pruned: u64,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
/// Drops the absent entries past the memo rule's room, once per frame. An entry asked for in this frame or the one
|
||||
/// before is shown.
|
||||
fn prune(&mut self, frame: u64) {
|
||||
if self.pruned == frame {
|
||||
return;
|
||||
}
|
||||
self.pruned = frame;
|
||||
let shown = self.entries.values().filter(|entry| entry.touched + 1 >= frame).count();
|
||||
let absent = self.entries.iter().filter(|(_, entry)| entry.touched + 1 < frame).map(|(id, entry)| (entry.touched, *id));
|
||||
for id in super::lazy::absent_past_room(shown, absent) {
|
||||
self.entries.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the component `id` derived from `key`: the kept one while `key` is the one it was built from, else
|
||||
/// `build`'s, which is kept in its place. One value is kept per id and value type `V`; a component that derives two
|
||||
/// values of one type gives each its own id.
|
||||
pub fn derived<K: MemoProps, V: Send + Sync + 'static>(ctx: &Context, id: Id, key: &K, build: impl FnOnce() -> V) -> Arc<V> {
|
||||
let mut memo = MemoKey::of_view(ctx);
|
||||
memo.feed_hash(&K::identity());
|
||||
key.key(&mut memo);
|
||||
#[cfg(feature = "testing")]
|
||||
crate::runtime::measure::count_memo_key_bytes(ctx, memo.bytes());
|
||||
let key = memo.finish();
|
||||
let slot = id.with(TypeId::of::<V>());
|
||||
crate::runtime::replay::note_derived_keep(ctx, slot);
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let frame = pass::frame_nr(ctx, viewport);
|
||||
let kept = PerViewport::<Store>::with(ctx, viewport, |store| {
|
||||
store.prune(frame);
|
||||
let entry = store.entries.get_mut(&slot).filter(|entry| entry.key == key)?;
|
||||
entry.touched = frame;
|
||||
Arc::clone(&entry.value).downcast::<V>().ok()
|
||||
});
|
||||
if let Some(value) = kept {
|
||||
return value;
|
||||
}
|
||||
#[cfg(feature = "testing")]
|
||||
crate::runtime::measure::count_derived(ctx, id);
|
||||
// Built outside the store, so a build may derive values of its own.
|
||||
let value = Arc::new(build());
|
||||
let entry = Entry { key, value: Arc::clone(&value) as Arc<dyn Any + Send + Sync>, touched: frame };
|
||||
PerViewport::<Store>::with(ctx, viewport, |store| store.entries.insert(slot, entry));
|
||||
value
|
||||
}
|
||||
|
||||
/// Keeps the values under `slots` through this frame, for a replayed run that asked for them: the replay asks for
|
||||
/// nothing, and an entry no pass asked for in a frame is dropped by the memo rule.
|
||||
pub(crate) fn keep(ctx: &Context, slots: &[Id]) {
|
||||
if slots.is_empty() {
|
||||
return;
|
||||
}
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let frame = pass::frame_nr(ctx, viewport);
|
||||
PerViewport::<Store>::with(ctx, viewport, |store| {
|
||||
for slot in slots {
|
||||
if let Some(entry) = store.entries.get_mut(slot) {
|
||||
entry.touched = frame;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -124,7 +124,7 @@ pub(crate) fn generation(ctx: &Context, input: Input) -> u64 {
|
||||
Input::Drag => observe(ctx, input, crate::runtime::drag::state(ctx)),
|
||||
Input::Focus => observe(ctx, input, crate::runtime::focus::focus_state(ctx)),
|
||||
Input::Overlays => observe(ctx, input, crate::runtime::overlay::open_state(ctx)),
|
||||
Input::Keymap => return crate::runtime::commands::keymap_generation(ctx),
|
||||
Input::Keymap => return crate::runtime::commands::keymap_built(ctx),
|
||||
Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Scroll => {}
|
||||
}
|
||||
with(ctx, |generations| generations.gens[input as usize])
|
||||
|
||||
@@ -1270,6 +1270,7 @@ pub(crate) mod guard {
|
||||
"runtime::lazy::Store",
|
||||
"lazy extents: the kept extent of content out of view, its own mechanism; a pass a kept transcript serves decides in its real run, which compares each row by its backstop",
|
||||
),
|
||||
("runtime::derived::Store", "derived values: a pure function of their key, so a value a measuring run builds is the one a real run builds"),
|
||||
("contract::steps::scroll_owner::", "scroll reveals and moves: read; taken through take_queued"),
|
||||
("contract::body::scroll::Jumps", "scroll jumps: taken through take_queued"),
|
||||
("runtime::edit::CancelAll", "edit cancels: read; a measuring run ends nothing"),
|
||||
|
||||
@@ -335,6 +335,20 @@ impl Store {
|
||||
}
|
||||
}
|
||||
|
||||
/// The memo rule for absent entries, shared by every memo store (memoized views, `runtime::derived`): an entry
|
||||
/// outlives its absence while the absent ones are at most twice as many as the shown ones, the longest absent dropped
|
||||
/// first. Takes the absent entries as (frame last touched, id) and returns the ones to drop.
|
||||
pub(crate) fn absent_past_room(shown: usize, absent: impl IntoIterator<Item = (u64, Id)>) -> Vec<Id> {
|
||||
let mut absent: Vec<(u64, Id)> = absent.into_iter().collect();
|
||||
let room = 2 * shown;
|
||||
if absent.len() <= room {
|
||||
return Vec::new();
|
||||
}
|
||||
absent.sort_unstable_by_key(|(touched, _)| *touched);
|
||||
absent.truncate(absent.len() - room);
|
||||
absent.into_iter().map(|(_, id)| id).collect()
|
||||
}
|
||||
|
||||
fn with<R>(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R {
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let (pass_nr, frame) = (pass::pass_nr(ctx, viewport), pass::frame_nr(ctx, viewport));
|
||||
@@ -345,16 +359,12 @@ fn with<R>(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R {
|
||||
store.pruned = frame;
|
||||
let reached = &store.reached;
|
||||
store.entries.retain(|_, entry| entry.memo() || entry.live(frame, reached));
|
||||
// A memoized view's entry outlives its absence while the absent ones are at most twice as many as the shown
|
||||
// ones, the longest absent dropped first: a view shown again with the same props replays.
|
||||
// A memoized view's entry outlives its absence by the memo rule: a view shown again with the same props
|
||||
// replays.
|
||||
let shown = store.entries.values().filter(|entry| entry.memo() && entry.live(frame, reached)).count();
|
||||
let mut absent: Vec<(u64, Id)> =
|
||||
store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id)).collect();
|
||||
if absent.len() > 2 * shown {
|
||||
absent.sort_unstable_by_key(|(touched, _)| *touched);
|
||||
for (_, id) in &absent[..absent.len() - 2 * shown] {
|
||||
store.entries.remove(id);
|
||||
}
|
||||
let absent = store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id));
|
||||
for id in absent_past_room(shown, absent) {
|
||||
store.entries.remove(&id);
|
||||
}
|
||||
let owners: IdSet = store.entries.values().filter_map(|entry| entry.owner).collect();
|
||||
store.reached.retain(|owner, _| owners.contains(owner));
|
||||
|
||||
@@ -52,6 +52,17 @@ struct BodyRuns {
|
||||
runs: Vec<(Id, u32)>,
|
||||
}
|
||||
|
||||
/// The derived values built in a pass, by component id, with the pass that counted them.
|
||||
#[cfg(feature = "testing")]
|
||||
#[derive(Default)]
|
||||
pub(crate) struct DerivedBuilds {
|
||||
pass: u64,
|
||||
builds: Vec<(Id, u32)>,
|
||||
/// The frame `frame_builds` counts, and the builds of every pass of it.
|
||||
frame: u64,
|
||||
frame_builds: Vec<(Id, u32)>,
|
||||
}
|
||||
|
||||
/// How many contributions the measuring runs of a pass made that stand, with the pass that counted them.
|
||||
#[cfg(feature = "testing")]
|
||||
#[derive(Default)]
|
||||
@@ -540,6 +551,47 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize {
|
||||
last_totals(ctx, |log| log.key_bytes, 0)
|
||||
}
|
||||
|
||||
/// Counts a build of a derived value of the component `id` in this pass (`runtime::derived`).
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) fn count_derived(ctx: &Context, id: Id) {
|
||||
if uncounted(ctx) {
|
||||
return;
|
||||
}
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
let frame = super::egui::pass::frame_nr(ctx, super::egui::pass::current_viewport(ctx));
|
||||
pass_state::with::<DerivedBuilds, _>(ctx, |log| {
|
||||
if log.frame != frame {
|
||||
log.frame = frame;
|
||||
log.frame_builds.clear();
|
||||
}
|
||||
if log.pass != pass {
|
||||
log.pass = pass;
|
||||
log.builds.clear();
|
||||
}
|
||||
for builds in [&mut log.builds, &mut log.frame_builds] {
|
||||
match builds.iter_mut().find(|(of, _)| *of == id) {
|
||||
Some((_, count)) => *count += 1,
|
||||
None => builds.push((id, 1)),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The components that built a derived value in any pass of the last frame, and how many builds each.
|
||||
#[cfg(feature = "testing")]
|
||||
pub fn last_frame_derived_builds(ctx: &Context) -> Vec<(Id, u32)> {
|
||||
let last = super::egui::pass::frame_nr(ctx, super::egui::pass::current_viewport(ctx)).saturating_sub(1);
|
||||
pass_state::with::<DerivedBuilds, _>(ctx, |log| if log.frame == last { log.frame_builds.clone() } else { Vec::new() })
|
||||
}
|
||||
|
||||
/// The components that built a derived value in the last pass, and how many builds each; empty when that pass built
|
||||
/// none.
|
||||
#[cfg(feature = "testing")]
|
||||
pub fn last_pass_derived_builds(ctx: &Context) -> Vec<(Id, u32)> {
|
||||
let last = ctx.cumulative_pass_nr().saturating_sub(1);
|
||||
pass_state::with::<DerivedBuilds, _>(ctx, |log| if log.pass == last { log.builds.clone() } else { Vec::new() })
|
||||
}
|
||||
|
||||
/// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass.
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) fn count_text_layout(ctx: &Context) {
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod access;
|
||||
pub(crate) mod audit;
|
||||
pub mod commands;
|
||||
pub mod cursor;
|
||||
pub mod derived;
|
||||
pub mod drag;
|
||||
pub mod edit;
|
||||
pub mod egui;
|
||||
|
||||
@@ -119,6 +119,8 @@ pass_state! {
|
||||
memo_log: crate::runtime::measure::MemoLog,
|
||||
#[cfg(feature = "testing")]
|
||||
pass_totals: crate::runtime::measure::PassTotals,
|
||||
#[cfg(feature = "testing")]
|
||||
derived_builds: crate::runtime::measure::DerivedBuilds,
|
||||
}
|
||||
records {
|
||||
focus: crate::runtime::focus::State,
|
||||
@@ -126,6 +128,7 @@ pass_state! {
|
||||
cursor: crate::runtime::cursor::State,
|
||||
layout: crate::runtime::layout_memory::Entries,
|
||||
lazy: crate::runtime::lazy::Store,
|
||||
derived: crate::runtime::derived::Store,
|
||||
arenas: crate::primitives::sensing::Arenas,
|
||||
envs: crate::runtime::env::ViewportEnvs,
|
||||
pointer: crate::runtime::pointer::Memory,
|
||||
|
||||
@@ -157,6 +157,8 @@ pub(crate) struct Facts {
|
||||
pub(crate) owners: Vec<egui::Id>,
|
||||
/// The layout memory entries the run kept (`note_layout_keep`): a replay keeps them (`layout_memory::keep`).
|
||||
pub(crate) layout_keeps: Vec<egui::Id>,
|
||||
/// The derived values the run asked for (`note_derived_keep`): a replay keeps them, since it asks for none.
|
||||
pub(crate) derived_keeps: Vec<egui::Id>,
|
||||
/// The framework inputs the run read outside its props (`runtime::inputs`).
|
||||
pub(crate) inputs: Inputs,
|
||||
/// The command scope instances that registered in the run (`commands::register_instance`): a command queued for one
|
||||
@@ -234,6 +236,7 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record {
|
||||
outer.facts.discards |= open.facts.discards;
|
||||
outer.facts.owners.extend(open.facts.owners.iter().copied());
|
||||
outer.facts.layout_keeps.extend(open.facts.layout_keeps.iter().copied());
|
||||
outer.facts.derived_keeps.extend(open.facts.derived_keeps.iter().copied());
|
||||
outer.facts.wake = min_wake(outer.facts.wake, open.facts.wake);
|
||||
let kept = outer.kept;
|
||||
outer.facts.reads.extend(open.facts.reads.iter().copied().filter(|key| !kept || !matches!(key, BindKey::Place(..))));
|
||||
@@ -249,6 +252,8 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record {
|
||||
// Every measure of an entry keeps it again: the record keeps each one once.
|
||||
facts.layout_keeps.sort_unstable_by_key(|id| id.value());
|
||||
facts.layout_keeps.dedup();
|
||||
facts.derived_keeps.sort_unstable_by_key(|id| id.value());
|
||||
facts.derived_keeps.dedup();
|
||||
// A paint callback's output depends on what its closure holds, which neither a view's key nor a comparison sees:
|
||||
// its run is never replayed.
|
||||
facts.blocked |= egui.layers().any(|on| on != layer) || egui.paints_callback();
|
||||
@@ -361,11 +366,13 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) {
|
||||
pass_state::with::<Recorder, _>(ctx, |recorder| recorder.replaying = false);
|
||||
}
|
||||
crate::runtime::layout_memory::keep(ctx, &record.facts.layout_keeps);
|
||||
crate::runtime::derived::keep(ctx, &record.facts.derived_keeps);
|
||||
if let Some(at) = record.facts.wake {
|
||||
crate::runtime::egui::repaint::request_after(ctx, crate::runtime::egui::pass::current_viewport(ctx), at - frame::clock(ctx));
|
||||
}
|
||||
with_open(ctx, |facts| {
|
||||
facts.layout_keeps.extend(record.facts.layout_keeps.iter().copied());
|
||||
facts.derived_keeps.extend(record.facts.derived_keeps.iter().copied());
|
||||
facts.reads.extend(record.facts.reads.iter().copied());
|
||||
facts.inputs.extend(record.facts.inputs);
|
||||
facts.wake = min_wake(facts.wake, record.facts.wake);
|
||||
@@ -481,6 +488,12 @@ pub(crate) fn note_layout_keep(ctx: &Context, id: egui::Id) {
|
||||
with_open(ctx, |facts| facts.layout_keeps.push(id));
|
||||
}
|
||||
|
||||
/// Notes that the running code asked for the derived value kept under `slot`: a replay of the records open around it
|
||||
/// keeps it too, as the replay asks for nothing and an entry no pass asked for in a frame is dropped.
|
||||
pub(crate) fn note_derived_keep(ctx: &Context, slot: egui::Id) {
|
||||
with_open(ctx, |facts| facts.derived_keeps.push(slot));
|
||||
}
|
||||
|
||||
/// Notes that the memory owner `owner` registered in the running code.
|
||||
pub(crate) fn note_owner(ctx: &Context, owner: egui::Id) {
|
||||
with_open(ctx, |facts| facts.owners.push(owner));
|
||||
|
||||
@@ -298,6 +298,14 @@ impl Fixture {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the user's binding overrides for every following pass, as an app's `FrameInput.commands` does: the keymap is
|
||||
/// rebuilt when the `Arc` is another one.
|
||||
pub fn overrides(&mut self, overrides: std::sync::Arc<craft_keymap::Overrides>) -> &mut Self {
|
||||
self.commands = self.commands.clone().overrides(overrides);
|
||||
self.frames.commands(self.commands.clone());
|
||||
self
|
||||
}
|
||||
|
||||
/// The room the story is shown in.
|
||||
pub fn room(&mut self, room: Vec2) -> &mut Self {
|
||||
self.room = room;
|
||||
|
||||
@@ -54,9 +54,10 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements;
|
||||
#[cfg(feature = "testing")]
|
||||
pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves;
|
||||
pub use crate::runtime::measure::{
|
||||
MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_memo_runs,
|
||||
last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs,
|
||||
last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs,
|
||||
MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_derived_builds,
|
||||
last_frame_memo_runs, last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks,
|
||||
last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures,
|
||||
run as measuring_run, take_effects, widest_runs,
|
||||
};
|
||||
pub use craft_ui_macros::{story, trial};
|
||||
pub use fixture::{Fixture, Impure, Room, Target};
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Derived values: built once per key, kept while the key is unchanged, and dropped by the memo rule once absent.
|
||||
|
||||
use craft_ui::runtime::derived::derived;
|
||||
use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, trial};
|
||||
use egui::Id;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A fixture whose pass derives a value under each id `ids` holds, keyed by `key`; `seen` collects the values.
|
||||
fn deriving(ids: Rc<RefCell<Vec<u32>>>, key: Rc<Cell<u32>>, seen: Rc<RefCell<Vec<Arc<String>>>>) -> Fixture {
|
||||
Fixture::new(move |ui| {
|
||||
seen.borrow_mut().clear();
|
||||
for id in ids.borrow().iter() {
|
||||
let value = derived(ui.ctx(), Id::NULL.with(("derived", *id)), &key.get(), || format!("{id} at {}", key.get()));
|
||||
seen.borrow_mut().push(value);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The number of builds in the last pass.
|
||||
fn builds(fixture: &Fixture) -> u32 {
|
||||
last_pass_derived_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum()
|
||||
}
|
||||
|
||||
/// An unchanged key returns the kept value without a build; a changed key builds once, then keeps that.
|
||||
#[trial]
|
||||
fn a_derived_value_builds_once_per_key() {
|
||||
let (ids, key, seen) = (Rc::new(RefCell::new(vec![1])), Rc::new(Cell::new(7)), Rc::default());
|
||||
let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen));
|
||||
fixture.frame(Vec::new());
|
||||
let first = Arc::clone(&seen.borrow()[0]);
|
||||
for _ in 0..3 {
|
||||
fixture.frame(Vec::new());
|
||||
assert_eq!(builds(&fixture), 0, "an unchanged key builds nothing");
|
||||
assert!(Arc::ptr_eq(&seen.borrow()[0], &first), "and returns the kept value");
|
||||
}
|
||||
key.set(8);
|
||||
fixture.frame(Vec::new());
|
||||
assert_eq!(builds(&fixture), 1, "a changed key builds once");
|
||||
assert_eq!(*seen.borrow()[0], "1 at 8");
|
||||
fixture.frame(Vec::new());
|
||||
assert_eq!(builds(&fixture), 0, "then keeps the new value");
|
||||
}
|
||||
|
||||
/// A value no pass asks for is kept while the absent ones are at most twice the shown ones, and dropped past that.
|
||||
#[trial]
|
||||
fn an_absent_derived_value_is_dropped_by_the_memo_rule() {
|
||||
let (ids, key, seen) = (Rc::new(RefCell::new(vec![1, 2, 3])), Rc::new(Cell::new(0)), Rc::default());
|
||||
let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen));
|
||||
fixture.frame(Vec::new()).frame(Vec::new());
|
||||
*ids.borrow_mut() = vec![1];
|
||||
fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new());
|
||||
*ids.borrow_mut() = vec![1, 2, 3];
|
||||
fixture.frame(Vec::new());
|
||||
assert_eq!(builds(&fixture), 0, "two absent values beside one shown are kept");
|
||||
*ids.borrow_mut() = Vec::new();
|
||||
fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new());
|
||||
*ids.borrow_mut() = vec![1];
|
||||
fixture.frame(Vec::new());
|
||||
assert_eq!(builds(&fixture), 1, "with none shown, every absent value was dropped");
|
||||
}
|
||||
|
||||
/// A memoized view that replays asks for no derived value, and its values stay kept: when the pointer then runs the
|
||||
/// view, it finds them.
|
||||
#[trial]
|
||||
fn a_replayed_view_keeps_the_values_it_derived() {
|
||||
use craft_ui::contract::MemoView;
|
||||
use craft_ui::testing::pointer;
|
||||
let at: Rc<Cell<egui::Pos2>> = Rc::default();
|
||||
let shown = Rc::clone(&at);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = MemoView::new("deriving", 1u32, |key: &mut u32, ui: &mut egui::Ui| {
|
||||
let value = derived(ui.ctx(), Id::NULL.with("derived"), key, || key.to_string());
|
||||
ui.label(value.as_str()).rect.center()
|
||||
})
|
||||
.show(ui);
|
||||
if let Some(out) = out {
|
||||
shown.set(out);
|
||||
}
|
||||
});
|
||||
fixture.room(egui::Vec2::new(200.0, 100.0));
|
||||
fixture.settle().idle(3);
|
||||
for _ in 0..3 {
|
||||
fixture.frame(Vec::new());
|
||||
assert_eq!(builds(&fixture), 0, "an idle frame builds nothing");
|
||||
}
|
||||
fixture.frame(vec![pointer::moved(at.get())]);
|
||||
assert_eq!(last_frame_memo_runs(fixture.ctx()).iter().filter(|(_, _, run)| *run == MemoRun::Ran).count(), 1, "the pointer runs the view");
|
||||
assert_eq!(builds(&fixture), 0, "the view runs for the pointer and finds its value kept");
|
||||
}
|
||||
@@ -4,6 +4,7 @@ pub(crate) mod chord_fallthrough;
|
||||
pub(crate) mod clipboard;
|
||||
pub(crate) mod control_click;
|
||||
pub(crate) mod cursor;
|
||||
pub(crate) mod derived;
|
||||
pub(crate) mod elapsed;
|
||||
pub(crate) mod env;
|
||||
pub(crate) mod frame;
|
||||
|
||||
@@ -10,7 +10,7 @@ use craft_theme::variant::Tone;
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::contract::{BodyCx, Outbox, SizeLimits, Tracked};
|
||||
use craft_ui::display::InspectLayers;
|
||||
use craft_ui::docking::{DockHeights, DockPanels, PanelSpec};
|
||||
use craft_ui::docking::{DockHeights, DockPanels, PanelSpec, PanelSpecs};
|
||||
use craft_ui::menu::PanelRow;
|
||||
use craft_ui::notices::Notice;
|
||||
use craft_window::policy::WindowKind;
|
||||
@@ -62,7 +62,11 @@ impl GalleryDock<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl DockPanels<PanelId> for GalleryDock<'_> {
|
||||
/// The gallery's panel specs: each panel's follow from its id.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::PlainData)]
|
||||
pub struct GallerySpecs;
|
||||
|
||||
impl PanelSpecs<PanelId> for GallerySpecs {
|
||||
fn spec(&self, panel: &PanelId) -> PanelSpec {
|
||||
let spec = PanelSpec::new(panel.title()).limits(SizeLimits::default());
|
||||
match panel {
|
||||
@@ -78,7 +82,9 @@ impl DockPanels<PanelId> for GalleryDock<'_> {
|
||||
fn permissions(&self, panel: &PanelId) -> Permissions {
|
||||
panel.permissions()
|
||||
}
|
||||
}
|
||||
|
||||
impl DockPanels<PanelId> for GalleryDock<'_> {
|
||||
fn body(&mut self, panel: &PanelId, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
match (panel, self.preview) {
|
||||
(PanelId::Preview, Preview::App) => {
|
||||
|
||||
@@ -12,6 +12,7 @@ mod shell;
|
||||
mod variants;
|
||||
|
||||
pub use card::{BodyShown, Card, CardEvents, CardStory, Look, StoryBody};
|
||||
pub use dock::GallerySpecs;
|
||||
pub use inspect::{Inspect, Inspected, region_key};
|
||||
pub use options::options_bar;
|
||||
pub use overview::{Spec, SpecStory, overview_card};
|
||||
|
||||
@@ -25,6 +25,7 @@ use craft_ui::shell::app::ShellApp;
|
||||
use craft_ui::shell::embed::CloseDecision;
|
||||
use egui::Ui;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use web_time::Instant;
|
||||
|
||||
/// The viewer as the root window's app.
|
||||
@@ -84,7 +85,7 @@ fn read_dropped(file: &OsFile) -> Result<AppSizes, String> {
|
||||
/// The registered name of the component whose tab is in front and selected in the shown workspace's dock.
|
||||
fn front_component(viewer: &Viewer) -> Option<&'static str> {
|
||||
let dock = if viewer.workspace == Workspace::Theme { &viewer.theme_dock } else { &viewer.dock };
|
||||
viewer.browser.selected_type().filter(|type_name| dock.layout.panel_state(&PanelId::component(type_name)) == PanelState::Front)
|
||||
viewer.browser.selected_type().filter(|type_name| dock.layout().panel_state(&PanelId::component(type_name)) == PanelState::Front)
|
||||
}
|
||||
|
||||
/// Gives an open Variants view its centre tab: the front centre tab of the components workspace when the view opens,
|
||||
@@ -92,12 +93,12 @@ fn front_component(viewer: &Viewer) -> Option<&'static str> {
|
||||
/// runs.
|
||||
fn place_variants(viewer: &mut Viewer) {
|
||||
let front =
|
||||
|panel: &PanelId| matches!(panel, PanelId::Overview | PanelId::Component(_)) && viewer.dock.layout.panel_state(panel) == PanelState::Front;
|
||||
|panel: &PanelId| matches!(panel, PanelId::Overview | PanelId::Component(_)) && viewer.dock.layout().panel_state(panel) == PanelState::Front;
|
||||
let owner = match (&viewer.variants, &viewer.variants_tab) {
|
||||
(None, _) => None,
|
||||
(Some(_), Some(tab)) if front(tab) => Some(tab.clone()),
|
||||
(Some(_), Some(_)) => None,
|
||||
(Some(_), None) => viewer.dock.layout.panels().into_iter().find(|panel| front(panel)).cloned(),
|
||||
(Some(_), None) => viewer.dock.layout().panels().into_iter().find(|panel| front(panel)).cloned(),
|
||||
};
|
||||
if owner.is_none() {
|
||||
viewer.variants = None;
|
||||
@@ -109,12 +110,12 @@ fn place_variants(viewer: &mut Viewer) {
|
||||
fn body(ui: &mut Ui, _: &mut BodyCx<'_>, viewer: &mut Viewer) {
|
||||
place_variants(viewer);
|
||||
let selected = front_component(viewer).map(PanelId::component);
|
||||
let Viewer { env, workspace, preview, browser, dock, themes, theme_dock, mock, variants, variants_tab, inspect_layers, .. } = viewer;
|
||||
let Viewer { env, workspace, preview, browser, dock, themes, theme_dock, specs, mock, variants, variants_tab, inspect_layers, .. } = viewer;
|
||||
let appearance = env.appearance(ui.ctx());
|
||||
let subject = ThemeSubject::new(theme_of(env.theme_id()), appearance);
|
||||
let in_theme = *workspace == Workspace::Theme;
|
||||
let dock: &mut Dock<_> = if in_theme { theme_dock } else { dock };
|
||||
let front = |panel: &PanelId| dock.layout.panel_state(panel) == PanelState::Front;
|
||||
let dock: &mut Arc<Dock<_>> = if in_theme { theme_dock } else { dock };
|
||||
let front = |panel: &PanelId| dock.layout().panel_state(panel) == PanelState::Front;
|
||||
let inspect = Inspect {
|
||||
on: !in_theme && variants.is_none() && front(&PanelId::Inspect),
|
||||
front: [Some(PanelId::Overview), selected].into_iter().flatten().filter(|panel| front(panel)).collect(),
|
||||
@@ -134,10 +135,10 @@ fn body(ui: &mut Ui, _: &mut BodyCx<'_>, viewer: &mut Viewer) {
|
||||
};
|
||||
// Component tabs are documents: they close from their ×.
|
||||
let config = DockConfig::default().tab_close_buttons(true);
|
||||
DockArea::new(if in_theme { "Theme dock" } else { "Components dock" }, Bind::bound(&mut *dock), &mut content, config).show(ui);
|
||||
DockArea::new(if in_theme { "Theme dock" } else { "Components dock" }, Bind::bound(&mut *dock), specs, &mut content, config).show(ui);
|
||||
let GalleryDock { opened, variants_out, .. } = content;
|
||||
for type_name in opened {
|
||||
let _ = dock.set_visible(PanelId::component(type_name), true, Some(PanelId::Overview), false, |panel| panel.permissions());
|
||||
let _ = Arc::make_mut(dock).set_visible(PanelId::component(type_name), true, Some(PanelId::Overview), false, |panel| panel.permissions());
|
||||
}
|
||||
for event in variants_out {
|
||||
if let VariantsEvent::Use(look) = event {
|
||||
@@ -154,7 +155,10 @@ fn body(ui: &mut Ui, _: &mut BodyCx<'_>, viewer: &mut Viewer) {
|
||||
*variants = None;
|
||||
}
|
||||
// A closed component tab does not come back from the layout's record of closed panels.
|
||||
dock.hidden.retain(|(panel, _)| !matches!(panel, PanelId::Component(_)));
|
||||
let component = |panel: &PanelId| matches!(panel, PanelId::Component(_));
|
||||
if dock.hidden().iter().any(|(panel, _)| component(panel)) {
|
||||
Arc::make_mut(dock).forget_hidden(component);
|
||||
}
|
||||
}
|
||||
|
||||
impl ShellApp for Gallery {
|
||||
|
||||
@@ -14,7 +14,7 @@ use craft_ui::canvas::{PickStep, ViewCommands};
|
||||
use craft_ui::contract::{Bind, BodyCx, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogResult, PromptChoice, StandardPrompt};
|
||||
use craft_ui::display::{Divider, Text};
|
||||
use craft_ui::docking::{DockConfig, DockEvent, DockPanels as _};
|
||||
use craft_ui::docking::{DockConfig, DockEvent, PanelSpecs as _};
|
||||
use craft_ui::menu::{Menu, MenuBar, MenuItem, MenuTitle};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
@@ -25,6 +25,7 @@ use craft_ui::runtime::env::{Env, Label, WindowKey};
|
||||
use craft_ui::shell::{AppShell, AppShellOutput, CaptionFamily, Captions, Frame, ScreenMode, ShellDialogsCx as _, Title, TitleBar};
|
||||
use craft_window::Layout;
|
||||
use egui::{Rect, Ui};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The parameters of Gaussian Blur.
|
||||
const BLUR: &str = r#"{"radius":0.1..1000=1}"#;
|
||||
@@ -94,13 +95,19 @@ impl<'a> EditorMock<'a> {
|
||||
/// The dock, then the commands and dialog answers of this pass.
|
||||
fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) {
|
||||
let mut tools = cx.keep::<Tools>().clone();
|
||||
let ctx = ui.ctx().clone();
|
||||
let (events, picked) = {
|
||||
let mut panels =
|
||||
Panels { document: &mut state.document, tool: state.tool, tools: &mut tools, last_used: &mut state.last_used, picked: None, ctx: &ctx };
|
||||
let mut panels = Panels {
|
||||
document: &mut state.document,
|
||||
tool: state.tool,
|
||||
tools: &mut tools,
|
||||
slots: &state.slots,
|
||||
last_used: &mut state.last_used,
|
||||
picked: None,
|
||||
};
|
||||
// The mock app is a preview inside the gallery's page: its floats stay in it.
|
||||
let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &mut panels, DockConfig::default().native_windows(false))
|
||||
.flyout(Bind::bound(&mut state.flyout));
|
||||
let mut area =
|
||||
DockArea::new("Dock", Bind::bound(&mut state.workspace), &state.specs, &mut panels, DockConfig::default().native_windows(false))
|
||||
.flyout(Bind::bound(&mut state.flyout));
|
||||
if let Some(panel) = state.maximized {
|
||||
area = area.maximized(panel);
|
||||
}
|
||||
@@ -138,20 +145,13 @@ fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) {
|
||||
for command in asked {
|
||||
if let Some(panel) = command.panel() {
|
||||
// A panel in a column collapsed to icons shows in its flyout: the command opens or closes that.
|
||||
if state.workspace.layout.opens_in_flyout(&panel) {
|
||||
if state.workspace.layout().opens_in_flyout(&panel) {
|
||||
state.flyout = if state.flyout == Some(panel) { None } else { Some(panel) };
|
||||
continue;
|
||||
}
|
||||
let shown = state.workspace.layout.panel_state(&panel) != PanelState::Hidden;
|
||||
let panels = Panels {
|
||||
document: &mut state.document,
|
||||
tool: state.tool,
|
||||
tools: &mut tools,
|
||||
last_used: &mut state.last_used,
|
||||
picked: None,
|
||||
ctx: &ctx,
|
||||
};
|
||||
let _ = state.workspace.set_visible(panel, !shown, None, false, |panel| panels.permissions(panel));
|
||||
let shown = state.workspace.layout().panel_state(&panel) != PanelState::Hidden;
|
||||
let specs = &state.specs;
|
||||
let _ = Arc::make_mut(&mut state.workspace).set_visible(panel, !shown, None, false, |panel| specs.permissions(panel));
|
||||
continue;
|
||||
}
|
||||
match command {
|
||||
@@ -266,7 +266,7 @@ fn title_bar(ui: &mut Ui, state: &MockState) {
|
||||
}),
|
||||
MenuTitle::new("&Window", |ui| {
|
||||
for panel in Panel::ALL {
|
||||
let layout = &state.workspace.layout;
|
||||
let layout = state.workspace.layout();
|
||||
let shown = if layout.opens_in_flyout(&panel) {
|
||||
state.flyout == Some(panel)
|
||||
} else {
|
||||
|
||||
@@ -12,6 +12,9 @@ use craft_ui::contract::{CommandSet, Tracked};
|
||||
use craft_ui::rails::{LastUsed, RailTool, SlotId, ToolSlot};
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use egui::{Color32, Rect};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::panels::MockSpecs;
|
||||
|
||||
/// The width of the dock column at the end edge.
|
||||
const SIDE_WIDTH: f32 = 220.0;
|
||||
@@ -30,7 +33,7 @@ const TOOLS_DOCK_WIDTH: f32 = 120.0;
|
||||
|
||||
/// The tools of the rail. Each is a command of the `tools` group; a tool alone in its slot carries its letter, and the
|
||||
/// letter of a slot with several is the pick command of [`ToolKey`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet, craft_ui::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[command(prefix = "mockTool")]
|
||||
#[non_exhaustive]
|
||||
pub enum Tool {
|
||||
@@ -403,13 +406,17 @@ impl Document {
|
||||
#[non_exhaustive]
|
||||
pub struct MockState {
|
||||
/// The dock's panels and where they sit.
|
||||
pub workspace: Workspace<Panel>,
|
||||
pub workspace: Arc<Workspace<Panel>>,
|
||||
/// The dock's panel specs.
|
||||
pub specs: Tracked<MockSpecs>,
|
||||
/// The open document.
|
||||
pub document: Document,
|
||||
/// The current tool.
|
||||
pub tool: Tool,
|
||||
/// The tool each rail slot showed last.
|
||||
pub last_used: LastUsed<Tool>,
|
||||
pub last_used: Tracked<LastUsed<Tool>>,
|
||||
/// The rail's slots.
|
||||
pub slots: Tracked<Vec<ToolSlot<Tool>>>,
|
||||
/// The status bar's item.
|
||||
pub status_item: StatusItem,
|
||||
/// The status bar's message: the newest thing the mock had to say.
|
||||
@@ -433,10 +440,12 @@ impl Default for MockState {
|
||||
Node::split(Axis::X, SplitSize::Ratio(CANVAS_SHARE), Node::tabs(vec![Panel::Canvas], 0), Node::dock(DockEdge::End, vec![side, icons]));
|
||||
let root = Node::split(Axis::X, SplitSize::FixedFirst(TOOLS_DOCK_WIDTH), Node::dock(DockEdge::Start, vec![tools]), canvas);
|
||||
MockState {
|
||||
workspace: Workspace::new(Layout::new(Some(root), Vec::new())),
|
||||
workspace: Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))),
|
||||
specs: Tracked::new(MockSpecs),
|
||||
document: Document::default(),
|
||||
tool: Tool::Move,
|
||||
last_used: LastUsed::default(),
|
||||
last_used: Tracked::new(LastUsed::default()),
|
||||
slots: Tracked::new(Tool::slots()),
|
||||
status_item: StatusItem::DocumentDimensions,
|
||||
status: None,
|
||||
colors: ColorPair::default(),
|
||||
|
||||
@@ -13,16 +13,16 @@ use craft_ui::canvas::{
|
||||
tool_pass,
|
||||
};
|
||||
use craft_ui::canvas_controls::{Guides, Marquee};
|
||||
use craft_ui::contract::SizeLimits;
|
||||
use craft_ui::contract::{
|
||||
Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, MemoProps, MemoView, Props as _, Remember as _, SelectMode, Show as _,
|
||||
ShowCollection as _, ShowContainer as _, SweepApply, SweepStep, ToggleColumn, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::docking::{DockPanels, GroupAt, PanelSpec};
|
||||
use craft_ui::contract::{SizeLimits, Tracked};
|
||||
use craft_ui::docking::{DockGrid, DockPanels, GroupAt, PanelSpec, PanelSpecs};
|
||||
use craft_ui::list::{ListRow, ToggleCell};
|
||||
use craft_ui::patterns::canvas::NavigatorPanel;
|
||||
use craft_ui::primitives::textures::Revision;
|
||||
use craft_ui::rails::{LastUsed, ToolRail};
|
||||
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot};
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use craft_ui::shell::CanvasPanel;
|
||||
use craft_ui::table::Table;
|
||||
@@ -45,20 +45,23 @@ pub(super) struct Panels<'a> {
|
||||
pub(super) tool: Tool,
|
||||
pub(super) tools: &'a mut Tools,
|
||||
/// The tool each toolbar slot showed last; the toolbar writes it.
|
||||
pub(super) last_used: &'a mut LastUsed<Tool>,
|
||||
pub(super) last_used: &'a mut Tracked<LastUsed<Tool>>,
|
||||
/// The toolbar's slots.
|
||||
pub(super) slots: &'a Tracked<Vec<ToolSlot<Tool>>>,
|
||||
/// The tool the toolbar picked in this pass.
|
||||
pub(super) picked: Option<Tool>,
|
||||
/// The context the toolbar's grid is measured in.
|
||||
pub(super) ctx: &'a egui::Context,
|
||||
}
|
||||
|
||||
/// The dock's panel specs: fixed for the mock's four panels.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::PlainData)]
|
||||
pub struct MockSpecs;
|
||||
|
||||
impl Panels<'_> {
|
||||
/// The toolbar's rail in the rect the dock gives it, or its height at a width: as many tool columns as the width
|
||||
/// holds. The rail's own padding surrounds the buttons, so no group padding applies.
|
||||
fn toolbar(&mut self, ui: &mut Ui, at: GroupAt) -> f32 {
|
||||
let slots = Tool::slots();
|
||||
let (current, last_used) = (self.tool, self.last_used.clone());
|
||||
let rail = ToolRail::new("Tools", &slots, ¤t, &last_used);
|
||||
let current = self.tool;
|
||||
let rail = ToolRail::new("Tools", self.slots, ¤t, self.last_used);
|
||||
match at {
|
||||
GroupAt::Measure(width) => rail.measure_rail(ui, width, |_, _| {}).y,
|
||||
GroupAt::Show(rect) => {
|
||||
@@ -67,7 +70,7 @@ impl Panels<'_> {
|
||||
self.picked = output.select;
|
||||
}
|
||||
if let Some(next) = output.last_used {
|
||||
*self.last_used = next;
|
||||
**self.last_used = next;
|
||||
}
|
||||
rect.height()
|
||||
}
|
||||
@@ -92,13 +95,13 @@ fn name(panel: Panel) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
impl DockPanels<Panel> for Panels<'_> {
|
||||
impl PanelSpecs<Panel> for MockSpecs {
|
||||
fn spec(&self, panel: &Panel) -> PanelSpec {
|
||||
let spec = PanelSpec::new(name(*panel)).limits(SizeLimits::default());
|
||||
match panel {
|
||||
Panel::Canvas => spec.canvas(),
|
||||
// The toolbar's column is whole tool columns wide.
|
||||
Panel::Tools => spec.grid(ToolRail::<Tool>::dock_grid(self.ctx, Tool::slots().len())),
|
||||
Panel::Tools => spec.grid(DockGrid::rail(Tool::slots().len())),
|
||||
_ => spec,
|
||||
}
|
||||
}
|
||||
@@ -111,7 +114,9 @@ impl DockPanels<Panel> for Panels<'_> {
|
||||
_ => Permissions::ALL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DockPanels<Panel> for Panels<'_> {
|
||||
fn body(&mut self, panel: &Panel, ui: &mut Ui, cx: &mut BodyCx<'_>) {
|
||||
match panel {
|
||||
Panel::Navigator => {
|
||||
|
||||
@@ -167,7 +167,7 @@ pub fn reconciled(mut saved: Dock<PanelId>, workspace: Workspace, catalog: &Cata
|
||||
}
|
||||
};
|
||||
saved.reconcile(registered, PanelId::permissions, &default_for(workspace));
|
||||
saved.hidden.retain(|(panel, _)| registered(panel));
|
||||
saved.forget_hidden(|panel| !registered(panel));
|
||||
saved
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ pub fn load(text: &str, workspace: Workspace, catalog: &Catalog) -> Dock<PanelId
|
||||
/// The component tabs `layout` holds, in layout order.
|
||||
pub fn open_tabs(layout: &Dock<PanelId>) -> Vec<TabName> {
|
||||
layout
|
||||
.layout
|
||||
.layout()
|
||||
.panels()
|
||||
.into_iter()
|
||||
.filter_map(|panel| match panel {
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::layout::{self, PanelId};
|
||||
use super::picks::Cells;
|
||||
use super::settings::GallerySettings;
|
||||
use super::tree::{self, TreeKey};
|
||||
use crate::chrome::GallerySpecs;
|
||||
use crate::mock::MockState;
|
||||
use craft_behavior::Selection;
|
||||
use craft_behavior::dock::Workspace as Dock;
|
||||
@@ -90,9 +91,11 @@ pub struct Viewer {
|
||||
/// What the theme panels share.
|
||||
pub themes: ThemeWorkspace,
|
||||
/// The components workspace's dock layout.
|
||||
pub dock: Dock<PanelId>,
|
||||
pub dock: Arc<Dock<PanelId>>,
|
||||
/// The theme workspace's dock layout.
|
||||
pub theme_dock: Dock<PanelId>,
|
||||
pub theme_dock: Arc<Dock<PanelId>>,
|
||||
/// The panel specs both docks show.
|
||||
pub specs: Tracked<GallerySpecs>,
|
||||
/// The mock application the theme workspace's App preview shows.
|
||||
pub mock: MockState,
|
||||
/// The drawings the inspector shows over the selected card's stories.
|
||||
@@ -125,8 +128,9 @@ impl Viewer {
|
||||
more_open: false,
|
||||
browser,
|
||||
themes: ThemeWorkspace::new(),
|
||||
dock: layout::default_components(),
|
||||
theme_dock: layout::default_theme(),
|
||||
dock: Arc::new(layout::default_components()),
|
||||
theme_dock: Arc::new(layout::default_theme()),
|
||||
specs: Tracked::new(GallerySpecs),
|
||||
mock: MockState::default(),
|
||||
inspect_layers: Tracked::new(InspectLayers::default()),
|
||||
sizes_synced: None,
|
||||
@@ -154,8 +158,8 @@ impl Viewer {
|
||||
*browser.tree_seen = Some(browser.selected_type());
|
||||
browser.level.edit(|level| level.clone_from(&settings.level));
|
||||
*browser.story_of = settings.story_of(&browser.catalog);
|
||||
self.dock = layout::load(&settings.dock, Workspace::Components, &browser.catalog);
|
||||
self.theme_dock = layout::load(&settings.theme_dock, Workspace::Theme, &browser.catalog);
|
||||
Arc::make_mut(&mut self.dock).replace(layout::load(&settings.dock, Workspace::Components, &browser.catalog));
|
||||
Arc::make_mut(&mut self.theme_dock).replace(layout::load(&settings.theme_dock, Workspace::Theme, &browser.catalog));
|
||||
}
|
||||
|
||||
/// Makes the root's app sizes the theme workspace's app layer, when the layer was edited since the last sync.
|
||||
@@ -181,26 +185,27 @@ impl Viewer {
|
||||
/// The dock layout of the shown workspace.
|
||||
pub fn dock_mut(&mut self) -> &mut Dock<PanelId> {
|
||||
match self.workspace {
|
||||
Workspace::Components => &mut self.dock,
|
||||
Workspace::Theme => &mut self.theme_dock,
|
||||
Workspace::Components => Arc::make_mut(&mut self.dock),
|
||||
Workspace::Theme => Arc::make_mut(&mut self.theme_dock),
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the tab of the component registered as `type_name` beside the Overview and shows it.
|
||||
pub fn open_component(&mut self, type_name: &str) {
|
||||
let _ = self.dock.set_visible(PanelId::component(type_name), true, Some(PanelId::Overview), false, |panel| panel.permissions());
|
||||
let _ = Arc::make_mut(&mut self.dock)
|
||||
.set_visible(PanelId::component(type_name), true, Some(PanelId::Overview), false, |panel| panel.permissions());
|
||||
}
|
||||
|
||||
/// Puts the shown workspace's panels back at their default places. The open component tabs are documents and stay.
|
||||
pub fn reset_layout(&mut self) {
|
||||
let workspace = self.workspace;
|
||||
let tabs = layout::open_tabs(&self.dock);
|
||||
*self.dock_mut() = layout::default_for(workspace);
|
||||
self.dock_mut().replace(layout::default_for(workspace));
|
||||
if workspace == Workspace::Components {
|
||||
for tab in tabs {
|
||||
self.open_component(&tab);
|
||||
}
|
||||
let _ = self.dock.set_visible(PanelId::Overview, true, None, false, |panel| panel.permissions());
|
||||
let _ = Arc::make_mut(&mut self.dock).set_visible(PanelId::Overview, true, None, false, |panel| panel.permissions());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ fn each_default_layout_is_valid_and_holds_exactly_its_workspaces_panels() {
|
||||
let layout = default_for(workspace);
|
||||
assert_eq!(layout.validate(), Ok(()));
|
||||
for panel in COMPONENTS.iter().chain(&THEME) {
|
||||
assert_eq!(layout.layout.contains(panel), panels.contains(panel), "{workspace:?} {panel:?}");
|
||||
assert_eq!(layout.layout().contains(panel), panels.contains(panel), "{workspace:?} {panel:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ fn the_overview_is_pinned_and_a_component_tab_is_not() {
|
||||
let tab = PanelId::component("craft_ui::buttons::link::Link");
|
||||
let mut dock = default_for(Workspace::Components);
|
||||
let _ = dock.set_visible(tab.clone(), true, Some(PanelId::Overview), false, |panel| panel.permissions());
|
||||
assert!(dock.layout.contains(&tab), "the component tab opens beside the Overview");
|
||||
assert!(dock.layout().contains(&tab), "the component tab opens beside the Overview");
|
||||
let refused = [
|
||||
Action::float(PanelId::Overview, rect),
|
||||
Action::close(PanelId::Overview),
|
||||
|
||||
@@ -32,7 +32,7 @@ use bar::panel_names;
|
||||
|
||||
pub(super) use bar::{BarRecord, CHEVRON, ColumnGrip, bar_band, bar_name, bar_slots, describe_chevron, paint_chevron, show_bar};
|
||||
use sizing::group_sizes;
|
||||
pub use sizing::{GroupSize, column_cells, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds};
|
||||
pub use sizing::{GroupSize, column_cells, fit_widths, group_heights, scale_widths, stacked, width_bounds};
|
||||
|
||||
const DIVIDER: PartKey = PartKey::new("divider");
|
||||
const EDGE: PartKey = PartKey::new("edge");
|
||||
@@ -68,7 +68,7 @@ pub enum ColumnArrow {
|
||||
/// Collapses the column to icons, or expands it.
|
||||
#[default]
|
||||
Collapse,
|
||||
/// Switches a stepped column ([`stepped`]) between one and two steps. Holds the steps it shows.
|
||||
/// Switches a stepped column ([`DockSizes::stepped`](super::DockSizes::stepped)) between one and two steps. Holds the steps it shows.
|
||||
Steps(u16),
|
||||
/// Nothing: the column neither collapses nor has steps. It shows no double arrow, and its menu offers no
|
||||
/// collapse.
|
||||
@@ -78,11 +78,11 @@ pub enum ColumnArrow {
|
||||
impl ColumnArrow {
|
||||
/// The arrow of `column`: an expanded column whose panels do not collapse (`collapses` false) switches steps
|
||||
/// when it is stepped and has none otherwise; any other column collapses or expands.
|
||||
pub fn of<P>(column: &Column<P>, spec: &dyn Fn(&P) -> PanelSpec, collapses: bool) -> Self {
|
||||
pub fn of<P>(column: &Column<P>, sizes: &DockSizes, spec: &dyn Fn(&P) -> PanelSpec, collapses: bool) -> Self {
|
||||
if collapses || column.iconic {
|
||||
return ColumnArrow::Collapse;
|
||||
}
|
||||
stepped(column, spec).map_or(ColumnArrow::Fixed, |(_, steps)| ColumnArrow::Steps(steps))
|
||||
sizes.stepped(column, spec).map_or(ColumnArrow::Fixed, |(_, steps)| ColumnArrow::Steps(steps))
|
||||
}
|
||||
|
||||
/// The steps a click gives a stepped column: two from one, else one. `None` for any other arrow.
|
||||
|
||||
@@ -55,12 +55,15 @@ pub fn column_cells<P>(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The grid and steps of a stepped column: its [`Column::steps`] and the [`DockGrid`] of its first panel that
|
||||
/// declares a valid one. `None` for a column without steps or whose panels declare none, which sizes as any other.
|
||||
pub fn stepped<P>(column: &Column<P>, spec: &dyn Fn(&P) -> PanelSpec) -> Option<(DockGrid, u16)> {
|
||||
let steps = column.steps?;
|
||||
let grid = column.panels().find_map(|panel| spec(panel).grid.filter(|grid| grid.valid()))?;
|
||||
Some((grid, grid.clamp(steps)))
|
||||
impl DockSizes {
|
||||
/// The grid and steps of a stepped column: its [`Column::steps`] and the [`DockGrid`] of its first panel that
|
||||
/// declares a valid one, in these sizes (a [`DockGrid::rail`] takes their rail widths). `None` for a column without
|
||||
/// steps or whose panels declare none, which sizes as any other. Every dock reads a panel's grid through here.
|
||||
pub fn stepped<P>(&self, column: &Column<P>, spec: &dyn Fn(&P) -> PanelSpec) -> Option<(DockGrid, u16)> {
|
||||
let steps = column.steps?;
|
||||
let grid = column.panels().find_map(|panel| spec(panel).grid.map(|grid| grid.resolved(self)).filter(|grid| grid.valid()))?;
|
||||
Some((grid, grid.clamp(steps)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Column widths that add up to `total` as far as their bounds allow. Each entry is `(width, (lo, hi))`. The
|
||||
|
||||
@@ -409,12 +409,12 @@ impl<P: Clone + Eq + Hash + Send + 'static> DropTarget<GroupDrag<P>> for DockDro
|
||||
}
|
||||
}
|
||||
|
||||
/// The arrangement a dock drag started on: the dock area and the revision of the workspace it showed.
|
||||
/// The arrangement a dock drag started on: the dock area and the generation of the workspace it showed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::contract::MemoProps)]
|
||||
#[doc(hidden)]
|
||||
pub struct Arrangement {
|
||||
pub dock: Id,
|
||||
pub revision: u64,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
/// The env value a dock area puts into its body: the arrangement it shows. `None` outside a dock area.
|
||||
@@ -463,9 +463,9 @@ where
|
||||
cx.start_drag(GroupDrag { unit, active, source: None, strip: Some(strip), started }, DragPreview::Named(label));
|
||||
}
|
||||
|
||||
/// Ends a running tab or group drag that started on `shown`'s dock under another revision: another arrangement
|
||||
/// Ends a running tab or group drag that started on `shown`'s dock under another generation: another arrangement
|
||||
/// replaced the workspace, and the panel or group the drag names may be gone or elsewhere. The dock's own edits keep
|
||||
/// the revision, and so the drag.
|
||||
/// the generation, and so the drag.
|
||||
#[doc(hidden)]
|
||||
pub fn end_replaced_drags<P: Send + Sync + 'static>(ctx: &Context, shown: Arrangement) {
|
||||
let replaced = |started: Option<Arrangement>| started.is_some_and(|started| started.dock == shown.dock && started != shown);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! `DockEvent`, `FloatSpace` and `HidePanels`: what a dock reports to the host and the host tells a dock.
|
||||
|
||||
use super::{DockCommands, DockSizes, DragUnit};
|
||||
use super::{DockCommands, DockSizes, DragUnit, PanelKey};
|
||||
use crate::contract::{MemoProps, Tracked};
|
||||
use egui::{Rect, Vec2};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// A request for host state outside the layout, or a report of where something ended up.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -42,24 +44,20 @@ pub enum DockEvent<P> {
|
||||
/// Which panels the host hides. Protected panels always stay. While the shell hides the panels and keeps the tools
|
||||
/// (Shift+Tab), the panels `Except` names stay and every other panel hides; while it hides the dock (Tab), every panel
|
||||
/// hides.
|
||||
///
|
||||
/// The set is a `Tracked` value, so a dock keys what it shows by the set's revision and keeps the pruned layout until
|
||||
/// the set, the workspace or the shell's visibility changes.
|
||||
#[derive(Clone, Copy, MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum HidePanels<'a, P> {
|
||||
pub enum HidePanels<'a> {
|
||||
/// Hides none.
|
||||
None,
|
||||
/// Hides every panel.
|
||||
All,
|
||||
/// Every panel except those for which the function returns true.
|
||||
Except(&'a dyn Fn(&P) -> bool),
|
||||
/// Every panel except those whose [`PanelKey`] the set holds.
|
||||
Except(&'a Tracked<BTreeSet<PanelKey>>),
|
||||
}
|
||||
|
||||
impl<P> Clone for HidePanels<'_, P> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> Copy for HidePanels<'_, P> {}
|
||||
|
||||
/// Where a docking command floats a panel, group or column when it gives no rect. A dock records one each pass;
|
||||
/// the host reads it to turn a command into placements.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! What the tree adds around the groups: Maximize Frame, the hidden-panel prune and the outer edge bands.
|
||||
|
||||
use super::PanelKey;
|
||||
use super::config::DockConfig;
|
||||
use super::event::HidePanels;
|
||||
use super::targets::{DockSizes, DockSpot, DockTargets};
|
||||
@@ -27,6 +28,11 @@ pub struct FrameView<'a, P: Clone> {
|
||||
}
|
||||
|
||||
impl<P: Clone> FrameView<'_, P> {
|
||||
/// The view with its layout owned, to keep it past the layout it was made from.
|
||||
pub fn into_owned(self) -> FrameView<'static, P> {
|
||||
FrameView { layout: Cow::Owned(self.layout.into_owned()), maximized: self.maximized, hidden: self.hidden, paths: self.paths }
|
||||
}
|
||||
|
||||
/// Writes the split sizes of `edited`, an edit of the view's layout, into `layout`, the layout the view was made
|
||||
/// from. Panels the view left out keep their place; only the docked tree's split sizes change: floating windows
|
||||
/// have no splits.
|
||||
@@ -64,13 +70,13 @@ fn split_sizes<P>(node: &Node<P>, paths: &HashMap<Vec<bool>, Vec<bool>>) -> Vec<
|
||||
pub fn maximize<'a, P: Clone + Eq + Hash>(
|
||||
layout: &'a Layout<P>,
|
||||
maximized: Option<&P>,
|
||||
hide: HidePanels<'_, P>,
|
||||
hide: HidePanels<'_>,
|
||||
protected: &dyn Fn(&P) -> bool,
|
||||
) -> FrameView<'a, P> {
|
||||
let hidden = |panel: &P| match hide {
|
||||
HidePanels::None => false,
|
||||
HidePanels::All => !protected(panel),
|
||||
HidePanels::Except(keep) => !protected(panel) && !keep(panel),
|
||||
HidePanels::Except(keep) => !protected(panel) && !keep.contains(&PanelKey::of(panel)),
|
||||
};
|
||||
// Only a docked panel maximizes its frame.
|
||||
let frame = maximized.and_then(|panel| match layout.place(panel)? {
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::commands::DockCommands;
|
||||
use super::drop::{self, DragUnit, start_group_drag};
|
||||
use super::targets::{DockSizes, DockSpot, DockTargets, ZoneRule};
|
||||
use super::words::DockWords;
|
||||
use super::{PanelDrag, PanelKey, PanelTitle};
|
||||
use super::{PanelDrag, PanelKey, PanelTitle, Titles};
|
||||
use crate::buttons::IconButton;
|
||||
use crate::contract::overlay::Anchor;
|
||||
use crate::contract::{
|
||||
@@ -245,7 +245,7 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> {
|
||||
#[container]
|
||||
props: ContainerProps,
|
||||
anchor: P,
|
||||
panels: &'a [PanelTitle],
|
||||
panels: Titles,
|
||||
active: PanelKey,
|
||||
/// Only the header shows; the body and its drop spots are left out.
|
||||
#[prop(flag)]
|
||||
@@ -292,10 +292,10 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> {
|
||||
impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup<'a, P> {
|
||||
/// The group named by `anchor` (one of its panels) with its `panels`, `active` showing. The group is named by the
|
||||
/// active panel's title.
|
||||
pub fn new(anchor: P, panels: &'a [PanelTitle], active: PanelKey) -> Self {
|
||||
pub fn new(anchor: P, panels: Titles, active: PanelKey) -> Self {
|
||||
let props =
|
||||
ContainerProps::new().sizing(Sizing::Fill).header(HeaderRegion::new().fill(SurfaceKind::Background)).command_scope(DockCommands::SCOPE);
|
||||
let title = panels.iter().find(|panel| panel.key == active).map(|panel| panel.title.clone()).unwrap_or_default();
|
||||
let title = panels.as_slice().iter().find(|panel| panel.key == active).map(|panel| panel.title.clone()).unwrap_or_default();
|
||||
DockGroup {
|
||||
common: Common::new(),
|
||||
props,
|
||||
@@ -445,7 +445,7 @@ impl<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static> Component for
|
||||
let Some(dock) = self.dock else { return };
|
||||
let (rect, rtl, header) = (cx.rect, cx.flow.is_rtl(), cx.style.header);
|
||||
let strip = Rect::from_min_size(rect.min, Vec2::new(rect.width(), header));
|
||||
DockTargets::<P>::register(&cx.core.ctx, dock, DockSpot::tab(self.anchor.clone(), self.panels.len()), strip);
|
||||
DockTargets::<P>::register(&cx.core.ctx, dock, DockSpot::tab(self.anchor.clone(), self.panels.as_slice().len()), strip);
|
||||
if self.minimized {
|
||||
return;
|
||||
}
|
||||
@@ -518,7 +518,7 @@ impl<P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> Container for
|
||||
}
|
||||
let row = TabRow {
|
||||
anchor: self.anchor.clone(),
|
||||
panels: self.panels,
|
||||
panels: self.panels.clone(),
|
||||
active: self.active,
|
||||
closable: self.closable,
|
||||
wheel_selects: self.wheel_selects_tabs,
|
||||
@@ -585,7 +585,8 @@ struct TabRow<'a, P> {
|
||||
/// The group's anchor panel, which names its drop spots.
|
||||
#[memo_props(hash = "a dock's panels are plain values it keys by their hash")]
|
||||
anchor: P,
|
||||
panels: &'a [PanelTitle],
|
||||
#[memo_props(hash = "its Hash is the content key taken when the titles were made")]
|
||||
panels: Titles,
|
||||
active: PanelKey,
|
||||
closable: bool,
|
||||
wheel_selects: bool,
|
||||
@@ -598,7 +599,7 @@ fn tab_row<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static>(row: &mu
|
||||
let env = crate::runtime::env::Env::of(ui);
|
||||
let name = Label::from(env.words::<DockWords>().panels.as_str().to_owned());
|
||||
let rtl = env.direction.is_rtl();
|
||||
let (panels, active, closable) = (row.panels, row.active, row.closable);
|
||||
let (panels, active, closable) = (row.panels.as_slice(), row.active, row.closable);
|
||||
let from = PanelKey::of(&row.anchor);
|
||||
let drags = crate::runtime::drag::started(ui.ctx());
|
||||
let source = keyed(panels, |panel: &PanelTitle| panel.key).with_text(|panel| Cow::Borrowed(panel.title.as_str()));
|
||||
|
||||
@@ -38,7 +38,7 @@ pub use event::{DockEvent, FloatSpace, HidePanels};
|
||||
pub use group::{DockGroup, DockGroupOutput, DockGroupStyle, GroupGrip, GroupGripOutput, GroupGripStyle, HeaderHook, MenuRows};
|
||||
|
||||
pub use floating::{FloatingGroup, FloatingGroupOutput, FloatingGroupStyle, WindowColumn};
|
||||
pub use panels::{DockPanels, request_actions};
|
||||
pub use panels::{DockPanels, PanelSpecs, SpecSource, request_actions};
|
||||
#[doc(hidden)]
|
||||
pub use panels::{close_requests, open_requests};
|
||||
pub use placed::{Placing, placed_rect, with_area_rules};
|
||||
@@ -59,7 +59,7 @@ pub(crate) mod iconic;
|
||||
|
||||
pub use dock_column::{
|
||||
ColumnArrow, ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, column_cells, fit_widths, group_heights,
|
||||
group_rects, scale_widths, stacked, stepped, width_bounds,
|
||||
group_rects, scale_widths, stacked, width_bounds,
|
||||
};
|
||||
pub use flyout::{Flyout, FlyoutOutput, FlyoutShown, FlyoutStyle, GroupAt};
|
||||
pub use iconic::{FlyoutResize, IconicColumn, IconicColumnOutput, IconicColumnStyle, IconicSizes};
|
||||
@@ -79,12 +79,13 @@ use divider::{Divider, Drag};
|
||||
use egui::{Rect, Response, Vec2};
|
||||
use std::fmt::Debug;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
use tree::{FrameRules, SplitHandle};
|
||||
|
||||
const HANDLE: PartKey = PartKey::new("handle");
|
||||
|
||||
/// The stable key of a panel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, crate::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, crate::contract::MemoProps, crate::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct PanelKey(pub u64);
|
||||
|
||||
@@ -114,6 +115,34 @@ pub struct PanelTitle {
|
||||
pub closable: bool,
|
||||
}
|
||||
|
||||
/// The tab titles of one group with their content key, taken once when they are made: a memoized view that holds them
|
||||
/// feeds that key, not the titles. A host keeps a group's titles in a derived value so the key is taken only when they
|
||||
/// are rebuilt.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Titles {
|
||||
list: Arc<Vec<PanelTitle>>,
|
||||
key: u128,
|
||||
}
|
||||
|
||||
impl Titles {
|
||||
/// The titles `list`, keyed by their content: this call walks them.
|
||||
pub fn from_content(list: Vec<PanelTitle>) -> Self {
|
||||
Titles { key: crate::contract::MemoKey::of(&list), list: Arc::new(list) }
|
||||
}
|
||||
|
||||
/// The titles in tab order.
|
||||
pub fn as_slice(&self) -> &[PanelTitle] {
|
||||
&self.list
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the content key taken when the titles were made, not the titles.
|
||||
impl Hash for Titles {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.key.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PanelTitle {
|
||||
/// A panel `key` titled `title`, not closable from its tab.
|
||||
pub fn new(key: PanelKey, title: impl Into<Label>) -> Self {
|
||||
|
||||
@@ -2,13 +2,56 @@
|
||||
|
||||
use super::flyout::GroupAt;
|
||||
use super::spec::PanelSpec;
|
||||
use crate::contract::BodyCx;
|
||||
use crate::contract::{BodyCx, PlainData, Revision, Tracked};
|
||||
use crate::menu::PanelRow;
|
||||
use crate::runtime::memory;
|
||||
use craft_behavior::dock::{Action, Permissions};
|
||||
use egui::{Context, Id, Ui};
|
||||
|
||||
/// The host's panels. A dock calls, in one pass and for each group it shows:
|
||||
/// What a dock reads of the host's panels: each panel's spec and permissions. The host keeps an implementation in a
|
||||
/// [`Tracked`] and gives the dock a reference to it; the dock reads it only when the `Tracked`'s revision or the
|
||||
/// workspace changed, and keeps what it read otherwise. A host changes a label or a limit by editing its spec model,
|
||||
/// which moves the revision. The model is plain data, so nothing it answers can change without that edit; a spec
|
||||
/// needs no style either (a tool rail's grid is [`DockGrid::rail`](super::DockGrid::rail), which the dock sizes).
|
||||
pub trait PanelSpecs<P>: PlainData {
|
||||
/// What the dock reads of `panel`.
|
||||
fn spec(&self, panel: &P) -> PanelSpec;
|
||||
|
||||
/// What may happen to `panel`: whether it moves, floats, closes and takes tabs and splits (the default allows
|
||||
/// everything). A canvas is `Permissions::PROTECTED`. A locked workspace narrows these itself.
|
||||
fn permissions(&self, _panel: &P) -> Permissions {
|
||||
Permissions::ALL
|
||||
}
|
||||
}
|
||||
|
||||
/// A host's [`PanelSpecs`] in its [`Tracked`], as a dock holds it: the revision keys what the dock derives from the
|
||||
/// specs. Implemented for `Tracked<S>` of every `S: PanelSpecs<P>`.
|
||||
pub trait SpecSource<P> {
|
||||
/// The revision of the spec model.
|
||||
fn revision(&self) -> Revision;
|
||||
|
||||
/// What the dock reads of `panel` ([`PanelSpecs::spec`]).
|
||||
fn spec(&self, panel: &P) -> PanelSpec;
|
||||
|
||||
/// What may happen to `panel` ([`PanelSpecs::permissions`]).
|
||||
fn permissions(&self, panel: &P) -> Permissions;
|
||||
}
|
||||
|
||||
impl<P, S: PanelSpecs<P>> SpecSource<P> for Tracked<S> {
|
||||
fn revision(&self) -> Revision {
|
||||
Tracked::revision(self)
|
||||
}
|
||||
|
||||
fn spec(&self, panel: &P) -> PanelSpec {
|
||||
PanelSpecs::spec(&**self, panel)
|
||||
}
|
||||
|
||||
fn permissions(&self, panel: &P) -> Permissions {
|
||||
PanelSpecs::permissions(&**self, panel)
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's panel views. A dock calls, in one pass and for each group it shows:
|
||||
///
|
||||
/// 1. `group_view`, with the group's panels and where the group goes. When it returns a height the host took the group
|
||||
/// itself: the dock shows no tab strip and no panel body for that group, and calls neither `group_header` nor `body`
|
||||
@@ -19,20 +62,10 @@ use egui::{Context, Id, Ui};
|
||||
/// Each of these runs every pass the group shows. A host memoizes inside them: a body or view shown through a
|
||||
/// [`MemoView`](crate::contract::MemoView) runs only when its props changed or input reached it, and otherwise repaints
|
||||
/// its last run. The dock's own chrome (each group's tab row, each column's bar) is memoized on what it shows: the
|
||||
/// panels' specs, the arrangement and the look.
|
||||
/// panels' specs ([`PanelSpecs`]), the arrangement and the look.
|
||||
///
|
||||
/// A panel's `spec` and `permissions` are read every pass, so a host may change a label or a limit between passes.
|
||||
/// `panel_rows` is read while the group's menu is open. The dock's actions name a group by one of its panels.
|
||||
pub trait DockPanels<P> {
|
||||
/// What the dock reads of `panel`.
|
||||
fn spec(&self, panel: &P) -> PanelSpec;
|
||||
|
||||
/// What may happen to `panel`: whether it moves, floats, closes and takes tabs and splits (the default allows
|
||||
/// everything). A canvas is `Permissions::PROTECTED`. A locked workspace narrows these itself.
|
||||
fn permissions(&self, _panel: &P) -> Permissions {
|
||||
Permissions::ALL
|
||||
}
|
||||
|
||||
/// Shows `panel`'s body in `ui`: the group's body, inset from its edges by the panel padding. The group is the
|
||||
/// body's panel and its tab the body's title, so the body shows no framework `Panel` or padding of its own; content
|
||||
/// taller than the group scrolls in the body's own scrolling container. A document panel's body
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use super::frame::maximize;
|
||||
use super::tree::{self, FrameRules};
|
||||
use super::{ColumnBar, DockSizes, HidePanels, PanelSpec, column_cells, group_rects, stepped};
|
||||
use super::{ColumnBar, DockSizes, HidePanels, PanelSpec, column_cells, group_rects};
|
||||
use craft_behavior::Flow;
|
||||
use craft_behavior::dock::{Column, Layout, Node};
|
||||
use egui::Rect;
|
||||
@@ -20,7 +20,7 @@ pub struct Placing<'a, P> {
|
||||
/// The panels that always show, such as a canvas.
|
||||
pub protected: &'a dyn Fn(&P) -> bool,
|
||||
/// The panels the area hides, as the shell's visibility leaves them.
|
||||
pub hide: HidePanels<'a, P>,
|
||||
pub hide: HidePanels<'a>,
|
||||
/// The panel whose frame the area shows maximized.
|
||||
pub maximized: Option<&'a P>,
|
||||
/// The floating window whose column the dock lays out, by its id; `None` for a dock area's docked tree.
|
||||
@@ -35,7 +35,7 @@ impl<'a, P> Placing<'a, P> {
|
||||
|
||||
/// The area hides `hide` and shows the frame of `maximized` alone.
|
||||
#[must_use]
|
||||
pub fn shown(mut self, hide: HidePanels<'a, P>, maximized: Option<&'a P>) -> Self {
|
||||
pub fn shown(mut self, hide: HidePanels<'a>, maximized: Option<&'a P>) -> Self {
|
||||
self.hide = hide;
|
||||
self.maximized = maximized;
|
||||
self
|
||||
@@ -109,7 +109,7 @@ fn column_rects<P: PartialEq>(
|
||||
if !column.panels().any(moves) {
|
||||
return Some(());
|
||||
}
|
||||
if column.iconic || stepped(column, placing.spec).is_some() {
|
||||
if column.iconic || placing.sizes.stepped(column, placing.spec).is_some() {
|
||||
return None;
|
||||
}
|
||||
if column.panels().all(moves) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! `PanelSpec`: what the dock asks of a panel before it shows its body.
|
||||
|
||||
use super::DockSizes;
|
||||
use crate::contract::SizeLimits;
|
||||
use crate::primitives::IconSpec;
|
||||
use crate::runtime::env::Label;
|
||||
@@ -52,26 +53,61 @@ impl DockHeights {
|
||||
/// whole number of content columns wide, its steps ([`Column::steps`](craft_behavior::dock::Column::steps)), and as
|
||||
/// tall as the content measures at that width: docked from the top of the dock, floating under the title row. A drag
|
||||
/// of the column's edge sets whole steps; the content lays out as many columns as fit the width it gets.
|
||||
///
|
||||
/// A tool rail's grid is [`DockGrid::rail`]: the dock computes its widths from its own style
|
||||
/// ([`resolved`](Self::resolved)), so the grid follows the theme and density without the panel's spec reading them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct DockGrid {
|
||||
/// The content's width at one column: a cell and the content's own padding on both sides.
|
||||
pub first: f32,
|
||||
/// The width each further column adds: a cell and the gap before it.
|
||||
pub step: f32,
|
||||
widths: GridWidths,
|
||||
/// The most columns the content fills, its cell count: more steps show it no wider.
|
||||
pub most: u16,
|
||||
}
|
||||
|
||||
/// The widths of a [`DockGrid`]'s columns.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum GridWidths {
|
||||
/// `first`: the content's width at one column, a cell and the content's own padding on both sides; `step`: the
|
||||
/// width each further column adds, a cell and the gap before it.
|
||||
Content { first: f32, step: f32 },
|
||||
/// A tool rail's cells, sized by the dock's style.
|
||||
Rail,
|
||||
}
|
||||
|
||||
impl DockGrid {
|
||||
/// A grid `first` wide at one column, `step` wider for each further column, up to `most` columns.
|
||||
pub const fn new(first: f32, step: f32, most: u16) -> Self {
|
||||
DockGrid { first, step, most }
|
||||
DockGrid { widths: GridWidths::Content { first, step }, most }
|
||||
}
|
||||
|
||||
/// Whether the widths are finite and positive and the grid has a column.
|
||||
/// The grid of a tool rail of `cells` cells: a rail button and the control padding on both sides at one column,
|
||||
/// a button and the tight gap for each further column, in the style the dock shows it in.
|
||||
pub fn rail(cells: usize) -> Self {
|
||||
DockGrid { widths: GridWidths::Rail, most: u16::try_from(cells).unwrap_or(u16::MAX).max(1) }
|
||||
}
|
||||
|
||||
/// The grid with its widths in points: a [`rail`](Self::rail) grid takes the rail widths of `sizes`.
|
||||
pub fn resolved(self, sizes: &DockSizes) -> Self {
|
||||
match self.widths {
|
||||
GridWidths::Content { .. } => self,
|
||||
GridWidths::Rail => DockGrid::new(sizes.rail_first, sizes.rail_step, self.most),
|
||||
}
|
||||
}
|
||||
|
||||
/// The content's width at one column and the width each further column adds; zero for a rail grid not yet
|
||||
/// [`resolved`](Self::resolved).
|
||||
fn first_step(self) -> (f32, f32) {
|
||||
match self.widths {
|
||||
GridWidths::Content { first, step } => (first, step),
|
||||
GridWidths::Rail => (0.0, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the widths are finite and positive and the grid has a column. A rail grid not yet
|
||||
/// [`resolved`](Self::resolved) is not.
|
||||
pub fn valid(self) -> bool {
|
||||
self.first.is_finite() && self.first > 0.0 && self.step.is_finite() && self.step > 0.0 && self.most > 0
|
||||
let (first, step) = self.first_step();
|
||||
first.is_finite() && first > 0.0 && step.is_finite() && step > 0.0 && self.most > 0
|
||||
}
|
||||
|
||||
/// `steps` kept between one column and [`most`](Self::most).
|
||||
@@ -81,7 +117,8 @@ impl DockGrid {
|
||||
|
||||
/// The content's width at `steps` columns, kept within the grid's columns.
|
||||
pub fn width(self, steps: u16) -> f32 {
|
||||
self.first + f32::from(self.clamp(steps) - 1) * self.step
|
||||
let (first, step) = self.first_step();
|
||||
first + f32::from(self.clamp(steps) - 1) * step
|
||||
}
|
||||
|
||||
/// The most columns whose width fits `width`, at least one.
|
||||
|
||||
@@ -4,9 +4,11 @@ use super::SplitFramesCx as _;
|
||||
use super::group::MENU;
|
||||
use super::stack::{StackSection, StackSections};
|
||||
use super::tree::FrameRules;
|
||||
use super::{DockCommands, DockGroup, DockPanels, DragUnit, GroupGrip, HANDLE, PanelKey, PanelSpec, PanelTitle, SplitArea, Splitter, WindowMenuRows};
|
||||
use super::{
|
||||
DockCommands, DockGroup, DragUnit, GroupGrip, HANDLE, PanelKey, PanelSpec, PanelSpecs, PanelTitle, SplitArea, Splitter, Titles, WindowMenuRows,
|
||||
};
|
||||
use crate::contract::SizeLimits;
|
||||
use crate::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _, Validity};
|
||||
use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _, Tracked, Validity};
|
||||
use crate::menu::{Menu, PanelRow};
|
||||
use crate::runtime::commands::CommandRef;
|
||||
use crate::runtime::env::Message;
|
||||
@@ -45,7 +47,7 @@ fn dock(ui: &mut Ui, bind: Bind<'_, Layout<usize>>, shown: &Layout<usize>) -> St
|
||||
let Some(Node::Tabs { panels, .. }) = shown.place(&anchor).and_then(|place| shown.node_of(&place)) else { continue };
|
||||
let panels = titles(panels);
|
||||
let active = panels.first().map_or(PanelKey::new(0), |panel| panel.key);
|
||||
DockGroup::new(anchor, &panels, active).show_at(ui, rect, |_, _| ());
|
||||
DockGroup::new(anchor, Titles::from_content(panels.clone()), active).show_at(ui, rect, |_, _| ());
|
||||
}
|
||||
});
|
||||
area.output.edit.into()
|
||||
@@ -84,14 +86,14 @@ fn a_dock_of_one_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
#[story(DockGroup<'static, usize>, covers = [Default])]
|
||||
fn two_panels(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let panels = titles(&[LAYERS, CHANNELS]);
|
||||
DockGroup::new(LAYERS, &panels, panels[0].key).show(ui, |_, _| ()).output.into()
|
||||
DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).show(ui, |_, _| ()).output.into()
|
||||
}
|
||||
|
||||
/// A group in a floating window: nothing goes beside it, so a drop on its body joins it or stacks above or below.
|
||||
#[story(DockGroup<'static, usize>, covers = [Default])]
|
||||
fn a_group_in_a_window(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let panels = titles(&[LAYERS, CHANNELS]);
|
||||
DockGroup::new(LAYERS, &panels, panels[0].key).in_window().show(ui, |_, _| ()).output.into()
|
||||
DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).in_window().show(ui, |_, _| ()).output.into()
|
||||
}
|
||||
|
||||
/// A click on the panel menu button opens the group's panel menu.
|
||||
@@ -106,7 +108,7 @@ fn open_panel_menu(fixture: &mut Fixture) {
|
||||
fn panel_menu(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let panels = titles(&[LAYERS, CHANNELS]);
|
||||
let rows = [DockCommands::FloatPanel, DockCommands::FloatGroup].map(|command| PanelRow::Command(CommandRef::from(command))).to_vec();
|
||||
DockGroup::new(LAYERS, &panels, panels[0].key).menu(move || rows.clone()).show(ui, |_, _| ()).output.into()
|
||||
DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).menu(move || rows.clone()).show(ui, |_, _| ()).output.into()
|
||||
}
|
||||
|
||||
#[story(GroupGrip<usize>, covers = [Default])]
|
||||
@@ -130,21 +132,20 @@ fn between_sections(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
}
|
||||
|
||||
/// The panels of the Window menu story: each labelled by its number.
|
||||
#[derive(crate::contract::PlainData)]
|
||||
struct NumberedPanels;
|
||||
|
||||
impl DockPanels<u32> for NumberedPanels {
|
||||
impl PanelSpecs<u32> for NumberedPanels {
|
||||
fn spec(&self, panel: &u32) -> PanelSpec {
|
||||
PanelSpec::new(format!("Panel {panel}"))
|
||||
}
|
||||
|
||||
fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {}
|
||||
}
|
||||
|
||||
#[story(WindowMenuRows<'static, u32>, covers = [Default], drive = Drive::Never)]
|
||||
fn window_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let layout = Layout::new(Some(Node::tabs(vec![1], 0)), Vec::new());
|
||||
let menu = Menu::new("Window").open(data.bind("open", true)).show(ui, |ui, _| {
|
||||
WindowMenuRows::new(&layout, &NumberedPanels, &[1, 2]).show(ui);
|
||||
WindowMenuRows::new(&layout, &Tracked::new(NumberedPanels), &[1, 2]).show(ui);
|
||||
});
|
||||
StoryOutput::from(menu.output)
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
//! previous pass's registry, because a drop is decided against what was on screen when the pointer moved. Every
|
||||
//! zone is a rect. A spot names a group by an anchor panel, as the dock model does.
|
||||
|
||||
use super::{DragUnit, PanelKey, PanelSpec, scale_widths, stepped, width_bounds};
|
||||
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;
|
||||
@@ -69,6 +69,11 @@ pub struct DockSizes {
|
||||
pub iconic_least: f32,
|
||||
/// The width of an expanded column the user has not resized (the dock column width).
|
||||
pub column: f32,
|
||||
/// A tool rail's width at one column: a rail button and the control padding on both sides
|
||||
/// ([`DockGrid::rail`](super::DockGrid::rail)).
|
||||
pub rail_first: f32,
|
||||
/// The width each further column of a tool rail adds: a rail button and the tight gap before it.
|
||||
pub rail_step: f32,
|
||||
}
|
||||
|
||||
impl DockSizes {
|
||||
@@ -78,6 +83,12 @@ impl DockSizes {
|
||||
StyleCx::with_root(ctx, DockSizes::style)
|
||||
}
|
||||
|
||||
/// The sizes in the style of the scope `ui` is in: what a dock shown in `ui` sizes with.
|
||||
pub fn of_scope(ui: &egui::Ui) -> Self {
|
||||
let env = crate::runtime::env::Env::of(ui);
|
||||
Self::style(&StyleCx::of_env(ui.ctx(), &env))
|
||||
}
|
||||
|
||||
/// The sizes of the style context `cx`.
|
||||
pub fn style(cx: &StyleCx<'_>) -> Self {
|
||||
let size = &cx.tokens.size;
|
||||
@@ -103,6 +114,8 @@ impl DockSizes {
|
||||
jump: cx.control().height,
|
||||
iconic_least: size.rail.width,
|
||||
column: size.dock.column,
|
||||
rail_first: size.rail.button + 2.0 * cx.tokens.space.pad.control,
|
||||
rail_step: size.rail.button + cx.tokens.space.gap.tight,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,9 +133,9 @@ impl DockSizes {
|
||||
|
||||
/// The width an expanded column's panels draw at, whether the column is expanded or iconic (its flyout and a
|
||||
/// floated iconic column use it): the stored width kept within the panels' limits, or a stepped column's width
|
||||
/// at its steps ([`stepped`]).
|
||||
/// at its steps ([`DockSizes::stepped`](super::DockSizes::stepped)).
|
||||
pub fn expanded_width<P>(&self, column: &Column<P>, spec: &dyn Fn(&P) -> PanelSpec) -> f32 {
|
||||
if let Some((grid, steps)) = stepped(column, spec) {
|
||||
if let Some((grid, steps)) = self.stepped(column, spec) {
|
||||
return grid.width(steps);
|
||||
}
|
||||
let (lo, hi) = self.width_bounds(column, spec);
|
||||
@@ -141,7 +154,7 @@ impl DockSizes {
|
||||
pub fn shown_bounds<P>(&self, column: &Column<P>, spec: &dyn Fn(&P) -> PanelSpec) -> (f32, f32) {
|
||||
if column.iconic {
|
||||
self.iconic_bounds(column, spec)
|
||||
} else if let Some((grid, _)) = stepped(column, spec) {
|
||||
} else if let Some((grid, _)) = self.stepped(column, spec) {
|
||||
(grid.width(1), grid.width(grid.most))
|
||||
} else {
|
||||
self.width_bounds(column, spec)
|
||||
@@ -175,7 +188,7 @@ impl DockSizes {
|
||||
Some(Node::Dock { columns, .. }) => columns,
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
let fixed = |column: &Column<P>| !column.iconic && stepped(column, spec).is_some();
|
||||
let fixed = |column: &Column<P>| !column.iconic && self.stepped(column, spec).is_some();
|
||||
let current: Vec<(f32, (f32, f32))> = columns
|
||||
.iter()
|
||||
.map(|column| {
|
||||
@@ -201,7 +214,7 @@ impl DockSizes {
|
||||
columns
|
||||
.iter()
|
||||
.map(|column| {
|
||||
let keeps = column.iconic || stepped(column, spec).is_some();
|
||||
let keeps = column.iconic || self.stepped(column, spec).is_some();
|
||||
(self.width(column, spec), (!keeps).then(|| self.width_bounds(column, spec).0.max(1.0)))
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! `WindowMenuRows`: the Window menu's check row for every panel of an app.
|
||||
|
||||
use super::DockPanels;
|
||||
use super::SpecSource;
|
||||
use crate::contract::Show as _;
|
||||
use crate::menu::MenuItem;
|
||||
use craft_behavior::dock::{Action, Layout, PanelState};
|
||||
@@ -8,7 +8,7 @@ use egui::Ui;
|
||||
use std::hash::Hash;
|
||||
|
||||
/// One check row per panel in the order the app gives, for a Window menu. A row is checked while its panel is in the
|
||||
/// layout (closed panels are not), and its label and icon come from [`DockPanels::spec`]. A pick returns the action
|
||||
/// layout (closed panels are not), and its label and icon come from the panels' specs ([`PanelSpecs::spec`](super::PanelSpecs::spec)). A pick returns the action
|
||||
/// that shows the panel (open a closed one, bring a panel behind another tab to the front) or closes it (a panel
|
||||
/// showing); the app applies it through the same path as the actions of a `DockArea`. A Hidden pick's `Action::open`
|
||||
/// restores the panel's last place through `Workspace::apply_all`.
|
||||
@@ -20,7 +20,7 @@ use std::hash::Hash;
|
||||
#[pattern(probe(WindowMenuRows<'static, u32>))]
|
||||
pub struct WindowMenuRows<'a, P> {
|
||||
layout: &'a Layout<P>,
|
||||
panels: &'a dyn DockPanels<P>,
|
||||
specs: &'a dyn SpecSource<P>,
|
||||
order: &'a [P],
|
||||
flyout: Option<&'a P>,
|
||||
}
|
||||
@@ -37,9 +37,10 @@ pub struct WindowMenuRowsOutput<P> {
|
||||
}
|
||||
|
||||
impl<'a, P: Clone + Eq + Hash> WindowMenuRows<'a, P> {
|
||||
/// Rows for `order` (every panel the app has, open or not), checked from `layout`, labelled by `panels`.
|
||||
pub fn new(layout: &'a Layout<P>, panels: &'a dyn DockPanels<P>, order: &'a [P]) -> Self {
|
||||
WindowMenuRows { layout, panels, order, flyout: None }
|
||||
/// Rows for `order` (every panel the app has, open or not), checked from `layout`, labelled by `specs`, the
|
||||
/// host's spec model the dock shows ([`DockArea::new`](crate::docking)).
|
||||
pub fn new(layout: &'a Layout<P>, specs: &'a dyn SpecSource<P>, order: &'a [P]) -> Self {
|
||||
WindowMenuRows { layout, specs, order, flyout: None }
|
||||
}
|
||||
|
||||
/// The panel whose flyout is open: the value of the binding the app gives `DockArea::flyout`.
|
||||
@@ -53,7 +54,7 @@ impl<'a, P: Clone + Eq + Hash> WindowMenuRows<'a, P> {
|
||||
pub fn show(self, ui: &mut Ui) -> WindowMenuRowsOutput<P> {
|
||||
let (mut action, mut flyout) = (None, None);
|
||||
for panel in self.order {
|
||||
let spec = self.panels.spec(panel);
|
||||
let spec = self.specs.spec(panel);
|
||||
let state = self.layout.panel_state(panel);
|
||||
let in_flyout = self.layout.opens_in_flyout(panel);
|
||||
let open = self.flyout == Some(panel);
|
||||
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user