mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
Merge upstream next into the checkbox sweep port
This commit is contained in:
Generated
+19
-14
@@ -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",
|
||||
@@ -4248,6 +4252,7 @@ name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-ui-macros",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5445,7 +5450,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -5501,7 +5506,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5536,7 +5541,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -5555,7 +5560,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5574,7 +5579,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"bytemuck",
|
||||
@@ -5594,7 +5599,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -5607,7 +5612,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5684,7 +5689,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -5757,7 +5762,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5783,7 +5788,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
@@ -15114,19 +15119,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
|
||||
|
||||
+14
-14
@@ -310,20 +310,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
linesweeper = { path = "vendor/linesweeper" }
|
||||
vello_common = { path = "vendor/vello_common" }
|
||||
vello_cpu = { path = "vendor/vello_cpu" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
|
||||
|
||||
@@ -60,7 +60,9 @@ impl ActionsSettings {
|
||||
|
||||
/// The Actions panel's persisted section: Button Mode and the collapsed sets.
|
||||
/// Selection and expansion are not persisted.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(
|
||||
Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ActionsSettings {
|
||||
@@ -72,7 +74,7 @@ pub struct ActionsSettings {
|
||||
|
||||
/// A row of the tree: a set header, an action or one of its steps. Also the selection (one row at
|
||||
/// a time) and the list's key.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum ActionSelection {
|
||||
/// The set header of this name.
|
||||
@@ -89,7 +91,7 @@ pub enum ActionSelection {
|
||||
/// The panel remaps `selected` itself when it reports a [`Reorder`](ActionsEvent::Reorder)
|
||||
/// that moves a row, since it owns the selection. After a [`Delete`](ActionsEvent::Delete) the
|
||||
/// app clears `selected` (the panel cannot tell which rows the delete removed).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct ActionsPanelState {
|
||||
/// The persisted section.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -124,6 +124,34 @@ impl Format {
|
||||
}
|
||||
}
|
||||
|
||||
/// Most files [`list_folder`] lists.
|
||||
const MAX_FILES: usize = 500;
|
||||
/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB.
|
||||
const MAX_BYTES: u64 = 64 << 20;
|
||||
|
||||
/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name
|
||||
/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files
|
||||
/// too large to be a LUT are skipped, and a symlink to a LUT file is listed.
|
||||
pub fn list_folder(dir: &std::path::Path) -> Vec<(String, std::path::PathBuf)> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut out: Vec<(String, std::path::PathBuf)> = entries
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let name = entry.file_name().into_string().ok()?;
|
||||
let extension = name.rsplit_once('.')?.1.to_ascii_lowercase();
|
||||
if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") {
|
||||
return None;
|
||||
}
|
||||
let path = entry.path();
|
||||
let meta = std::fs::metadata(&path).ok()?;
|
||||
(meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path))
|
||||
})
|
||||
.collect();
|
||||
out.sort_by_key(|(name, _)| name.to_lowercase());
|
||||
out.truncate(MAX_FILES);
|
||||
out
|
||||
}
|
||||
|
||||
/// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing).
|
||||
pub fn parse(file_name: &str, bytes: &[u8]) -> Result<LutFile, LutError> {
|
||||
parse_as(Format::detect(file_name, bytes), bytes)
|
||||
|
||||
@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How a gradient's opacity is stored, which decides the rows of its stop bar.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[non_exhaustive]
|
||||
pub enum StopRows {
|
||||
/// Opacity stops in their own row above the ramp, colour stops below; a colour's alpha is
|
||||
@@ -36,6 +37,7 @@ pub enum StopRow {
|
||||
|
||||
/// A colour stop.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorStop {
|
||||
@@ -56,6 +58,7 @@ pub struct ColorStop {
|
||||
|
||||
/// An opacity stop of a [`StopRows::Split`] gradient.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct OpacityStop {
|
||||
@@ -120,6 +123,7 @@ impl OpacityStop {
|
||||
|
||||
/// A gradient's stops, each list sorted by location.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientStops {
|
||||
|
||||
@@ -97,6 +97,7 @@ impl SwatchFormat {
|
||||
|
||||
/// A swatch colour in its own model.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(tag = "model", content = "values", rename_all = "camelCase")]
|
||||
pub enum SwatchColor {
|
||||
/// Encoded RGB, 0–1 each, in the RGB working space.
|
||||
@@ -148,6 +149,7 @@ impl SwatchColor {
|
||||
|
||||
/// How an `.ase` file marks a colour.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SwatchKind {
|
||||
#[default]
|
||||
@@ -161,6 +163,7 @@ pub enum SwatchKind {
|
||||
|
||||
/// One named swatch.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
pub struct SwatchEntry {
|
||||
/// The swatch's label.
|
||||
pub name: String,
|
||||
@@ -181,6 +184,7 @@ impl SwatchEntry {
|
||||
/// A named group of swatches, as the Swatches panel shows them. A file without groups reads as
|
||||
/// one group named after the file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
pub struct SwatchGroup {
|
||||
/// The group's label.
|
||||
pub name: String,
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
//! [`Files`](craft_host::Files) and reads and parses it as a [`Jobs`](craft_host::Jobs) job.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Instant;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{EditEvent, EditEvents, Metrics, Mixed, Proposal, Sense};
|
||||
use craft_cms::lutfile::{LutError, LutFile};
|
||||
@@ -16,6 +15,7 @@ use craft_ui::contract::{
|
||||
};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::frame;
|
||||
use craft_ui::style::{ComponentStyle, StyleCx};
|
||||
use egui::{Response, Vec2};
|
||||
|
||||
@@ -154,12 +154,6 @@ impl Default for Parsed {
|
||||
}
|
||||
}
|
||||
|
||||
/// The seconds since the first scan of the process, for the rescan interval.
|
||||
fn seconds() -> u64 {
|
||||
static START: OnceLock<Instant> = OnceLock::new();
|
||||
START.get_or_init(Instant::now).elapsed().as_secs()
|
||||
}
|
||||
|
||||
/// A select of LUTs.
|
||||
///
|
||||
/// - Rows: Load 3D LUT…, None, the eight built-in looks, the LUT folder's files by name (in the language's
|
||||
@@ -269,9 +263,11 @@ impl Component for LutPicker<'_> {
|
||||
state = LutState { folder: self.folder.clone(), load: state.load, ..LutState::default() };
|
||||
}
|
||||
if let Some(folder) = self.folder.clone() {
|
||||
let key = ("lut-scan", folder.clone(), seconds() / RESCAN);
|
||||
let key = ("lut-scan", folder.clone(), frame::stepped_clock(&cx.response.ctx, RESCAN as f64) as u64 / RESCAN);
|
||||
let started = folder.clone();
|
||||
if let Pending::Ready(found) = cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(list_folder(&started))))) {
|
||||
if let Pending::Ready(found) =
|
||||
cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(craft_cms::lutfile::list_folder(&started)))))
|
||||
{
|
||||
let mut files = (**found).clone();
|
||||
cx.env.collator().sort_by_key(&mut files, |(name, _)| name.as_str());
|
||||
state.files = Arc::new(files);
|
||||
@@ -378,30 +374,3 @@ fn builtin_name(words: &LutWords, id: &str) -> Label {
|
||||
fn file_name(path: &Path) -> String {
|
||||
path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
/// Most files [`list_folder`] lists.
|
||||
const MAX_FILES: usize = 500;
|
||||
/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB.
|
||||
const MAX_BYTES: u64 = 64 << 20;
|
||||
|
||||
/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name
|
||||
/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files
|
||||
/// too large to be a LUT are skipped, and a symlink to a LUT file is listed.
|
||||
fn list_folder(dir: &Path) -> FolderFiles {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut out: FolderFiles = entries
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let name = entry.file_name().into_string().ok()?;
|
||||
let extension = name.rsplit_once('.')?.1.to_ascii_lowercase();
|
||||
if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") {
|
||||
return None;
|
||||
}
|
||||
let path = entry.path();
|
||||
let meta = std::fs::metadata(&path).ok()?;
|
||||
(meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path))
|
||||
})
|
||||
.collect();
|
||||
out.sort_by_key(|(name, _)| name.to_lowercase());
|
||||
out.truncate(MAX_FILES);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ pub use screen_picker::{CaptureResult, CaptureSource, LOUPE_PIXELS, LOUPE_ZOOM,
|
||||
pub use strip::{ColorStrip, ColorStripStyle};
|
||||
pub use swatches::{
|
||||
MAX_GROUPS, MAX_SWATCHES, SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput,
|
||||
SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows,
|
||||
SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows, swatch_source,
|
||||
};
|
||||
pub use warning::{ColorWarning, ColorWarningArrangement, ColorWarningChip, ColorWarningChipOutput, ColorWarningChipStyle};
|
||||
pub use wheel::{
|
||||
|
||||
@@ -14,14 +14,14 @@ use craft_behavior::{Axis, EditEvent, EditEvents, Metrics, PartKey};
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchFace};
|
||||
use craft_ui::choice::{ChoiceWords, Segmented, Swatch};
|
||||
use craft_ui::contract::{
|
||||
Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, Pages,
|
||||
PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState, ThumbInfo};
|
||||
use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState};
|
||||
use craft_ui::primitives::textures::CachedTexture;
|
||||
use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
@@ -30,7 +30,7 @@ use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx}
|
||||
use egui::{Color32, Pos2, Rect, Response, Ui, pos2, vec2};
|
||||
|
||||
use super::popover::compact_picker;
|
||||
use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, SwatchesWords, swatch_rows};
|
||||
use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, swatch_source};
|
||||
use crate::palette::{SwatchColor, SwatchGroup};
|
||||
|
||||
pub(crate) mod paint_list;
|
||||
@@ -475,7 +475,6 @@ impl Component for PaintChip<'_> {
|
||||
let solid = cx.memory::<LastSolid>().0.unwrap_or(self.fallback);
|
||||
let current = FillKind::of(&paint);
|
||||
let sampled = self.sampled;
|
||||
let swatch_words = cx.words::<SwatchesWords>();
|
||||
let recent_cells: Vec<(Label, Srgba)> = self.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
|
||||
let full_picker = self.full_picker;
|
||||
let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated());
|
||||
@@ -514,21 +513,14 @@ impl Component for PaintChip<'_> {
|
||||
}
|
||||
if let Some((groups, state)) = swatches.as_mut() {
|
||||
let groups: &[SwatchGroup] = groups;
|
||||
let rows = swatch_rows(groups, &swatch_words);
|
||||
let source = swatch_source(groups, cmyk);
|
||||
let colors: HashMap<&str, &SwatchColor> =
|
||||
groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect();
|
||||
let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &rows)
|
||||
let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &source)
|
||||
.toolbar(false)
|
||||
.row_menu(false)
|
||||
.default_open(DefaultOpen::None)
|
||||
.room_height(Env::of(ui).tokens.size.control.sm * SWATCH_ROWS)
|
||||
.thumb(|painter: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| {
|
||||
if let SwatchKey::Swatch(name) = info.key
|
||||
&& let Some(color) = colors.get(name.as_str())
|
||||
{
|
||||
SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(painter, rect);
|
||||
}
|
||||
})
|
||||
.show(ui);
|
||||
for event in out.events {
|
||||
if let PresetEvent::Select { key: SwatchKey::Swatch(name), .. } = event
|
||||
|
||||
@@ -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, _| {
|
||||
|
||||
@@ -62,7 +62,19 @@ craft_ui::words! {
|
||||
|
||||
/// What the panel shows: Photoshop's panel menu choices, in its order. Hue Cube is the default;
|
||||
/// the theme never changes it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(
|
||||
Clone,
|
||||
Copy,
|
||||
Debug,
|
||||
Default,
|
||||
PartialEq,
|
||||
Eq,
|
||||
Hash,
|
||||
serde::Serialize,
|
||||
serde::Deserialize,
|
||||
craft_ui::contract::MemoProps,
|
||||
craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPanelMode {
|
||||
@@ -129,7 +141,19 @@ impl ColorPanelMode {
|
||||
}
|
||||
|
||||
/// The ramp under the sliders. Shift-click on the ramp cycles them in this order.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(
|
||||
Clone,
|
||||
Copy,
|
||||
Debug,
|
||||
Default,
|
||||
PartialEq,
|
||||
Eq,
|
||||
Hash,
|
||||
serde::Serialize,
|
||||
serde::Deserialize,
|
||||
craft_ui::contract::MemoProps,
|
||||
craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPanelRamp {
|
||||
@@ -179,7 +203,9 @@ impl ColorPanelRamp {
|
||||
}
|
||||
|
||||
/// The Color panel's settings, kept across runs (settings section `color_panel`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorPanelState {
|
||||
|
||||
@@ -11,7 +11,7 @@ pub(crate) mod panel;
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows};
|
||||
pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows, swatch_source};
|
||||
pub use menu::{SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput};
|
||||
pub use panel::{SwatchesPanel, SwatchesPanelOutput};
|
||||
|
||||
|
||||
@@ -2,8 +2,15 @@
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::SwatchFace;
|
||||
use craft_ui::contract::ReorderMove;
|
||||
use craft_ui::patterns::presets::{PresetRow, PresetState};
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource, PresetState, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use egui::Rect;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::{MAX_GROUPS, MAX_SWATCHES, SWATCH_ZOOM, SwatchesWords};
|
||||
use crate::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchReport};
|
||||
@@ -11,7 +18,7 @@ use crate::ui::PickedColor;
|
||||
|
||||
/// What the browser names its rows by. Swatch names are unique across the library and group names among groups, so
|
||||
/// both survive reordering.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum SwatchKey {
|
||||
/// A group, by name.
|
||||
@@ -556,8 +563,27 @@ impl SwatchLibrary {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as its
|
||||
/// tooltip and accessible name. `SwatchesPanel` and `PaintChip`'s swatches list build their rows with it.
|
||||
/// The swatch list's inputs: the library's groups and each swatch's colour as drawn, by name.
|
||||
#[derive(craft_ui::contract::MemoProps)]
|
||||
struct SwatchInputs<'a> {
|
||||
groups: &'a [SwatchGroup],
|
||||
drawn: BTreeMap<&'a str, Srgba>,
|
||||
}
|
||||
|
||||
/// The presets of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as
|
||||
/// its tooltip and accessible name, painted in its colour through `cmyk`. `SwatchesPanel` and `PaintChip`'s swatches
|
||||
/// list show it.
|
||||
pub fn swatch_source<'a>(groups: &'a [SwatchGroup], cmyk: &CmykConverter) -> PresetSource<'a, SwatchKey> {
|
||||
let drawn = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), e.color.to_srgb(cmyk)))).collect();
|
||||
PresetSource::new(SwatchInputs { groups, drawn }, PresetFns::new(source_rows).thumb(paint_swatch))
|
||||
}
|
||||
|
||||
fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>> {
|
||||
swatch_rows(inputs.groups, &env.words::<SwatchesWords>())
|
||||
}
|
||||
|
||||
/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and
|
||||
/// colour value.
|
||||
pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetRow<SwatchKey>> {
|
||||
let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::<usize>());
|
||||
for group in groups {
|
||||
@@ -570,6 +596,14 @@ pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetR
|
||||
rows
|
||||
}
|
||||
|
||||
fn paint_swatch(inputs: &SwatchInputs<'_>, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>) {
|
||||
if let SwatchKey::Swatch(name) = info.key
|
||||
&& let Some(color) = inputs.drawn.get(name.as_str())
|
||||
{
|
||||
SwatchFace::new(*color).selected(info.selected).paint(cx, rect);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,24 +1,20 @@
|
||||
//! `SwatchesPanel`: the panel body, its state and what it reports.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_i18n::Format;
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::bars::StatusMessage;
|
||||
use craft_ui::choice::SwatchFace;
|
||||
use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _, request_rename};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords};
|
||||
use craft_ui::runtime::env::{Count, Env};
|
||||
use egui::{Rect, Response, Ui};
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use super::library::{find_swatch, has};
|
||||
use super::menu::event_edits;
|
||||
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_rows};
|
||||
use crate::palette::{SwatchColor, SwatchGroup, SwatchNote, SwatchReport};
|
||||
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_source};
|
||||
use crate::palette::{SwatchGroup, SwatchNote, SwatchReport};
|
||||
|
||||
/// What [`SwatchesPanel::show`] reports.
|
||||
#[derive(Debug)]
|
||||
@@ -99,21 +95,13 @@ impl<'a> SwatchesPanel<'a> {
|
||||
if st.selected.as_ref().is_some_and(|k| !has(groups, k)) {
|
||||
st.selected = None;
|
||||
}
|
||||
let rows = swatch_rows(groups, &words);
|
||||
let source = swatch_source(groups, cmyk);
|
||||
let out = {
|
||||
let colors: HashMap<&str, &SwatchColor> = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect();
|
||||
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &rows)
|
||||
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source)
|
||||
.thumb_range(SWATCH_ZOOM)
|
||||
.toolbar(true)
|
||||
.reorder(PresetReorder::items_and_groups())
|
||||
.footer(PresetFooterOptions::new().can_delete(st.selected.is_some()))
|
||||
.thumb(|cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| {
|
||||
if let SwatchKey::Swatch(name) = info.key
|
||||
&& let Some(color) = colors.get(name.as_str())
|
||||
{
|
||||
SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(cx, rect);
|
||||
}
|
||||
});
|
||||
.footer(PresetFooterOptions::new().can_delete(st.selected.is_some()));
|
||||
if let Some(key) = &st.selected {
|
||||
browser = browser.selected(key.clone());
|
||||
}
|
||||
|
||||
@@ -910,6 +910,7 @@ timeline-otio = ["timeline", "craft-timeline/otio"]
|
||||
timeline-xml = ["timeline", "craft-timeline/xml"]
|
||||
|
||||
tracked = ["dep:craft-tracked"]
|
||||
tracked-serde = ["tracked", "craft-tracked/serde"]
|
||||
|
||||
ui-app = ["ui", "craft-ui/app"]
|
||||
ui-cloud = ["ui", "craft-ui/cloud"]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/// The egui fork the library is built and tested with. Apps patch egui to exactly this.
|
||||
pub const GIT: &str = "https://github.com/storytold/egui.git";
|
||||
/// The commit of [`GIT`].
|
||||
pub const REV: &str = "6525c87923ca47465aac244460fe4b1139349060";
|
||||
pub const REV: &str = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f";
|
||||
|
||||
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
|
||||
pub const PACKAGES: &[&str] = &[
|
||||
|
||||
@@ -75,13 +75,13 @@ reason = "document-space drawing"
|
||||
| `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` |
|
||||
| `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is |
|
||||
| `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. |
|
||||
| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or later task that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` |
|
||||
| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or test-data cache that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` |
|
||||
|
||||
Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui.
|
||||
|
||||
Names are resolved through the file's `use` items, per module scope: grouped imports, renames (`use egui::Margin as M`), module aliases (`use crate::theme as t`) and glob imports (`use crate::theme::*`) all reach the rule table, so `margin(4.0)` is flagged after `use crate::theme::margin`. A bare name that a fn in the same module defines is not extended through globs. Imports in a module do not apply in sibling modules.
|
||||
|
||||
A literal is a number, optionally negated, parenthesised, cast or in arithmetic; zero is never flagged. A name is flagged when a `const` or `static` in the same file with that name has such a value. Consts are keyed by module and impl scope: a bare name takes the innermost scope that defines it, `Self::X`, `self::X`, `super::X`, `crate::X`, `Type::X` and `module::X` (last two segments) the scope they name, and a name with several candidates is flagged when any is non-zero.
|
||||
A literal is a number, optionally negated, parenthesised, cast or in arithmetic; zero is never flagged. A name is flagged when a `const` or `static` in the same file with that name has such a value, unless it is a component constant: a module- or impl-level `const` with a doc comment, the named place for a dimension of one component's own drawing (craft-framework.md 5.4). A name that resolves to a component constant is not a literal size, and its initializer is its definition, so the literals in it are not flagged either. A `const` inside a fn body, a `static` and an undocumented `const` are flagged as literals. Consts are keyed by module and impl scope: a bare name takes the innermost scope that defines it, `Self::X`, `self::X`, `super::X`, `crate::X`, `Type::X` and `module::X` (last two segments) the scope they name, and a name with several candidates is flagged when any is non-zero.
|
||||
|
||||
## Markers
|
||||
|
||||
|
||||
@@ -150,6 +150,7 @@ pub(crate) fn analyze_file(src: &str, file: &syn::File, include_tests: bool) ->
|
||||
imports: Vec::new(),
|
||||
fns: Vec::new(),
|
||||
scope: Vec::new(),
|
||||
in_named_const: false,
|
||||
out: Analysis::default(),
|
||||
include_tests,
|
||||
};
|
||||
@@ -184,6 +185,9 @@ struct ConstDef {
|
||||
line: usize,
|
||||
expr: Expr,
|
||||
value: Option<f64>,
|
||||
/// A component constant: a module- or impl-level `const` with a doc comment. A name that resolves to it is not a
|
||||
/// literal size, and its initializer is its definition, not a call site.
|
||||
named: bool,
|
||||
}
|
||||
|
||||
/// A `use` declaration: `alias` is the name it brings in, `None` for a glob (`path::*`).
|
||||
@@ -202,6 +206,8 @@ struct Linter<'a> {
|
||||
fns: Vec<(Vec<Frame>, String)>,
|
||||
/// The modules and impl blocks around the item being visited.
|
||||
scope: Vec<Frame>,
|
||||
/// Inside the initializer of a named const, where `literal-size/*` does not apply.
|
||||
in_named_const: bool,
|
||||
out: Analysis,
|
||||
include_tests: bool,
|
||||
}
|
||||
@@ -212,17 +218,21 @@ struct ConstCollector {
|
||||
imports: Vec<Import>,
|
||||
fns: Vec<(Vec<Frame>, String)>,
|
||||
scope: Vec<Frame>,
|
||||
/// How many fn bodies enclose the item being visited.
|
||||
fn_depth: usize,
|
||||
include_tests: bool,
|
||||
}
|
||||
|
||||
impl ConstCollector {
|
||||
fn add(&mut self, name: &syn::Ident, expr: &Expr) {
|
||||
/// Records a const or static; `documented` is whether it is a `const` with a doc comment.
|
||||
fn add(&mut self, name: &syn::Ident, expr: &Expr, documented: bool) {
|
||||
self.defs.push(ConstDef {
|
||||
scope: self.scope.clone(),
|
||||
name: name.to_string(),
|
||||
line: name.span().start().line,
|
||||
expr: expr.clone(),
|
||||
value: None,
|
||||
named: documented && self.fn_depth == 0,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -256,9 +266,21 @@ impl<'ast> Visit<'ast> for ConstCollector {
|
||||
fn visit_item_fn(&mut self, i: &'ast syn::ItemFn) {
|
||||
if !self.skipped(&i.attrs) {
|
||||
self.fns.push((module_scope(&self.scope).to_vec(), i.sig.ident.to_string()));
|
||||
self.fn_depth += 1;
|
||||
visit::visit_item_fn(self, i);
|
||||
self.fn_depth -= 1;
|
||||
}
|
||||
}
|
||||
fn visit_impl_item_fn(&mut self, i: &'ast syn::ImplItemFn) {
|
||||
self.fn_depth += 1;
|
||||
visit::visit_impl_item_fn(self, i);
|
||||
self.fn_depth -= 1;
|
||||
}
|
||||
fn visit_trait_item_fn(&mut self, i: &'ast syn::TraitItemFn) {
|
||||
self.fn_depth += 1;
|
||||
visit::visit_trait_item_fn(self, i);
|
||||
self.fn_depth -= 1;
|
||||
}
|
||||
fn visit_item_use(&mut self, i: &'ast syn::ItemUse) {
|
||||
if !self.skipped(&i.attrs) {
|
||||
let mut found = Vec::new();
|
||||
@@ -268,15 +290,15 @@ impl<'ast> Visit<'ast> for ConstCollector {
|
||||
}
|
||||
}
|
||||
fn visit_item_const(&mut self, i: &'ast syn::ItemConst) {
|
||||
self.add(&i.ident, &i.expr);
|
||||
self.add(&i.ident, &i.expr, has_doc(&i.attrs));
|
||||
visit::visit_item_const(self, i);
|
||||
}
|
||||
fn visit_item_static(&mut self, i: &'ast syn::ItemStatic) {
|
||||
self.add(&i.ident, &i.expr);
|
||||
self.add(&i.ident, &i.expr, false);
|
||||
visit::visit_item_static(self, i);
|
||||
}
|
||||
fn visit_impl_item_const(&mut self, i: &'ast syn::ImplItemConst) {
|
||||
self.add(&i.ident, &i.expr);
|
||||
self.add(&i.ident, &i.expr, has_doc(&i.attrs));
|
||||
visit::visit_impl_item_const(self, i);
|
||||
}
|
||||
}
|
||||
@@ -349,6 +371,11 @@ fn last_ident(path: &syn::Path) -> Option<String> {
|
||||
path.segments.last().map(|s| s.ident.to_string())
|
||||
}
|
||||
|
||||
/// Whether an item carries a doc comment (`///` or `#[doc = ...]`).
|
||||
fn has_doc(attrs: &[Attribute]) -> bool {
|
||||
attrs.iter().any(|a| a.path().is_ident("doc"))
|
||||
}
|
||||
|
||||
fn cfg_is_test(meta: &Meta) -> bool {
|
||||
match meta {
|
||||
Meta::Path(p) => p.is_ident("test"),
|
||||
@@ -420,8 +447,14 @@ impl Linter<'_> {
|
||||
}
|
||||
|
||||
fn resolve_consts(&mut self, file: &syn::File) {
|
||||
let mut collector =
|
||||
ConstCollector { defs: Vec::new(), imports: Vec::new(), fns: Vec::new(), scope: Vec::new(), include_tests: self.include_tests };
|
||||
let mut collector = ConstCollector {
|
||||
defs: Vec::new(),
|
||||
imports: Vec::new(),
|
||||
fns: Vec::new(),
|
||||
scope: Vec::new(),
|
||||
fn_depth: 0,
|
||||
include_tests: self.include_tests,
|
||||
};
|
||||
collector.visit_file(file);
|
||||
self.defs = collector.defs;
|
||||
self.imports = collector.imports;
|
||||
@@ -431,7 +464,8 @@ impl Linter<'_> {
|
||||
.defs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, d)| d.value.is_none())
|
||||
// A named const keeps no literal value: a name that resolves to it reads like a token.
|
||||
.filter(|(_, d)| d.value.is_none() && !d.named)
|
||||
.filter_map(|(i, d)| self.eval_in(&d.expr, &d.scope).map(|v| (i, v)))
|
||||
.collect();
|
||||
if resolved.is_empty() {
|
||||
@@ -552,12 +586,21 @@ impl Linter<'_> {
|
||||
Some((shown, def.line))
|
||||
}
|
||||
|
||||
/// Whether the const item named `ident` is a named const (`ConstDef::named`).
|
||||
fn is_named_const(&self, ident: &syn::Ident) -> bool {
|
||||
let line = ident.span().start().line;
|
||||
self.defs.iter().any(|d| d.named && d.line == line && *ident == d.name)
|
||||
}
|
||||
|
||||
fn is_flagged_size(&self, e: &Expr) -> bool {
|
||||
self.eval(e).is_some_and(|v| v != 0.0)
|
||||
}
|
||||
|
||||
/// Reports `what` when any of `args` is a non-zero literal size.
|
||||
fn size_rule<'e>(&mut self, rule: &'static str, what: proc_macro2::Span, args: impl IntoIterator<Item = &'e Expr>) {
|
||||
if self.in_named_const {
|
||||
return;
|
||||
}
|
||||
let args: Vec<&Expr> = args.into_iter().collect();
|
||||
// A vector of literal -1, 0 and 1 is a direction, not a size.
|
||||
if rule == VEC2 && args.iter().all(|a| is_unit_literal(a)) {
|
||||
@@ -726,11 +769,21 @@ fn is_unit_literal(e: &Expr) -> bool {
|
||||
|
||||
fn hint(rule: &str) -> &'static str {
|
||||
match rule {
|
||||
VEC2 => "use a size token (`Tokens::of(ui).size.control.md`, `space.gap.inline`) or mark `// design: allow(<reason>)`",
|
||||
ADD_SPACE => "use a spacing token (`Tokens::of(ui).space.gap.inline`) or mark `// design: allow(<reason>)`",
|
||||
CORNER_RADIUS => "use a radius token from `Tokens::of(ui)` or mark `// design: allow(<reason>)`",
|
||||
STROKE => "use a stroke width token from `Tokens::of(ui)` or mark `// design: allow(<reason>)`",
|
||||
MARGIN => "use a spacing token (`Tokens::of(ui).space`) or mark `// design: allow(<reason>)`",
|
||||
VEC2 => {
|
||||
"use a size token (`Tokens::of(ui).size.control.md`, `space.gap.inline`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow(<reason>)`"
|
||||
}
|
||||
ADD_SPACE => {
|
||||
"use a spacing token (`Tokens::of(ui).space.gap.inline`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow(<reason>)`"
|
||||
}
|
||||
CORNER_RADIUS => {
|
||||
"use a radius token from `Tokens::of(ui)`, a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow(<reason>)`"
|
||||
}
|
||||
STROKE => {
|
||||
"use a stroke width token from `Tokens::of(ui)`, a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow(<reason>)`"
|
||||
}
|
||||
MARGIN => {
|
||||
"use a spacing token (`Tokens::of(ui).space`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow(<reason>)`"
|
||||
}
|
||||
TOOLTIP => "use `craft_ui::contract::Props::tooltip` or `craft_ui::contract::Show::show_with_tip` or mark `// design: allow(<reason>)`",
|
||||
STYLE_MUTATION => "set styles through the theme (craft-ui installs them from the tokens) or mark `// design: allow(<reason>)`",
|
||||
_ => "use a type-size token from `Tokens::of(ui)` or mark `// design: allow(<reason>)`",
|
||||
@@ -774,9 +827,18 @@ impl<'ast> Visit<'ast> for Linter<'_> {
|
||||
}
|
||||
fn visit_item_const(&mut self, i: &'ast syn::ItemConst) {
|
||||
if !self.skips(&i.attrs, i.span()) {
|
||||
let named = self.in_named_const || self.is_named_const(&i.ident);
|
||||
let outer = std::mem::replace(&mut self.in_named_const, named);
|
||||
visit::visit_item_const(self, i);
|
||||
self.in_named_const = outer;
|
||||
}
|
||||
}
|
||||
fn visit_impl_item_const(&mut self, i: &'ast syn::ImplItemConst) {
|
||||
let named = self.in_named_const || self.is_named_const(&i.ident);
|
||||
let outer = std::mem::replace(&mut self.in_named_const, named);
|
||||
visit::visit_impl_item_const(self, i);
|
||||
self.in_named_const = outer;
|
||||
}
|
||||
fn visit_item_static(&mut self, i: &'ast syn::ItemStatic) {
|
||||
if !self.skips(&i.attrs, i.span()) {
|
||||
visit::visit_item_static(self, i);
|
||||
|
||||
@@ -58,6 +58,7 @@ const CLOSED: &[&str] = &[
|
||||
"ReorderMove", // built or matched in craft-ui-patterns
|
||||
"RowState", // built or matched in craft-ui-widgets
|
||||
"RuleLook", // built or matched in craft-ui-canvas
|
||||
"RulerFace", // matched by every ruler (craft-text, craft-pages, craft-ui-canvas): a new face must be drawn by each
|
||||
"ShellRegions", // built or matched in craft-ui-shell
|
||||
"SizeLimits", // built or matched in craft-ui-panels
|
||||
"StoryOutput", // built or matched in craft-ui-widgets
|
||||
@@ -137,8 +138,8 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[
|
||||
];
|
||||
|
||||
/// The reviewed per-item allowlist of `contract/no-global-state`: a file and what it may hold, either the identifier of
|
||||
/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact or environment key that
|
||||
/// covers it, or the later task of craft-libs#2336 that removes the state. A new item in these files is flagged.
|
||||
/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact, environment key or test-data
|
||||
/// cache that covers it. A new item in these files is flagged.
|
||||
const NO_GLOBAL_STATE: &[(&str, &str)] = &[
|
||||
// Compile-time registry discovery reads the defining crate's source, never a view input.
|
||||
("crates/ui-macros/src/registry.rs", FS),
|
||||
@@ -160,6 +161,9 @@ const NO_GLOBAL_STATE: &[(&str, &str)] = &[
|
||||
("crates/ui-patterns/src/patterns/presets/model/library.rs", "MemoProps"),
|
||||
// Settled fact: a name check keys by its inputs and its `fn` behind `dyn NameChecker`, as `Bind::check_with` does.
|
||||
("crates/ui-patterns/src/patterns/presets/named.rs", "MemoProps"),
|
||||
// Settled fact: `PresetSource` erases its inputs behind a trait object; it keys on those inputs (themselves
|
||||
// `MemoProps`) and on the addresses of its capture-free `fn`s, which stand for the code that reads them.
|
||||
("crates/ui-patterns/src/patterns/presets/source.rs", "MemoProps"),
|
||||
// Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init.
|
||||
("crates/ui-contract/src/fonts/defaults.rs", "HACK"),
|
||||
("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"),
|
||||
@@ -199,32 +203,8 @@ const NO_GLOBAL_STATE: &[(&str, &str)] = &[
|
||||
("crates/imaging/src/ui/layer_style/hosted.rs", "PAINT"),
|
||||
// Settled fact: a test fake of the font store; it writes a temporary folder.
|
||||
("crates/font-manager/src/store/fake.rs", FS),
|
||||
// later task of #2336: the 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.
|
||||
("crates/ui-canvas/src/canvas_controls/outline/hover.rs", "GENERATIONS"),
|
||||
// later task of #2336: the texture serial counter is hidden state.
|
||||
("crates/imaging/src/ui/transform_preview/textures.rs", "SERIAL"),
|
||||
// later task of #2336: the mock image read cache is hidden state.
|
||||
// A cache of pure test data: MockImage is used only by stories and trials.
|
||||
("crates/imaging/src/ui/mock_image.rs", "READS"),
|
||||
// later task of #2336: the ranking cache is hidden state.
|
||||
("crates/font-manager/src/picker/rank.rs", "CACHE"),
|
||||
// later task of #2336: the face loader reads file sizes during the pass.
|
||||
("crates/font-manager/src/panel/faces.rs", FS),
|
||||
// later task of #2336: the gallery's set of seen names is hidden state.
|
||||
("crates/ui-gallery/src/viewer/layout.rs", "NAMES"),
|
||||
// later task of #2336: the LUT picker reads the process clock and scans folders during the pass.
|
||||
("crates/color-ui/src/ui/lut_picker.rs", "START"),
|
||||
("crates/color-ui/src/ui/lut_picker.rs", FS),
|
||||
];
|
||||
|
||||
/// Files that may read a clock (`contract/motion:clock`) beyond the runtime's motion module. A file key, because
|
||||
/// color-ui has no layer map.
|
||||
const MOTION_CLOCK_FILES: &[&str] = &[
|
||||
// later task of #2336: the LUT picker reads the process clock during the pass.
|
||||
"crates/color-ui/src/ui/lut_picker.rs",
|
||||
];
|
||||
|
||||
/// Whether `what` (an item identifier or [`FS`]) may be declared or used in `file` for `contract/no-global-state`.
|
||||
@@ -406,9 +386,6 @@ impl RuleScope for WorkspaceScope {
|
||||
if let Some(what) = key.strip_prefix("contract/no-global-state:") {
|
||||
return no_global_state_allows(what, file);
|
||||
}
|
||||
if key == "contract/motion:clock" && MOTION_CLOCK_FILES.iter().any(|f| file == Path::new(f)) {
|
||||
return true;
|
||||
}
|
||||
if key == "test/layout" {
|
||||
return file.starts_with(krate.dir.join("tests").join("it"));
|
||||
}
|
||||
|
||||
@@ -67,6 +67,20 @@ fn consts_resolve_by_module_and_impl_scope() {
|
||||
assert_eq!(run(src).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_consts_are_component_constants() {
|
||||
// A documented module or impl const is a named value, its initializer included; arithmetic on it reads like a token.
|
||||
let src = "/// The tick.\nconst TICK: f32 = 3.0;\n/// The room.\nconst ROOM: Vec2 = vec2(30.0, 40.0);\nstruct A;\nimpl A {\n /// The pad.\n const PAD: f32 = 6.0;\n fn f(&self, ui: &mut Ui) { ui.add_space(Self::PAD); ui.add_space(TICK * 2.0); let v = vec2(TICK, ROOM.y); }\n}\n";
|
||||
assert!(clean(src));
|
||||
|
||||
// An undocumented const, a documented const in a fn body and a literal stay flagged.
|
||||
let src = "const GAP: f32 = 4.0;\nfn f(ui: &mut Ui) { ui.add_space(GAP); }\nfn g(ui: &mut Ui) {\n /// The gap.\n const LOCAL: f32 = 4.0;\n ui.add_space(LOCAL);\n}\nfn h(ui: &mut Ui) { ui.add_space(4.0); }\n";
|
||||
assert_eq!(run(src).iter().map(|f| f.line).collect::<Vec<_>>(), [2, 6, 8]);
|
||||
|
||||
// The initializer of an undocumented const is a call site.
|
||||
assert!(flagged("const ROOM: Vec2 = vec2(30.0, 40.0);\n", "literal-size/vec2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clippy_allow_attributes_are_counted_and_inner_ones_flagged() {
|
||||
let src = "#![allow(clippy::disallowed_methods, reason = \"stock widgets\")]\n#[expect(clippy::disallowed_types)]\nstruct S;\n#[allow(clippy::too_many_arguments)]\nfn f() {}\nmod m {\n #![expect(clippy::disallowed_methods)]\n}\n";
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
use std::hash::Hash;
|
||||
|
||||
use craft_behavior::{EditEvents, IconId};
|
||||
use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, EditResponse, MemoProps, Outcome, Props as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetState};
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetSource, PresetState};
|
||||
use craft_ui::runtime::drag::DropZone;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::sections::FooterAction;
|
||||
@@ -29,9 +29,9 @@ pub(super) const BRUSH_THUMBS: TileZoom =
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
|
||||
#[pattern(probe(BrushesPanel<'static, u32>))]
|
||||
pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
|
||||
pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> {
|
||||
label: Label,
|
||||
rows: &'a [PresetRow<K>],
|
||||
source: &'a PresetSource<'a, K>,
|
||||
state: Bind<'a, PresetState<K>>,
|
||||
diameter: Bind<'a, f64>,
|
||||
max_size: f64,
|
||||
@@ -67,16 +67,22 @@ impl<K> Outcome for BrushesPanelOutput<K> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> BrushesPanel<'a, K> {
|
||||
/// A panel named `label` over the presets in `rows`, with its view in `state` and the brush
|
||||
impl<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> BrushesPanel<'a, K> {
|
||||
/// A panel named `label` over the presets of `source`, with its view in `state` and the brush
|
||||
/// size in `diameter` up to `max_size`.
|
||||
pub fn new(label: impl Into<Label>, rows: &'a [PresetRow<K>], state: Bind<'a, PresetState<K>>, diameter: Bind<'a, f64>, max_size: f64) -> Self {
|
||||
BrushesPanel { label: label.into(), rows, state, diameter, max_size, selected: None, drop_zone: None, import: false }
|
||||
pub fn new(
|
||||
label: impl Into<Label>,
|
||||
source: &'a PresetSource<'a, K>,
|
||||
state: Bind<'a, PresetState<K>>,
|
||||
diameter: Bind<'a, f64>,
|
||||
max_size: f64,
|
||||
) -> Self {
|
||||
BrushesPanel { label: label.into(), source, state, diameter, max_size, selected: None, drop_zone: None, import: false }
|
||||
}
|
||||
|
||||
/// Shows the panel.
|
||||
pub fn show(self, ui: &mut Ui) -> BrushesPanelOutput<K> {
|
||||
let BrushesPanel { label, rows, mut state, mut diameter, max_size, mut selected, mut drop_zone, import } = self;
|
||||
let BrushesPanel { label, source, mut state, mut diameter, max_size, mut selected, mut drop_zone, import } = self;
|
||||
let words = Env::of(ui).words::<BrushPresetWords>();
|
||||
let shown = Stack::new().label(label.clone()).fill().show(ui, |ui, _| {
|
||||
let size = BrushSizeField::new(words.size.clone(), diameter.reborrowed(), max_size).show(ui);
|
||||
@@ -84,7 +90,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> BrushesPanel<'a, K> {
|
||||
if import {
|
||||
footer = footer.action(FooterAction::new(IconId::new("folder_open"), words.menu_import.clone()));
|
||||
}
|
||||
let mut browser = PresetBrowser::new(label.clone(), state.reborrowed(), rows)
|
||||
let mut browser = PresetBrowser::new(label.clone(), state.reborrowed(), source)
|
||||
.toolbar(true)
|
||||
.row_menu(true)
|
||||
.reorder(PresetReorder::items_and_groups())
|
||||
|
||||
@@ -7,14 +7,15 @@ use std::hash::Hash;
|
||||
use craft_behavior::{Codec as _, EditEvent, EditEvents, IconId, Mixed, NumberCodec, Value};
|
||||
use craft_ui::buttons::IconButton;
|
||||
use craft_ui::contract::{
|
||||
Bind, BodyCx, EditResponse, Outcome, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _, TooltipSpec, Trigger, clicked,
|
||||
Bind, BodyCx, EditResponse, MemoProps, MemoView, Outbox, Outcome, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _, TooltipSpec,
|
||||
Trigger, clicked,
|
||||
};
|
||||
use craft_ui::display::Divider;
|
||||
use craft_ui::form::SliderField;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::menu::{Menu, MenuItem};
|
||||
use craft_ui::patterns::presets::{
|
||||
CellShape, PickerField, PresetBrowser, PresetEvent, PresetFooterOptions, PresetPicker, PresetRow, PresetState, PresetView, PreviewPaint,
|
||||
CellShape, PickerField, PresetBrowser, PresetEvent, PresetFooterOptions, PresetPicker, PresetSource, PresetState, PresetView, PreviewPaint,
|
||||
};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind};
|
||||
@@ -30,7 +31,7 @@ use crate::ui::brush_settings::{BrushSizeField, TipAngle, TipEllipse};
|
||||
const DEFAULT_MAX_DIAMETER: f64 = 5000.0;
|
||||
|
||||
/// The brush values the picker's head edits, given by the app each pass.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct BrushPickerValues {
|
||||
/// The diameter in pixels: the Size field and its log slider.
|
||||
@@ -103,21 +104,13 @@ pub enum GearSection {
|
||||
End,
|
||||
}
|
||||
|
||||
type GearRowsFn<'a> = Box<dyn FnMut(&mut Ui, GearSection) + 'a>;
|
||||
|
||||
/// The app's own rows of the gear menu: called once per [`GearSection`], after the picker's rows of that section.
|
||||
pub struct GearRows<'a>(GearRowsFn<'a>);
|
||||
|
||||
impl<'a> GearRows<'a> {
|
||||
/// The rows that `show` adds to each section.
|
||||
pub fn new(show: impl FnMut(&mut Ui, GearSection) + 'a) -> Self {
|
||||
GearRows(Box::new(show))
|
||||
}
|
||||
}
|
||||
/// The app's own rows of the gear menu: called once per [`GearSection`], after the picker's rows of that section. A
|
||||
/// `fn`, which captures nothing, so the picker's tools view keys it by its address.
|
||||
pub type GearRows = fn(&mut Ui, GearSection);
|
||||
|
||||
/// The picker's state, kept by the host while the app runs: the browser's view (search, open groups, scale), the
|
||||
/// parts the presets show and whether the search field shows. [`settings`](Self::settings) is what persists.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct BrushPickerState<K> {
|
||||
/// The browser's view settings; its zoom is the thumbnail scale.
|
||||
@@ -233,7 +226,8 @@ impl Opened {
|
||||
/// brush live and report [`BrushPresetPickerOutput::tip`], [`diameter`](BrushPresetPickerOutput::diameter) and
|
||||
/// [`hardness`](BrushPresetPickerOutput::hardness).
|
||||
/// - **Search row.** The browser's search field (any letter case, groups open while filtering) unless Show Search
|
||||
/// Bar is off, then at its reading end the Brush Settings and New Brush Preset buttons and the gear.
|
||||
/// Bar is off, then at its reading end the Brush Settings and New Brush Preset buttons and the gear. The popover
|
||||
/// opens with the focus in the search field, so typing filters the presets.
|
||||
/// - **Gear menu.** New Brush Preset…; Rename Brush… (opens the name field on the current preset) and Delete Brush…
|
||||
/// (enabled with a current preset); the Brush Name, Brush Stroke and Brush Tip boxes (at least one stays on); Show
|
||||
/// Search Bar; Import Brushes… with [`import`](Self::import). The app adds its own rows to each section with
|
||||
@@ -251,10 +245,10 @@ impl Opened {
|
||||
#[must_use = "show the picker with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
|
||||
#[pattern(probe(BrushPresetPicker<'static, u32>))]
|
||||
pub struct BrushPresetPicker<'a, K: Value + Eq + Hash> {
|
||||
pub struct BrushPresetPicker<'a, K: Value + Eq + Hash + MemoProps> {
|
||||
label: Label,
|
||||
current: Bind<'a, Option<K>>,
|
||||
rows: &'a [PresetRow<K>],
|
||||
source: &'a PresetSource<'a, K>,
|
||||
state: Bind<'a, BrushPickerState<K>>,
|
||||
values: BrushPickerValues,
|
||||
/// The largest diameter the app's engine paints; 5000 until set.
|
||||
@@ -264,8 +258,8 @@ pub struct BrushPresetPicker<'a, K: Value + Eq + Hash> {
|
||||
#[prop(flag)]
|
||||
import: bool,
|
||||
/// The app's rows of the gear menu, added to each section.
|
||||
#[prop(func = "FnMut(&mut Ui, GearSection)")]
|
||||
gear_rows: Option<GearRows<'a>>,
|
||||
#[prop]
|
||||
gear_rows: Option<GearRows>,
|
||||
/// Edge grips resize the popover, and the size the user leaves it at is saved under this key.
|
||||
#[prop]
|
||||
resizable: Option<SaveKey>,
|
||||
@@ -289,20 +283,20 @@ pub struct BrushPresetPicker<'a, K: Value + Eq + Hash> {
|
||||
/// The app's own rows of the picker's gear menu.
|
||||
type AppRows<'a> = Box<dyn FnOnce(&mut Ui) + 'a>;
|
||||
|
||||
impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
|
||||
/// A picker named `label` over the presets in `rows` (build each with [`brush_row`](super::brush_row)), holding the
|
||||
/// preset the brush was picked from in `current`, its view in `state` and the brush's `values`.
|
||||
impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
/// A picker named `label` over the presets of `source` (build each row with [`brush_row`](super::brush_row)),
|
||||
/// holding the preset the brush was picked from in `current`, its view in `state` and the brush's `values`.
|
||||
pub fn new(
|
||||
label: impl Into<Label>,
|
||||
current: Bind<'a, Option<K>>,
|
||||
rows: &'a [PresetRow<K>],
|
||||
source: &'a PresetSource<'a, K>,
|
||||
state: Bind<'a, BrushPickerState<K>>,
|
||||
values: BrushPickerValues,
|
||||
) -> Self {
|
||||
Self {
|
||||
label: label.into(),
|
||||
current,
|
||||
rows,
|
||||
source,
|
||||
state,
|
||||
values,
|
||||
max_diameter: DEFAULT_MAX_DIAMETER,
|
||||
@@ -329,12 +323,12 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
|
||||
let BrushPresetPicker {
|
||||
label,
|
||||
mut current,
|
||||
rows,
|
||||
source,
|
||||
mut state,
|
||||
values,
|
||||
max_diameter,
|
||||
import,
|
||||
mut gear_rows,
|
||||
gear_rows,
|
||||
resizable,
|
||||
mut opened_at,
|
||||
compact,
|
||||
@@ -355,116 +349,45 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
|
||||
Some(Mixed::Same(held)) => held,
|
||||
_ => None,
|
||||
};
|
||||
let has_current = held.as_ref().is_some_and(|key| rows.iter().any(|row| !row.is_group() && row.key == *key));
|
||||
let has_current = held.as_ref().is_some_and(|key| source.rows(ui.ctx(), &env).iter().any(|row| !row.is_group() && row.key == *key));
|
||||
let mut browser = before.browser.clone();
|
||||
let next_parts = Cell::new(parts);
|
||||
let next_search = Cell::new(before.search);
|
||||
let tool_picks: RefCell<Vec<BrushPick<K>>> = RefCell::new(Vec::new());
|
||||
let (mut diameter, mut hardness, mut tip) = (EditEvents::new(), EditEvents::new(), EditEvents::new());
|
||||
let browser_id = ui.scope_id().with("browser");
|
||||
let has_app_rows = gear_rows.is_some();
|
||||
let head = |ui: &mut Ui, _: &mut BodyCx<'_>| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
tip = match values.tip {
|
||||
Some(angle) => TipEllipse::new(words.tip.clone(), Bind::given(angle)).show(ui).events,
|
||||
None => EditEvents::new(),
|
||||
};
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
let size = BrushSizeField::new(words.size.clone(), Bind::given(values.diameter), max_diameter).show(ui);
|
||||
diameter = size.edit.events;
|
||||
hardness = EditEvents::new();
|
||||
if let Some(value) = values.hardness {
|
||||
let field = SliderField::new(words.hardness.clone(), Bind::given(value * 100.0), 0.0..=100.0)
|
||||
.step(1.0)
|
||||
.unit_kind(UnitKind::Percent)
|
||||
.show(ui);
|
||||
hardness = field.edit.events.map(|percent| (percent / 100.0).clamp(0.0, 1.0));
|
||||
}
|
||||
});
|
||||
});
|
||||
Divider::horizontal().show(ui);
|
||||
let mut sent = Vec::new();
|
||||
let props = HeadProps { values, max_diameter, sent: Outbox::new(&mut sent) };
|
||||
let _ = MemoView::new("head", props, head_view).show(ui);
|
||||
for edits in sent {
|
||||
(diameter, hardness, tip) = (edits.diameter, edits.hardness, edits.tip);
|
||||
}
|
||||
if let Some(rows) = app_rows.take() {
|
||||
rows(ui);
|
||||
}
|
||||
};
|
||||
// The buttons and the gear at the reading end of the browser's search row.
|
||||
let tools = |ui: &mut Ui| {
|
||||
let mut picks = tool_picks.borrow_mut();
|
||||
picks.clear();
|
||||
next_parts.set(parts);
|
||||
next_search.set(before.search);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let icon = |name: &'static str| IconSpec::svg(IconId::new(name));
|
||||
let settings = IconButton::new(icon("adjustments")).label(words.settings.clone()).tooltip(words.settings.clone()).show(ui);
|
||||
if clicked(&settings) {
|
||||
picks.push(BrushPick::OpenSettings);
|
||||
}
|
||||
let new_preset = IconButton::new(icon("plus")).label(words.new_preset.clone()).tooltip(words.new_preset.clone()).show(ui);
|
||||
if clicked(&new_preset) {
|
||||
picks.push(BrushPick::NewPreset);
|
||||
}
|
||||
let gear = IconButton::new(icon("settings")).label(words.options.clone()).tooltip(words.options.clone()).show(ui);
|
||||
let _ = Menu::new(words.options.clone()).opened_by(&gear, Trigger::Click).show(ui, |ui, _| {
|
||||
let mut app_rows = |ui: &mut Ui, section: GearSection| {
|
||||
if let Some(rows) = gear_rows.as_mut() {
|
||||
(rows.0)(ui, section);
|
||||
}
|
||||
};
|
||||
if MenuItem::new(words.menu_new.clone()).show(ui).ran {
|
||||
picks.push(BrushPick::NewPreset);
|
||||
}
|
||||
app_rows(ui, GearSection::Create);
|
||||
Divider::horizontal().show(ui);
|
||||
let on_current = |row: MenuItem<'static>| {
|
||||
let row = row.enabled(has_current);
|
||||
if has_current {
|
||||
row
|
||||
} else {
|
||||
row.tooltip(TooltipSpec::new(words.no_current.clone()).disabled_text(words.no_current.clone()))
|
||||
}
|
||||
};
|
||||
if on_current(MenuItem::new(words.menu_rename.clone())).show(ui).ran
|
||||
&& let Some(key) = held.as_ref()
|
||||
{
|
||||
PresetBrowser::request_rename(ui.ctx(), browser_id, key);
|
||||
}
|
||||
if on_current(MenuItem::new(words.menu_delete.clone())).show(ui).ran
|
||||
&& let Some(key) = held.clone()
|
||||
{
|
||||
picks.push(BrushPick::List(PresetEvent::Delete(key)));
|
||||
}
|
||||
app_rows(ui, GearSection::Preset);
|
||||
Divider::horizontal().show(ui);
|
||||
for (part, label) in [
|
||||
(BrushCardPart::Name, &words.part_name),
|
||||
(BrushCardPart::Stroke, &words.part_stroke),
|
||||
(BrushCardPart::Tip, &words.part_tip),
|
||||
] {
|
||||
let on = next_parts.get().get(part);
|
||||
if MenuItem::new(label.clone()).check(on).keep_open(true).show(ui).ran {
|
||||
next_parts.set(next_parts.get().set(part, !on));
|
||||
}
|
||||
}
|
||||
app_rows(ui, GearSection::Parts);
|
||||
Divider::horizontal().show(ui);
|
||||
let search = next_search.get();
|
||||
if MenuItem::new(words.search_bar.clone()).check(search).keep_open(true).show(ui).ran {
|
||||
next_search.set(!search);
|
||||
}
|
||||
app_rows(ui, GearSection::View);
|
||||
Divider::horizontal().show(ui);
|
||||
if import && MenuItem::new(words.menu_import.clone()).show(ui).ran {
|
||||
picks.push(BrushPick::Import);
|
||||
}
|
||||
app_rows(ui, GearSection::Library);
|
||||
if has_app_rows {
|
||||
Divider::horizontal().show(ui);
|
||||
app_rows(ui, GearSection::End);
|
||||
}
|
||||
});
|
||||
});
|
||||
let mut sent = Vec::new();
|
||||
let props = ToolsProps {
|
||||
has_current,
|
||||
held: held.clone(),
|
||||
parts,
|
||||
search: before.search,
|
||||
import,
|
||||
browser_id,
|
||||
gear_rows,
|
||||
sent: Outbox::new(&mut sent),
|
||||
};
|
||||
let _ = MemoView::new("tools", props, tools_view::<K>).show(ui);
|
||||
for run in sent {
|
||||
*tool_picks.borrow_mut() = run.picks;
|
||||
next_parts.set(run.parts);
|
||||
next_search.set(run.search);
|
||||
}
|
||||
};
|
||||
let mut picker = PresetPicker::new(words.picker.clone(), current.reborrowed(), rows, Bind::bound(&mut browser))
|
||||
let mut picker = PresetPicker::new(words.picker.clone(), current.reborrowed(), source, Bind::bound(&mut browser))
|
||||
.field(PickerField::Chip)
|
||||
.caption(NumberCodec::new(env.units().reader(None), 0).format(&Some(values.diameter.round())))
|
||||
.caption_range((1.0..=max_diameter.round(), 0))
|
||||
@@ -531,6 +454,141 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every input of the picker's head: the brush values it shows and the largest diameter, and an outbox for its edits.
|
||||
#[derive(MemoProps)]
|
||||
struct HeadProps<'a> {
|
||||
values: BrushPickerValues,
|
||||
max_diameter: f64,
|
||||
sent: Outbox<'a, HeadEdits>,
|
||||
}
|
||||
|
||||
/// What a run of the head reports: the Size, Hardness and angle widget edits.
|
||||
struct HeadEdits {
|
||||
diameter: EditEvents<f64>,
|
||||
hardness: EditEvents<f64>,
|
||||
tip: EditEvents<TipAngle>,
|
||||
}
|
||||
|
||||
/// The head: the angle widget, Size and Hardness, then a divider. A memoized view, so a drag of its Size runs it
|
||||
/// alone and the presets below replay.
|
||||
fn head_view(props: &mut HeadProps<'_>, ui: &mut Ui) {
|
||||
let words = Env::of(ui).words::<BrushPresetWords>();
|
||||
let (values, max_diameter) = (props.values, props.max_diameter);
|
||||
let mut edits = HeadEdits { diameter: EditEvents::new(), hardness: EditEvents::new(), tip: EditEvents::new() };
|
||||
Row::new().show(ui, |ui, _| {
|
||||
if let Some(angle) = values.tip {
|
||||
edits.tip = TipEllipse::new(words.tip.clone(), Bind::given(angle)).show(ui).events;
|
||||
}
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
edits.diameter = BrushSizeField::new(words.size.clone(), Bind::given(values.diameter), max_diameter).show(ui).edit.events;
|
||||
if let Some(value) = values.hardness {
|
||||
let field =
|
||||
SliderField::new(words.hardness.clone(), Bind::given(value * 100.0), 0.0..=100.0).step(1.0).unit_kind(UnitKind::Percent).show(ui);
|
||||
edits.hardness = field.edit.events.map(|percent| (percent / 100.0).clamp(0.0, 1.0));
|
||||
}
|
||||
});
|
||||
});
|
||||
Divider::horizontal().show(ui);
|
||||
props.sent.send(edits);
|
||||
}
|
||||
|
||||
/// Every input of the search row's buttons and gear menu, and an outbox for what a run reports.
|
||||
#[derive(MemoProps)]
|
||||
struct ToolsProps<'a, K: 'static> {
|
||||
has_current: bool,
|
||||
held: Option<K>,
|
||||
parts: BrushCardParts,
|
||||
search: bool,
|
||||
import: bool,
|
||||
browser_id: egui::Id,
|
||||
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
|
||||
gear_rows: Option<GearRows>,
|
||||
sent: Outbox<'a, ToolsRun<K>>,
|
||||
}
|
||||
|
||||
/// What a run of the search row's tools reports: the picks, and the parts and Show Search Bar as the gear left them.
|
||||
struct ToolsRun<K> {
|
||||
picks: Vec<BrushPick<K>>,
|
||||
parts: BrushCardParts,
|
||||
search: bool,
|
||||
}
|
||||
|
||||
/// The Brush Settings and New Brush Preset buttons and the gear menu. A memoized view: it runs while its menu is
|
||||
/// open, and replays while nothing it shows changes.
|
||||
fn tools_view<K: Value + Eq + Hash + MemoProps>(props: &mut ToolsProps<'_, K>, ui: &mut Ui) {
|
||||
let words = Env::of(ui).words::<BrushPresetWords>();
|
||||
let ToolsProps { has_current, ref held, parts, search, import, browser_id, gear_rows, .. } = *props;
|
||||
let held = held.clone();
|
||||
let mut picks = Vec::new();
|
||||
let next_parts = Cell::new(parts);
|
||||
let next_search = Cell::new(search);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let icon = |name: &'static str| IconSpec::svg(IconId::new(name));
|
||||
let settings = IconButton::new(icon("adjustments")).label(words.settings.clone()).tooltip(words.settings.clone()).show(ui);
|
||||
if clicked(&settings) {
|
||||
picks.push(BrushPick::OpenSettings);
|
||||
}
|
||||
let new_preset = IconButton::new(icon("plus")).label(words.new_preset.clone()).tooltip(words.new_preset.clone()).show(ui);
|
||||
if clicked(&new_preset) {
|
||||
picks.push(BrushPick::NewPreset);
|
||||
}
|
||||
let gear = IconButton::new(icon("settings")).label(words.options.clone()).tooltip(words.options.clone()).show(ui);
|
||||
let _ = Menu::new(words.options.clone()).opened_by(&gear, Trigger::Click).show(ui, |ui, _| {
|
||||
let app_rows = |ui: &mut Ui, section: GearSection| {
|
||||
if let Some(rows) = gear_rows {
|
||||
rows(ui, section);
|
||||
}
|
||||
};
|
||||
if MenuItem::new(words.menu_new.clone()).show(ui).ran {
|
||||
picks.push(BrushPick::NewPreset);
|
||||
}
|
||||
app_rows(ui, GearSection::Create);
|
||||
Divider::horizontal().show(ui);
|
||||
let on_current = |row: MenuItem<'static>| {
|
||||
let row = row.enabled(has_current);
|
||||
if has_current { row } else { row.tooltip(TooltipSpec::new(words.no_current.clone()).disabled_text(words.no_current.clone())) }
|
||||
};
|
||||
if on_current(MenuItem::new(words.menu_rename.clone())).show(ui).ran
|
||||
&& let Some(key) = held.as_ref()
|
||||
{
|
||||
PresetBrowser::request_rename(ui.ctx(), browser_id, key);
|
||||
}
|
||||
if on_current(MenuItem::new(words.menu_delete.clone())).show(ui).ran
|
||||
&& let Some(key) = held.clone()
|
||||
{
|
||||
picks.push(BrushPick::List(PresetEvent::Delete(key)));
|
||||
}
|
||||
app_rows(ui, GearSection::Preset);
|
||||
Divider::horizontal().show(ui);
|
||||
for (part, label) in
|
||||
[(BrushCardPart::Name, &words.part_name), (BrushCardPart::Stroke, &words.part_stroke), (BrushCardPart::Tip, &words.part_tip)]
|
||||
{
|
||||
let on = next_parts.get().get(part);
|
||||
if MenuItem::new(label.clone()).check(on).keep_open(true).show(ui).ran {
|
||||
next_parts.set(next_parts.get().set(part, !on));
|
||||
}
|
||||
}
|
||||
app_rows(ui, GearSection::Parts);
|
||||
Divider::horizontal().show(ui);
|
||||
let shown = next_search.get();
|
||||
if MenuItem::new(words.search_bar.clone()).check(shown).keep_open(true).show(ui).ran {
|
||||
next_search.set(!shown);
|
||||
}
|
||||
app_rows(ui, GearSection::View);
|
||||
Divider::horizontal().show(ui);
|
||||
if import && MenuItem::new(words.menu_import.clone()).show(ui).ran {
|
||||
picks.push(BrushPick::Import);
|
||||
}
|
||||
app_rows(ui, GearSection::Library);
|
||||
if gear_rows.is_some() {
|
||||
Divider::horizontal().show(ui);
|
||||
app_rows(ui, GearSection::End);
|
||||
}
|
||||
});
|
||||
});
|
||||
props.sent.send(ToolsRun { picks, parts: next_parts.get(), search: next_search.get() });
|
||||
}
|
||||
|
||||
/// Keeps what Escape goes back to while the popover is open and returns the values Escape sets back, if any.
|
||||
///
|
||||
/// The pass the popover shows open first takes `values` as the opening values; the head's edits become the values
|
||||
|
||||
@@ -23,7 +23,7 @@ pub enum BrushCardPart {
|
||||
///
|
||||
/// - The tip alone is the browser's grid of thumbnails with the size as each caption.
|
||||
/// - The name or the stroke is the browser's list: the stroke as the row's picture while it is on, else the tip.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[serde(default)]
|
||||
#[non_exhaustive]
|
||||
pub struct BrushCardParts {
|
||||
@@ -80,7 +80,7 @@ impl BrushCardParts {
|
||||
/// scale. The app saves it in its settings (serde) when
|
||||
/// [`BrushPresetPickerOutput::settings`](super::BrushPresetPickerOutput::settings) is set and restores it with
|
||||
/// [`BrushPickerState::restore`]; the search text, open groups and an open rename are not saved.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui::contract::MemoProps)]
|
||||
#[serde(default)]
|
||||
#[non_exhaustive]
|
||||
pub struct BrushPickerSettings {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Stories of the Brush Preset picker.
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::pictures::{SampleTip, paint_tip, paint_wave};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
@@ -28,7 +28,8 @@ fn paint(tip: SampleTip) -> BrushRowPaint {
|
||||
)
|
||||
}
|
||||
|
||||
fn rows(env: &Env, parts: BrushCardParts) -> Vec<PresetRow<u32>> {
|
||||
fn rows(parts: &BrushCardParts, env: &Env) -> Vec<PresetRow<u32>> {
|
||||
let parts = *parts;
|
||||
vec![
|
||||
brush_row(SOFT, "Soft Round", 0, SOFT_SIZE, parts, env, &paint(SampleTip::Soft)),
|
||||
brush_row(HARD, "Hard Round", 0, HARD_SIZE, parts, env, &paint(SampleTip::Hard)),
|
||||
@@ -37,11 +38,10 @@ fn rows(env: &Env, parts: BrushCardParts) -> Vec<PresetRow<u32>> {
|
||||
|
||||
#[story(BrushPresetPicker<'static, u32>, covers = [Default], drive = Drive::Never)]
|
||||
fn picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let env = Env::of(ui);
|
||||
let ((current, state), brush_at) = data.value_at("brush", (Some(SOFT), BrushPickerState::<u32>::new()));
|
||||
let rows = rows(&env, state.parts);
|
||||
let source = PresetSource::new(state.parts, PresetFns::new(rows));
|
||||
let values = BrushPickerValues::new(SOFT_SIZE, Some(0.8));
|
||||
BrushPresetPicker::new("Brush Preset picker", brush_at.bind(current), &rows, brush_at.bind(state), values)
|
||||
BrushPresetPicker::new("Brush Preset picker", brush_at.bind(current), &source, brush_at.bind(state), values)
|
||||
.max_diameter(MAX_SIZE)
|
||||
.import()
|
||||
.show(ui)
|
||||
@@ -52,12 +52,11 @@ fn picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
/// and Hardness in the head.
|
||||
#[story(BrushPresetPicker<'static, u32>, covers = [Open], drive = Drive::Never)]
|
||||
fn picker_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let env = Env::of(ui);
|
||||
let at = ui.max_rect().min;
|
||||
let ((current, state, open), open_at2) = data.value_at("open", (Some(SOFT), BrushPickerState::<u32>::new(), true));
|
||||
let rows = rows(&env, state.parts);
|
||||
let source = PresetSource::new(state.parts, PresetFns::new(rows));
|
||||
let values = BrushPickerValues::new(SOFT_SIZE, Some(0.8)).with_tip(TipAngle::new(30.0, 0.6));
|
||||
BrushPresetPicker::new("Brush Preset picker", open_at2.bind(current), &rows, open_at2.bind(state), values)
|
||||
BrushPresetPicker::new("Brush Preset picker", open_at2.bind(current), &source, open_at2.bind(state), values)
|
||||
.max_diameter(MAX_SIZE)
|
||||
.import()
|
||||
.open_at(at, open_at2.bind(open))
|
||||
@@ -67,27 +66,24 @@ fn picker_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
|
||||
#[story(BrushesPanel<'static, u32>, covers = [Default], drive = Drive::Never)]
|
||||
fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let env = Env::of(ui);
|
||||
let ((state, diameter), panel_at) = data.value_at("panel", (PresetState::<u32>::new(), SOFT_SIZE));
|
||||
let rows = rows(&env, BrushCardParts::ALL);
|
||||
BrushesPanel::new("Brushes", &rows, panel_at.bind(state), panel_at.bind(diameter), MAX_SIZE).selected(SOFT).import(true).show(ui).into()
|
||||
let source = PresetSource::new(BrushCardParts::ALL, PresetFns::new(rows));
|
||||
BrushesPanel::new("Brushes", &source, panel_at.bind(state), panel_at.bind(diameter), MAX_SIZE).selected(SOFT).import(true).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(BrushPresetPicker<'static, u32>, covers = [Mixed], drive = Drive::Never)]
|
||||
fn picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let env = Env::of(ui);
|
||||
let ((current, state), mixed_at) = data.value_at("mixed", (Mixed::<Option<u32>>::Mixed, BrushPickerState::<u32>::new()));
|
||||
let rows = rows(&env, state.parts);
|
||||
let source = PresetSource::new(state.parts, PresetFns::new(rows));
|
||||
let values = BrushPickerValues::new(HARD_SIZE, None);
|
||||
BrushPresetPicker::new("Brush Preset picker", mixed_at.bind_mixed(current), &rows, mixed_at.bind(state), values).show(ui).into()
|
||||
BrushPresetPicker::new("Brush Preset picker", mixed_at.bind_mixed(current), &source, mixed_at.bind(state), values).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(BrushPresetPicker<'static, u32>, covers = [], drive = Drive::Never)]
|
||||
fn picker_sampled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let env = Env::of(ui);
|
||||
let ((current, state), sampled_at) = data.value_at("sampled", (Some(HARD), BrushPickerState::<u32>::new()));
|
||||
let rows = rows(&env, state.parts);
|
||||
BrushPresetPicker::new("Brush Preset picker", sampled_at.bind(current), &rows, sampled_at.bind(state), BrushPickerValues::new(HARD_SIZE, None))
|
||||
let source = PresetSource::new(state.parts, PresetFns::new(rows));
|
||||
BrushPresetPicker::new("Brush Preset picker", sampled_at.bind(current), &source, sampled_at.bind(state), BrushPickerValues::new(HARD_SIZE, None))
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
@@ -95,7 +91,8 @@ fn picker_sampled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
#[story(BrushPresetPicker<'static, u32>, covers = [], drive = Drive::Never)]
|
||||
fn picker_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let ((current, state), empty_at) = data.value_at("empty", (None::<u32>, BrushPickerState::<u32>::new()));
|
||||
BrushPresetPicker::new("Brush Preset picker", empty_at.bind(current), &[], empty_at.bind(state), BrushPickerValues::new(SOFT_SIZE, Some(1.0)))
|
||||
let source = PresetSource::new((), PresetFns::new(|_, _| Vec::new()));
|
||||
BrushPresetPicker::new("Brush Preset picker", empty_at.bind(current), &source, empty_at.bind(state), BrushPickerValues::new(SOFT_SIZE, Some(1.0)))
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ const ROUND_STEP: f64 = 0.01;
|
||||
const ROUND_MIN: f64 = 0.01;
|
||||
|
||||
/// A tip's angle and roundness.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct TipAngle {
|
||||
/// The major axis's angle in whole degrees, counter-clockwise from the right, −180 to 180.
|
||||
@@ -235,12 +235,12 @@ impl Component for TipEllipse<'_> {
|
||||
let value = cx.value().copied().unwrap_or_default();
|
||||
let dots = ellipse_handles(value, radius);
|
||||
cx.part(ARROW, HitShape::circle(center, disc))
|
||||
.sense(Sense::CLICK | Sense::DRAG)
|
||||
.sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS)
|
||||
.value_part()
|
||||
.pointer_only("the arrow keys turn the angle, Alt with them squashes the ellipse");
|
||||
for (at, dot) in dots.into_iter().enumerate() {
|
||||
cx.part(DOT.at(at as u64), HitShape::circle(center + dot, reach))
|
||||
.sense(Sense::CLICK | Sense::DRAG)
|
||||
.sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS)
|
||||
.priority(HitPriority::new(HitLevel::Handle, 0))
|
||||
.value_part()
|
||||
.pointer_only("Alt with the arrow keys squashes the ellipse");
|
||||
|
||||
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
|
||||
use super::fill_editor::GradientFillWords;
|
||||
|
||||
/// How a gradient runs from its line.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum GradientStyle {
|
||||
/// Along the line.
|
||||
|
||||
@@ -14,7 +14,7 @@ use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, Sh
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::presets::{PickerField, PresetPicker, PresetRow};
|
||||
use craft_ui::patterns::presets::{PickerField, PresetFns, PresetPicker, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::style::TypeRole;
|
||||
use egui::{Response, Ui};
|
||||
@@ -136,26 +136,18 @@ impl<'a> GradientMapEditor<'a> {
|
||||
(words.preset.clone(), words.custom.clone(), words.import_presets.clone(), words.stops.clone());
|
||||
let (reverse_label, dither_label) = (words.reverse.clone(), words.dither.clone());
|
||||
let shown = Stack::new().label(self.label.clone()).show(ui, |ui, cx| {
|
||||
let rows: Vec<PresetRow<GradientRef>> = self
|
||||
.presets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(group, g)| {
|
||||
let header = PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0);
|
||||
let items =
|
||||
g.items.iter().enumerate().map(move |(item, p)| PresetRow::item(GradientRef::Item { group, item }, p.name.clone(), 1));
|
||||
std::iter::once(header).chain(items)
|
||||
})
|
||||
.collect();
|
||||
let source = PresetSource::new(self.presets, PresetFns::new(preset_rows));
|
||||
// Stop tags identify host data, so they do not determine which preset's colours match.
|
||||
let matches = |&key: &GradientRef| {
|
||||
self.preset_colors(key).is_some_and(|colors| colors.map(|s| s.with_tag(0)).eq(base.stops.color.iter().map(|s| s.with_tag(0))))
|
||||
};
|
||||
let preferred = cx.keep::<PickedPreset>().0.filter(matches);
|
||||
let current = preferred.or_else(|| rows.iter().map(|row| row.key).find(matches));
|
||||
let mut items =
|
||||
self.presets.iter().enumerate().flat_map(|(group, g)| (0..g.items.len()).map(move |item| GradientRef::Item { group, item }));
|
||||
let current = preferred.or_else(|| items.find(matches));
|
||||
let picked = Field::new(preset_label.clone())
|
||||
.show(ui, |ui, _| {
|
||||
PresetPicker::new(preset_label.clone(), Bind::given(current), &rows, Bind::kept())
|
||||
PresetPicker::new(preset_label.clone(), Bind::given(current), &source, Bind::kept())
|
||||
.field(PickerField::Name)
|
||||
.placeholder(custom.clone())
|
||||
.show(ui)
|
||||
@@ -200,3 +192,16 @@ impl<'a> GradientMapEditor<'a> {
|
||||
GradientMapOutput { response: shown.output, event, color_requested, import }
|
||||
}
|
||||
}
|
||||
|
||||
/// The picker's rows: each group's header, then its presets. A header's key names no preset (`item == usize::MAX`).
|
||||
fn preset_rows(presets: &&[GradientGroup], _: &Env) -> Vec<PresetRow<GradientRef>> {
|
||||
presets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(group, g)| {
|
||||
let header = PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0);
|
||||
let items = g.items.iter().enumerate().map(move |(item, p)| PresetRow::item(GradientRef::Item { group, item }, p.name.clone(), 1));
|
||||
std::iter::once(header).chain(items)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -21,6 +21,6 @@ pub use fill_editor::{GradientFillEditor, GradientFillEditorOutput, GradientFill
|
||||
pub use gradient_line::{GradientLine, LineGradient, LinePart};
|
||||
pub use gradient_overlay::{GradientLineWords, GradientOverlay, GradientOverlayOutput, GradientOverlayStyle};
|
||||
pub use map::{GradientMap, GradientMapEditor, GradientMapOutput};
|
||||
pub use palette::{GradientGroup, GradientItem, GradientPalette, GradientPaletteOutput, GradientRef};
|
||||
pub use palette::{GradientGroup, GradientItem, GradientPalette, GradientPaletteOutput, GradientRef, RampSampler};
|
||||
pub use swatch::{GradientSwatch, GradientSwatchOutput};
|
||||
pub use tile::{FocusOutline, GradientTile};
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
//! family's [`PresetBrowser`]: the browser owns the grid, the list, the roving focus, the keys and the accessible tree;
|
||||
//! the palette supplies the rows and paints each preset's thumbnail as a gradient ramp.
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, NoValue, Outcome, Pattern};
|
||||
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetEvent, PresetRow, PresetState, PresetTiles};
|
||||
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetSource, PresetState, PresetTiles, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use egui::{Response, Ui};
|
||||
use egui::{Rect, Response, Ui};
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
@@ -18,7 +20,7 @@ use super::GradientTile;
|
||||
const MAX_ROWS: f32 = 6.0;
|
||||
|
||||
/// A named group of gradient presets.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientGroup {
|
||||
/// The group's heading.
|
||||
@@ -35,7 +37,7 @@ impl GradientGroup {
|
||||
}
|
||||
|
||||
/// A named gradient preset.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientItem {
|
||||
/// The preset's name.
|
||||
@@ -62,7 +64,7 @@ impl GradientItem {
|
||||
|
||||
/// The preset a pick names: a recent gradient by its place in the list the host passed, or an
|
||||
/// item of a group.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum GradientRef {
|
||||
/// Place in the Recent list.
|
||||
@@ -163,9 +165,10 @@ pub struct GradientPalette<'a> {
|
||||
/// The row layout the ramps are sampled with.
|
||||
#[prop]
|
||||
rows: StopRows,
|
||||
/// Samples a ramp; the default sampler of the rows by default.
|
||||
/// Samples a ramp; the default sampler of the rows by default. A `fn`, which captures nothing, so the palette's
|
||||
/// presets key it by its address.
|
||||
#[prop]
|
||||
sampler: Option<&'a Sampler>,
|
||||
sampler: Option<RampSampler>,
|
||||
/// The selected preset.
|
||||
#[prop]
|
||||
selected: Option<GradientRef>,
|
||||
@@ -186,55 +189,17 @@ impl<'a> GradientPalette<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the groups: the header of each group, then its presets. A header's key names no preset
|
||||
/// (`item == usize::MAX`).
|
||||
fn preset_rows(&self) -> Vec<PresetRow<GradientRef>> {
|
||||
let mut rows = Vec::new();
|
||||
if !self.recent.is_empty() {
|
||||
rows.push(PresetRow::group(GradientRef::Recent(usize::MAX), self.recent_label.clone(), 0));
|
||||
for i in 0..self.recent.len() {
|
||||
rows.push(PresetRow::item(GradientRef::Recent(i), format!("{} {}", self.recent_label, i + 1), 1));
|
||||
}
|
||||
}
|
||||
for (group, g) in self.groups.iter().enumerate() {
|
||||
rows.push(PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0));
|
||||
for (item, preset) in g.items.iter().enumerate() {
|
||||
rows.push(PresetRow::item(GradientRef::Item { group, item }, preset.name.clone(), 1));
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Shows the palette across the available width.
|
||||
pub fn show(self, ui: &mut Ui) -> GradientPaletteOutput {
|
||||
let rows = self.preset_rows();
|
||||
let default = default_sampler(self.rows);
|
||||
let sampler: &Sampler = self.sampler.unwrap_or(&default);
|
||||
let (groups, recent) = (self.groups, self.recent);
|
||||
let (wide, high) = GradientRamp::CHIP_ASPECT;
|
||||
// The browser has one cell shape for the grid and the list, so any tile makes every cell square.
|
||||
let square = groups.iter().flat_map(|g| &g.items).any(|item| item.tile != GradientTile::Ramp);
|
||||
let thumb =
|
||||
move |cx: &craft_ui::primitives::ContentPainterCx, rect: egui::Rect, info: craft_ui::patterns::presets::ThumbInfo<'_, GradientRef>| {
|
||||
if let Some(stops) = stops_of(groups, recent, *info.key) {
|
||||
let (radius, edge) = GradientRamp::chip_look(&cx.style_cx());
|
||||
let tile = item_of(groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile);
|
||||
if tile != GradientTile::Ramp {
|
||||
tile.paint(cx, rect, radius, stops, sampler, edge);
|
||||
return;
|
||||
}
|
||||
let chip = if square {
|
||||
egui::Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide)))
|
||||
} else {
|
||||
rect
|
||||
};
|
||||
GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge);
|
||||
}
|
||||
};
|
||||
let inputs = PaletteInputs { groups, recent, recent_label: self.recent_label, rows: self.rows, sampler: self.sampler, square };
|
||||
let source = PresetSource::new(inputs, PresetFns::new(preset_rows).thumb(paint_thumb));
|
||||
let most = Env::of(ui).tokens.size.control.sm * MAX_ROWS;
|
||||
let shape = if square { CellShape::Square } else { CellShape::ratio(wide, high) };
|
||||
let mut browser =
|
||||
PresetBrowser::new(self.label, self.state, &rows).cell_shape(shape).tiles(PresetTiles::Chips).room_height(most).thumb(thumb);
|
||||
let mut browser = PresetBrowser::new(self.label, self.state, &source).cell_shape(shape).tiles(PresetTiles::Chips).room_height(most);
|
||||
if let Some(selected) = self.selected {
|
||||
browser = browser.selected(selected);
|
||||
}
|
||||
@@ -251,6 +216,64 @@ impl<'a> GradientPalette<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples a gradient's ramp at a location 0..=1.
|
||||
pub type RampSampler = fn(&GradientStops, f32) -> Srgba;
|
||||
|
||||
/// What the palette's presets are built from.
|
||||
#[derive(craft_ui::contract::MemoProps)]
|
||||
struct PaletteInputs<'a> {
|
||||
groups: &'a [GradientGroup],
|
||||
recent: &'a [GradientStops],
|
||||
recent_label: String,
|
||||
rows: StopRows,
|
||||
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
|
||||
sampler: Option<RampSampler>,
|
||||
/// Whether every cell is square: some preset has a tile other than the ramp.
|
||||
square: bool,
|
||||
}
|
||||
|
||||
/// The rows of the groups: the header of each group, then its presets. A header's key names no preset
|
||||
/// (`item == usize::MAX`).
|
||||
fn preset_rows(inputs: &PaletteInputs<'_>, _: &Env) -> Vec<PresetRow<GradientRef>> {
|
||||
let mut rows = Vec::new();
|
||||
if !inputs.recent.is_empty() {
|
||||
rows.push(PresetRow::group(GradientRef::Recent(usize::MAX), inputs.recent_label.clone(), 0));
|
||||
for i in 0..inputs.recent.len() {
|
||||
rows.push(PresetRow::item(GradientRef::Recent(i), format!("{} {}", inputs.recent_label, i + 1), 1));
|
||||
}
|
||||
}
|
||||
for (group, g) in inputs.groups.iter().enumerate() {
|
||||
rows.push(PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0));
|
||||
for (item, preset) in g.items.iter().enumerate() {
|
||||
rows.push(PresetRow::item(GradientRef::Item { group, item }, preset.name.clone(), 1));
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Paints a preset's thumbnail: its tile, or its ramp chip, which keeps the chip's aspect in a square cell.
|
||||
fn paint_thumb(inputs: &PaletteInputs<'_>, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, GradientRef>) {
|
||||
let Some(stops) = stops_of(inputs.groups, inputs.recent, *info.key) else { return };
|
||||
let (radius, edge) = GradientRamp::chip_look(&cx.style_cx());
|
||||
let default = default_sampler(inputs.rows);
|
||||
let sampler: &Sampler = match &inputs.sampler {
|
||||
Some(sampler) => sampler,
|
||||
None => &default,
|
||||
};
|
||||
let tile = item_of(inputs.groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile);
|
||||
if tile != GradientTile::Ramp {
|
||||
tile.paint(cx, rect, radius, stops, sampler, edge);
|
||||
return;
|
||||
}
|
||||
let (wide, high) = GradientRamp::CHIP_ASPECT;
|
||||
let chip = if inputs.square {
|
||||
Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide)))
|
||||
} else {
|
||||
rect
|
||||
};
|
||||
GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge);
|
||||
}
|
||||
|
||||
/// The stops of the preset `key` names; none for a group header.
|
||||
pub(super) fn stops_of<'a>(groups: &'a [GradientGroup], recent: &'a [GradientStops], key: GradientRef) -> Option<&'a GradientStops> {
|
||||
match key {
|
||||
|
||||
@@ -18,7 +18,7 @@ const TILE_STEPS: usize = 17;
|
||||
///
|
||||
/// A tile other than [`Ramp`](GradientTile::Ramp) is one `craft_color_ui::ui::smooth_mesh` sampled through
|
||||
/// [`t_at`](GradientTile::t_at). `p` below is a point in the tile's unit square (0 to 1, y down) and `c` its centre.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum GradientTile {
|
||||
/// The ramp chip: the gradient along its length.
|
||||
@@ -56,7 +56,7 @@ impl GradientTile {
|
||||
}
|
||||
|
||||
/// The outline a [`GradientTile::Focus`] gradient follows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum FocusOutline {
|
||||
/// A circle.
|
||||
|
||||
@@ -79,7 +79,7 @@ pub use crop::{
|
||||
pub use crop::{PerspectiveCropQuad, PerspectiveQuad};
|
||||
pub use gradient::{
|
||||
FocusOutline, GradientGroup, GradientItem, GradientLine, GradientMap, GradientMapEditor, GradientMapOutput, GradientOverlay, GradientPalette,
|
||||
GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart,
|
||||
GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart, RampSampler,
|
||||
};
|
||||
pub use gradient::{GradientFill, GradientFillEditor, GradientFillEditorOutput, GradientFillWords, GradientStyle};
|
||||
pub use measure::{
|
||||
@@ -89,9 +89,7 @@ pub use paint_bar::{
|
||||
EraserMode, MIXER_COMBINATIONS, MIXER_GROUP_STARTS, MixerValues, PaintBar, PaintBarOutput, PaintBarWords, PaintTool, PaintValues, Smoothing,
|
||||
};
|
||||
pub use paths::{PathKind, PathRow, PathsCommands, PathsEvent, PathsFooterButton, PathsOutput, PathsPanel, PathsWords};
|
||||
pub use pattern::{
|
||||
PatternColors, PatternFillDialog, PatternFillEditor, PatternFillOptions, PatternFillOutput, PatternSwatch, PatternWords, SwatchPainter,
|
||||
};
|
||||
pub use pattern::{PatternColors, PatternFillDialog, PatternFillEditor, PatternFillOptions, PatternFillOutput, PatternSwatch, PatternWords};
|
||||
pub use pen::{AnchorDelete, AnchorTool, PenEnd};
|
||||
pub use pen::{AnchorsShown, HitMark, PATH_OPTIONS_COLOR_KEY, PathMode, PathOptionsPopover, PathOptionsSettings, PathTool, PenMode, SegmentMark};
|
||||
pub use pen::{
|
||||
|
||||
@@ -30,7 +30,7 @@ pub use words::PaintBarWords;
|
||||
const PRESSURE: &str = "target";
|
||||
|
||||
/// The painting tools the bar serves.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum PaintTool {
|
||||
/// The Brush tool.
|
||||
@@ -43,14 +43,10 @@ pub enum PaintTool {
|
||||
MixerBrush,
|
||||
}
|
||||
|
||||
/// The bar's values.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
/// The bar's values. The size and the hardness are the preset picker's, which comes before the bar.
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct PaintValues<M> {
|
||||
/// The brush size.
|
||||
pub size: f64,
|
||||
/// The brush hardness.
|
||||
pub hardness: f64,
|
||||
/// The opacity.
|
||||
pub opacity: f64,
|
||||
/// The flow.
|
||||
@@ -78,8 +74,6 @@ impl<M> PaintValues<M> {
|
||||
/// options overwrites every field.
|
||||
pub fn new(mode: M) -> Self {
|
||||
PaintValues {
|
||||
size: 30.0,
|
||||
hardness: 0.5,
|
||||
opacity: 1.0,
|
||||
flow: 1.0,
|
||||
smoothing: Smoothing::default(),
|
||||
@@ -95,7 +89,7 @@ impl<M> PaintValues<M> {
|
||||
}
|
||||
|
||||
/// The stroke smoothing options.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct Smoothing {
|
||||
/// The amount, 0 to 1.
|
||||
@@ -118,7 +112,7 @@ impl Default for Smoothing {
|
||||
}
|
||||
|
||||
/// The Mixer Brush's values.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct MixerValues {
|
||||
/// Load the brush after each stroke.
|
||||
@@ -162,7 +156,7 @@ impl Default for MixerValues {
|
||||
}
|
||||
|
||||
/// What the Eraser tool erases with.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum EraserMode {
|
||||
/// A brush.
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
//! [`PatternFillDialog`].
|
||||
|
||||
use super::editor::{ANGLE_RANGE, SwatchPainter};
|
||||
use super::editor::ANGLE_RANGE;
|
||||
use super::{PatternColors, PatternFillEditor, PatternFillOptions, PatternSwatch, PatternWords};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, CanvasGesture, Sampler as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::form_dialogs::FormDialog;
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use egui::{Rect, Ui};
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Photoshop's Pattern Fill dialog (Layer, New Fill Layer, Pattern...; a Pattern Fill layer's thumbnail; Layer Content
|
||||
@@ -25,7 +24,6 @@ pub struct PatternFillDialog {
|
||||
initial: PatternFillOptions,
|
||||
current: PatternFillOptions,
|
||||
swatches: Vec<PatternSwatch>,
|
||||
thumbnails: Option<SwatchPainter>,
|
||||
changed: bool,
|
||||
canvas: Option<egui::Id>,
|
||||
/// Whether the dialog is open: bound to the form's open state, so the host's dialog closes with it.
|
||||
@@ -40,20 +38,12 @@ impl PatternFillDialog {
|
||||
initial: options.clone(),
|
||||
current: options,
|
||||
swatches,
|
||||
thumbnails: None,
|
||||
changed: false,
|
||||
canvas: None,
|
||||
open: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints a swatch's tile (see [`PatternFillEditor::thumbnails`]).
|
||||
#[must_use]
|
||||
pub fn thumbnails(mut self, paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self {
|
||||
self.thumbnails = Some(SwatchPainter::new(paint));
|
||||
self
|
||||
}
|
||||
|
||||
/// The canvas whose primary drag moves the pattern while Link with Layer is on: the body passes
|
||||
/// that gesture to it each pass.
|
||||
#[must_use]
|
||||
@@ -148,7 +138,7 @@ impl StackDialog for PatternFillDialog {
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<PatternFillOptions>> {
|
||||
let words = Env::of(ui).words::<PatternWords>();
|
||||
let PatternFillDialog { current, swatches, thumbnails, changed, canvas, open, .. } = self;
|
||||
let PatternFillDialog { current, swatches, changed, canvas, open, .. } = self;
|
||||
let before = current.clone();
|
||||
let form = FormDialog::new(words.title.clone(), Bind::bound(&mut *current)).opened(Bind::bound(open));
|
||||
let shown = form.show(ui, |ui, _, value| {
|
||||
@@ -159,11 +149,7 @@ impl StackDialog for PatternFillDialog {
|
||||
if let (Some(canvas), true) = (*canvas, link) {
|
||||
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
|
||||
}
|
||||
let mut editor = PatternFillEditor::new(words.pattern.clone(), Bind::bound(&mut *value), swatches);
|
||||
if let Some(painter) = thumbnails.clone() {
|
||||
editor = editor.thumbnails(move |cx, rect, swatch| painter.paint(cx, rect, swatch));
|
||||
}
|
||||
editor.show(ui);
|
||||
PatternFillEditor::new(words.pattern.clone(), Bind::bound(&mut *value), swatches).show(ui);
|
||||
});
|
||||
true
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ use craft_ui::contract::{Bind, FieldLayout, Outcome, Props as _, Remember as _,
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetPicker, PresetRow, PresetState, PresetView, ThumbInfo};
|
||||
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetFns, PresetPicker, PresetRow, PresetSource, PresetState, PresetView};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind};
|
||||
use craft_ui::text::NumberField;
|
||||
@@ -21,22 +21,6 @@ use egui::{Rect, Response, Ui};
|
||||
/// The angle of the dial runs over half a turn each way.
|
||||
pub(super) const ANGLE_RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
|
||||
|
||||
type SwatchPaintFn = Arc<dyn Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync>;
|
||||
|
||||
/// The host's painter of a swatch's tile, shared with the preset rows that paint it.
|
||||
#[derive(Clone)]
|
||||
pub struct SwatchPainter(SwatchPaintFn);
|
||||
|
||||
impl SwatchPainter {
|
||||
pub(super) fn new(paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self {
|
||||
SwatchPainter(Arc::new(paint))
|
||||
}
|
||||
|
||||
pub(super) fn paint(&self, cx: &ContentPainterCx<'_>, rect: Rect, swatch: &PatternSwatch) {
|
||||
(self.0)(cx, rect, swatch);
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`PatternFillEditor`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
@@ -67,7 +51,7 @@ impl Outcome for PatternFillOutput {
|
||||
/// Preset mode (`colors` set, PowerPoint's Pattern fill): a grid of the swatches, then Foreground and Background
|
||||
/// colour chips.
|
||||
///
|
||||
/// The tiles come from [`thumbnails`](Self::thumbnails); without it a tile shows the swatch's name. Keyboard: Tab
|
||||
/// A tile shows its swatch's [`picture`](PatternSwatch::picture); without one, the swatch's name. Keyboard: Tab
|
||||
/// through the fields; the grid takes arrows. Right to left the rows mirror. The editor is the body a host passes to
|
||||
/// a paint chip's pattern editor.
|
||||
#[must_use = "show the editor with `show`"]
|
||||
@@ -76,29 +60,22 @@ pub struct PatternFillEditor<'a> {
|
||||
label: Label,
|
||||
options: Bind<'a, PatternFillOptions>,
|
||||
swatches: &'a [PatternSwatch],
|
||||
thumbnails: Option<SwatchPainter>,
|
||||
}
|
||||
|
||||
impl<'a> PatternFillEditor<'a> {
|
||||
/// The editor named `label` over `options`, offering `swatches`.
|
||||
pub fn new(label: impl Into<Label>, options: Bind<'a, PatternFillOptions>, swatches: &'a [PatternSwatch]) -> Self {
|
||||
PatternFillEditor { label: label.into(), options, swatches, thumbnails: None }
|
||||
}
|
||||
|
||||
/// Paints a swatch's tile into a rect (the picker's field and cells, the preset grid).
|
||||
pub fn thumbnails(mut self, paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self {
|
||||
self.thumbnails = Some(SwatchPainter::new(paint));
|
||||
self
|
||||
PatternFillEditor { label: label.into(), options, swatches }
|
||||
}
|
||||
|
||||
/// Draws the editor and reports the edit.
|
||||
pub fn show(self, ui: &mut Ui) -> PatternFillOutput {
|
||||
let PatternFillEditor { label, mut options, swatches, thumbnails } = self;
|
||||
let PatternFillEditor { label, mut options, swatches } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<PatternWords>();
|
||||
let units = env.units();
|
||||
let name: Arc<str> = label.as_str().into();
|
||||
let rows: Vec<PresetRow<String>> = swatches.iter().map(|swatch| tile_row(swatch, thumbnails.as_ref())).collect();
|
||||
let rows = PresetSource::new(swatches, PresetFns::new(tile_rows));
|
||||
let mut events = EditEvents::new();
|
||||
let shown = FieldGroup::new(label).show(ui, |ui, cx| {
|
||||
events = EditEvents::new();
|
||||
@@ -108,20 +85,13 @@ impl<'a> PatternFillEditor<'a> {
|
||||
let mut take = |edits: EditEvents<PatternFillOptions>| next.extend(edits);
|
||||
if let Some(colors) = current.colors {
|
||||
let browser = Field::new(words.pattern.clone()).id_salt("grid").show(ui, |ui, _| {
|
||||
let thumbs = thumbnails.clone();
|
||||
let mut browser = PresetBrowser::new(words.pattern.clone(), Bind::bound(&mut state), &rows)
|
||||
PresetBrowser::new(words.pattern.clone(), Bind::bound(&mut state), &rows)
|
||||
.selected(current.pattern.clone())
|
||||
.cell_shape(CellShape::Square)
|
||||
.view_lock(PresetView::Grid)
|
||||
.row_menu(false);
|
||||
if let Some(thumbs) = thumbs {
|
||||
browser = browser.thumb(move |cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, String>| {
|
||||
if let Some(swatch) = swatches.iter().find(|swatch| swatch.id == *info.key) {
|
||||
thumbs.paint(cx, rect, swatch);
|
||||
}
|
||||
});
|
||||
}
|
||||
browser.show(ui).events
|
||||
.row_menu(false)
|
||||
.show(ui)
|
||||
.events
|
||||
});
|
||||
for picked in browser.inner.into_iter().flatten().filter_map(selected_key) {
|
||||
if picked != current.pattern {
|
||||
@@ -206,16 +176,21 @@ impl<'a> PatternFillEditor<'a> {
|
||||
/// The most decimals the Scale field shows.
|
||||
const SCALE_DECIMALS: usize = 2;
|
||||
|
||||
/// The preset row of `swatch`: its name, with the tile painter when the host gave one.
|
||||
fn tile_row(swatch: &PatternSwatch, thumbnails: Option<&SwatchPainter>) -> PresetRow<String> {
|
||||
let row = PresetRow::item(swatch.id.clone(), swatch.name.clone(), 0);
|
||||
match thumbnails {
|
||||
Some(painter) => {
|
||||
let (painter, swatch) = (painter.clone(), swatch.clone());
|
||||
row.preview(CellShape::Square.aspect(), move |cx, rect| painter.paint(cx, rect, &swatch))
|
||||
/// The preset row of each swatch: its name, with the tile painter when the host gave one.
|
||||
fn tile_rows(swatches: &&[PatternSwatch], _: &Env) -> Vec<PresetRow<String>> {
|
||||
let tile_row = |swatch: &PatternSwatch| {
|
||||
let row = PresetRow::item(swatch.id.clone(), swatch.name.clone(), 0);
|
||||
match swatch.picture {
|
||||
Some(picture) => row.preview(CellShape::Square.aspect(), move |cx, rect| paint_picture(cx, rect, picture)),
|
||||
None => row,
|
||||
}
|
||||
None => row,
|
||||
}
|
||||
};
|
||||
swatches.iter().map(tile_row).collect()
|
||||
}
|
||||
|
||||
/// Paints the whole of a swatch's `picture` into `rect`.
|
||||
fn paint_picture(cx: &ContentPainterCx<'_>, rect: Rect, picture: egui::TextureId) {
|
||||
cx.picture(picture, rect, Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), 0.0);
|
||||
}
|
||||
|
||||
/// The key a browser event picked: a click or Enter on a tile.
|
||||
|
||||
@@ -11,25 +11,35 @@ pub(crate) mod stories;
|
||||
mod words;
|
||||
|
||||
pub use dialog::PatternFillDialog;
|
||||
pub use editor::{PatternFillEditor, PatternFillOutput, SwatchPainter};
|
||||
pub use editor::{PatternFillEditor, PatternFillOutput};
|
||||
pub use words::PatternWords;
|
||||
|
||||
/// A pattern the editor offers: the app's pattern library (PhotoCraft's Patterns, a bitmap each)
|
||||
/// or its preset patterns (PowerPoint's "pct25", "dkHorz", …). The app paints each swatch's tile
|
||||
/// ([`PatternFillEditor::thumbnails`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
/// or its preset patterns (PowerPoint's "pct25", "dkHorz", …), with the app's picture of its tile
|
||||
/// ([`picture`](Self::picture)); a swatch without one shows its name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct PatternSwatch {
|
||||
/// The app's id, which [`PatternFillOptions::pattern`] holds.
|
||||
pub id: String,
|
||||
/// The name in the tooltip and for a screen reader ("Bubbles", "25 %").
|
||||
pub name: String,
|
||||
/// The tile's picture, a texture the app made: the picker's field and cells and the preset grid show it.
|
||||
#[memo_props(hash = "a texture handle: the texture store keeps one picture under it")]
|
||||
pub picture: Option<egui::TextureId>,
|
||||
}
|
||||
|
||||
impl PatternSwatch {
|
||||
/// A swatch of the app's pattern `id`, named `name`.
|
||||
pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
|
||||
PatternSwatch { id: id.into(), name: name.into() }
|
||||
PatternSwatch { id: id.into(), name: name.into(), picture: None }
|
||||
}
|
||||
|
||||
/// This swatch with its tile's `picture`.
|
||||
#[must_use]
|
||||
pub fn with_picture(mut self, picture: egui::TextureId) -> Self {
|
||||
self.picture = Some(picture);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,46 +1,49 @@
|
||||
//! Stories of the pattern fill editor: the bitmap mode, the two-colour preset mode and the editor in Photoshop's
|
||||
//! dialog. The tiles are painted from the theme's colours by a closure, as a host paints its patterns.
|
||||
//! dialog. Each tile shows a texture the story makes, as a host hands in its patterns' pictures.
|
||||
|
||||
use super::{PatternColors, PatternFillEditor, PatternFillOptions, PatternSwatch};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::patterns::form_dialogs::FormDialog;
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::primitives::textures::TextureCache;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::{Rect, Ui};
|
||||
use egui::{Color32, ColorImage, Ui};
|
||||
|
||||
fn swatches() -> Vec<PatternSwatch> {
|
||||
["Stripes", "Checks", "Dots", "Grid", "Waves", "Bubbles"].iter().map(|name| PatternSwatch::new(name.to_lowercase(), *name)).collect()
|
||||
}
|
||||
|
||||
/// A tile: a plain fill over the whole rect, the stand-in for the host's pattern bitmap.
|
||||
fn tile(cx: &ContentPainterCx<'_>, rect: Rect, _: &PatternSwatch) {
|
||||
cx.checker(rect);
|
||||
/// The library, each tile a checker texture: the stand-in for the host's pattern bitmaps.
|
||||
fn swatches(ctx: &egui::Context) -> Vec<PatternSwatch> {
|
||||
let picture = TextureCache::texture(ctx, "pattern-story-tile", || {
|
||||
let (light, dark) = (Color32::from_gray(225), Color32::from_gray(150));
|
||||
ColorImage::new([8, 8], (0..64).map(|at| if (at % 8 < 4) == (at / 8 < 4) { light } else { dark }).collect())
|
||||
});
|
||||
["Stripes", "Checks", "Dots", "Grid", "Waves", "Bubbles"]
|
||||
.iter()
|
||||
.map(|name| PatternSwatch::new(name.to_lowercase(), *name).with_picture(picture))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn editor(ui: &mut Ui, data: &mut StoryData, start: PatternFillOptions, library: &[PatternSwatch]) -> StoryOutput {
|
||||
let (options, options_at) = data.value_at("options", start);
|
||||
let out = PatternFillEditor::new("Pattern fill", options_at.bind(options), library).thumbnails(tile).show(ui);
|
||||
let out = PatternFillEditor::new("Pattern fill", options_at.bind(options), library).show(ui);
|
||||
StoryOutput::from(out)
|
||||
}
|
||||
|
||||
#[story(PatternFillEditor<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn pattern_fill_bitmap(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
editor(ui, data, PatternFillOptions::bitmap("bubbles"), &swatches())
|
||||
editor(ui, data, PatternFillOptions::bitmap("bubbles"), &swatches(ui.ctx()))
|
||||
}
|
||||
|
||||
#[story(PatternFillEditor<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn pattern_fill_preset(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let colors = PatternColors::new(Srgba::rgb(0.1, 0.1, 0.1), Srgba::rgb(0.95, 0.95, 0.9));
|
||||
editor(ui, data, PatternFillOptions::preset("checks", colors), &swatches())
|
||||
editor(ui, data, PatternFillOptions::preset("checks", colors), &swatches(ui.ctx()))
|
||||
}
|
||||
|
||||
#[story(PatternFillEditor<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn pattern_fill_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let library = swatches();
|
||||
let library = swatches(ui.ctx());
|
||||
let ((options, options_at), (open, open_at)) = data.pair_at(("options", PatternFillOptions::bitmap("bubbles")), ("open", true));
|
||||
FormDialog::new("Pattern Fill", options_at.bind(options)).opened(open_at.bind(open)).show(ui, |ui, _, value| {
|
||||
PatternFillEditor::new("Pattern fill", Bind::bound(value), &library).thumbnails(tile).show(ui);
|
||||
PatternFillEditor::new("Pattern fill", Bind::bound(value), &library).show(ui);
|
||||
true
|
||||
});
|
||||
StoryOutput::default()
|
||||
|
||||
@@ -10,7 +10,6 @@ use craft_ui::primitives::{Draw, ToolIcon};
|
||||
use egui::Vec2;
|
||||
|
||||
/// The apex of the Convert Point icon's caret, in the units of the icon's box.
|
||||
// design: allow[literal-size/vec2](the cursor art's hot spot offset in icon units, not a layout size)
|
||||
const CONVERT_TIP: Vec2 = Vec2::new(ICON_BOX / 2.0, 5.5);
|
||||
|
||||
/// The canvas tool of Add Anchor Point, Delete Anchor Point, Convert Point and Direct Selection. Every press of these
|
||||
|
||||
@@ -398,7 +398,7 @@ struct Scene {
|
||||
/// the selected anchors or the picked handle (⌥ alone); Delete and Backspace report
|
||||
/// [`delete`](BezierOutput::delete) under the tools that delete anchors (Direct, Convert, Curvature, Add Anchor,
|
||||
/// Delete Anchor), Insert [`insert`](BezierOutput::insert) halfway along the segment leaving the picked anchor;
|
||||
/// Escape deselects.
|
||||
/// Escape leaves the selection and goes to the window.
|
||||
/// - The anchor tools ([`BezierTool::AddAnchor`], [`BezierTool::DeleteAnchor`], [`BezierTool::AutoAddDelete`]) and
|
||||
/// [`BezierTool::Curvature`] take only a press that hits what they edit, and draw the [`HitMark`] of what a press
|
||||
/// would take under the pointer. [`segment_mark`](Self::segment_mark), [`anchors`](Self::anchors) and
|
||||
@@ -1121,9 +1121,6 @@ impl<'a> BezierOverlay<'a> {
|
||||
self.report.delete = Some(AnchorDelete::new(path, self.selection.anchors.clone(), true));
|
||||
}
|
||||
}
|
||||
if keyed && cx.gesture().is_none() && cx.intents().take(Intent::Cancel) && *self.selection != PathSelection::default() {
|
||||
self.report.select = Some(PathSelection::default());
|
||||
}
|
||||
}
|
||||
|
||||
/// The path ⌘A selects: the selection's, else the picked part's, else the only one.
|
||||
|
||||
@@ -57,7 +57,7 @@ impl BezierTool {
|
||||
matches!(self, BezierTool::AddAnchor | BezierTool::DeleteAnchor | BezierTool::AutoAddDelete)
|
||||
}
|
||||
|
||||
/// Whether the tool has the arrow, ⌘A and Esc keys: Direct, Convert and Curvature. Add and Delete have Delete
|
||||
/// Whether the tool has the arrow and ⌘A keys: Direct, Convert and Curvature. Add and Delete have Delete
|
||||
/// only, Auto Add/Delete none.
|
||||
pub(super) fn keyed(self) -> bool {
|
||||
matches!(self, BezierTool::Direct | BezierTool::Convert | BezierTool::Curvature)
|
||||
|
||||
@@ -28,7 +28,7 @@ craft_ui::words! {
|
||||
}
|
||||
|
||||
/// The symmetry in force, as the menu marks it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum SymmetryChoice {
|
||||
/// No symmetry.
|
||||
@@ -40,7 +40,7 @@ pub enum SymmetryChoice {
|
||||
}
|
||||
|
||||
/// A path the symmetry can come from (the saved paths, the Work Path, the layer's path), in the app's order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct SymmetryPathRow {
|
||||
/// The app's key ("work", "layer", or the saved path's name).
|
||||
|
||||
@@ -9,7 +9,7 @@ pub const TURN_STEP_DEGREES: f64 = 15.0;
|
||||
|
||||
/// The straight symmetry modes PhotoCraft has (lead call 23). Photoshop's Wavy, Circle, Spiral,
|
||||
/// Parallel Lines, Radial and Mandala modes need engine work and are not built.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
#[non_exhaustive]
|
||||
pub enum SymmetryMode {
|
||||
|
||||
@@ -205,6 +205,8 @@ pub struct TransformSession<W = ()> {
|
||||
nudge_pause: Option<f64>,
|
||||
/// When the latest arrow nudge was applied (the `now` of [`apply`](Self::apply)).
|
||||
last_nudge: Option<f64>,
|
||||
/// See [`revision`](Self::revision).
|
||||
revision: u64,
|
||||
}
|
||||
|
||||
impl<W: TransformWarp> TransformSession<W> {
|
||||
@@ -230,6 +232,7 @@ impl<W: TransformWarp> TransformSession<W> {
|
||||
reference_point: false,
|
||||
nudge_pause: None,
|
||||
last_nudge: None,
|
||||
revision: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,6 +427,7 @@ impl<W: TransformWarp> TransformSession<W> {
|
||||
}
|
||||
}
|
||||
TransformEdit::Warp(warp) => {
|
||||
self.revision += u64::from(self.draft.warp.is_none());
|
||||
if self.draft.warp.is_none()
|
||||
&& let Some(frame) = warp.frame()
|
||||
{
|
||||
@@ -434,6 +438,7 @@ impl<W: TransformWarp> TransformSession<W> {
|
||||
self.draft.warp = Some(warp);
|
||||
}
|
||||
TransformEdit::LeaveWarp => {
|
||||
self.revision += u64::from(self.draft.warp.is_some());
|
||||
if let Some((frame, state)) = self.draft.unwarped.take() {
|
||||
self.draft.frame = frame;
|
||||
self.draft.state = state;
|
||||
@@ -498,6 +503,14 @@ impl<W: TransformWarp> TransformSession<W> {
|
||||
self.step(Step::Redo)
|
||||
}
|
||||
|
||||
/// Moves whenever what [`can_undo`](Self::can_undo), [`can_redo`](Self::can_redo) or whether a
|
||||
/// [`warp`](Self::warp) is open report may change: an undo step recorded or taken, the Warp phase opened
|
||||
/// or closed. A new session starts at 0, where nothing can be undone or redone and no warp is open, so
|
||||
/// an app keys what it shows of those on this number.
|
||||
pub fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
}
|
||||
|
||||
/// Whether [`undo`](Self::undo) has a step to take back.
|
||||
pub fn can_undo(&self) -> bool {
|
||||
self.history.can_undo()
|
||||
@@ -557,6 +570,7 @@ impl<W: TransformWarp> TransformSession<W> {
|
||||
let step = EditEvent::set(Mixed::Same(self.rested.clone()), self.draft.clone(), Arc::from(""), None);
|
||||
self.history.record(&step);
|
||||
self.rested = self.draft.clone();
|
||||
self.revision += 1;
|
||||
}
|
||||
|
||||
/// One box or field event. A Begin takes the draft as `before`; a Set outside a gesture is a
|
||||
@@ -600,6 +614,7 @@ impl<W: TransformWarp> TransformSession<W> {
|
||||
let moved = self.history.step(&mut self.draft, step);
|
||||
self.rested = self.draft.clone();
|
||||
self.changed = false;
|
||||
self.revision += u64::from(moved);
|
||||
moved
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,7 +421,7 @@ fn hit_test_matches_the_overlays_press_priority() {
|
||||
|
||||
// ---- the anchor tools and the Curvature tool ----
|
||||
|
||||
// Arrows, select all and Escape belong to Direct, Convert and Curvature; Add, Delete and Auto Add/Delete have none.
|
||||
// Arrows and select all belong to Direct, Convert and Curvature; Add, Delete and Auto Add/Delete have none.
|
||||
|
||||
#[trial]
|
||||
fn cmd_or_ctrl_with_page_down_on_a_focused_anchor_scrolls_the_canvas_and_picks_no_part() {
|
||||
@@ -1202,6 +1202,23 @@ fn arrow_keys_nudge_the_selected_anchors_and_shift_nudges_farther() {
|
||||
assert_eq!(h.state.borrow().changes.len(), 2, "one edit per press");
|
||||
}
|
||||
|
||||
// Escape on a focused anchor leaves the anchor selection and the targeted path under Direct, Convert and Curvature; it
|
||||
// goes on to the window. A key still reaches the overlay afterwards.
|
||||
#[trial]
|
||||
fn escape_on_a_focused_anchor_keeps_the_selection() {
|
||||
for tool in [BezierTool::Direct, BezierTool::Convert, BezierTool::Curvature] {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)])));
|
||||
h.fixture.key(egui::Key::Tab, egui::Modifiers::NONE).key(egui::Key::Tab, egui::Modifiers::NONE).settle();
|
||||
let before = h.state.borrow().selection.clone();
|
||||
assert!(before != PathSelection::default(), "{tool:?}: an anchor is selected");
|
||||
h.fixture.key(egui::Key::Escape, egui::Modifiers::NONE).settle();
|
||||
assert_eq!(h.state.borrow().selection, before, "{tool:?}: Escape keeps the selection");
|
||||
h.fixture.key(egui::Key::ArrowRight, egui::Modifiers::NONE).settle();
|
||||
assert!(h.last_change().is_some(), "{tool:?}: the overlay still has the keys");
|
||||
}
|
||||
}
|
||||
|
||||
// A press belongs to the tool it began under: switching the host's tool in the middle of a drag leaves the drag its
|
||||
// own, and it commits as that tool's edit.
|
||||
#[trial]
|
||||
|
||||
@@ -2,18 +2,25 @@
|
||||
//! opens the picker at a point without its field; a resized picker keeps its size; the head edits angle and
|
||||
//! roundness; Escape reverts the head's edits.
|
||||
|
||||
use craft_draw::ui::brush_presets::{BrushPick, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, brush_row};
|
||||
use craft_draw::ui::brush_presets::{BrushCardParts, BrushPick, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, brush_row};
|
||||
use craft_draw::ui::brush_settings::TipAngle;
|
||||
use craft_ui::contract::{Bind, Role, SaveKey};
|
||||
use craft_ui::patterns::presets::PresetEvent;
|
||||
use craft_ui::patterns::presets::{PresetEvent, PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial};
|
||||
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
const HARD: u32 = 2;
|
||||
|
||||
/// Two presets, Soft Round and Hard Round, showing `parts`.
|
||||
fn two_rows(parts: &BrushCardParts, env: &Env) -> Vec<PresetRow<u32>> {
|
||||
let paint = BrushRowPaint::new(|_, _| {}, |_, _| {});
|
||||
vec![brush_row(1, "Soft Round", 0, 45.0, *parts, env, &paint), brush_row(HARD, "Hard Round", 0, 12.0, *parts, env, &paint)]
|
||||
}
|
||||
|
||||
struct Host {
|
||||
current: Option<u32>,
|
||||
state: BrushPickerState<u32>,
|
||||
@@ -25,12 +32,9 @@ fn rename_brush_opens_the_name_field_on_the_current_preset() {
|
||||
let host = Rc::new(RefCell::new(Host { current: Some(HARD), state: BrushPickerState::new(), picks: Vec::new() }));
|
||||
let shown = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let env = Env::of(ui);
|
||||
let paint = BrushRowPaint::new(|_, _| {}, |_, _| {});
|
||||
let mut host = shown.borrow_mut();
|
||||
let Host { current, state, picks } = &mut *host;
|
||||
let rows =
|
||||
vec![brush_row(1, "Soft Round", 0, 45.0, state.parts, &env, &paint), brush_row(HARD, "Hard Round", 0, 12.0, state.parts, &env, &paint)];
|
||||
let rows = PresetSource::new(state.parts, PresetFns::new(two_rows));
|
||||
let values = BrushPickerValues::new(12.0, Some(1.0));
|
||||
let out = BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), values).show(ui);
|
||||
picks.extend(out.picks);
|
||||
@@ -88,13 +92,10 @@ fn opened_rig(at_point: bool, remember: bool) -> (Fixture, Rc<RefCell<Opened>>)
|
||||
}));
|
||||
let shown = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let env = Env::of(ui);
|
||||
let paint = BrushRowPaint::new(|_, _| {}, |_, _| {});
|
||||
let mut host = shown.borrow_mut();
|
||||
let Opened { current, state, values, open, tip_edits, at, offset } = &mut *host;
|
||||
ui.add_space(*offset);
|
||||
let rows =
|
||||
vec![brush_row(1, "Soft Round", 0, 45.0, state.parts, &env, &paint), brush_row(HARD, "Hard Round", 0, 12.0, state.parts, &env, &paint)];
|
||||
let rows = PresetSource::new(state.parts, PresetFns::new(two_rows));
|
||||
let mut picker = BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), *values);
|
||||
if remember {
|
||||
picker = picker.resizable(SaveKey::new("craft_draw_tests.brush_picker"));
|
||||
@@ -222,3 +223,35 @@ fn escape_reverts_size_hardness_angle_and_roundness() {
|
||||
fixture.idle(3);
|
||||
assert_eq!(host.borrow().values, OPENED, "Escape puts all four back");
|
||||
}
|
||||
|
||||
/// The memoized views of `props` that ran in the last frame.
|
||||
fn views_ran(fixture: &Fixture, props: &str) -> usize {
|
||||
last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Ran).count()
|
||||
}
|
||||
|
||||
/// The memoized views of `props` that replayed in the last frame.
|
||||
fn views_replayed(fixture: &Fixture, props: &str) -> usize {
|
||||
last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Replayed).count()
|
||||
}
|
||||
|
||||
/// While nothing changes the open picker's head and preset list replay; each move of a Size drag runs the head's view
|
||||
/// and replays the list.
|
||||
#[trial]
|
||||
fn a_size_drag_runs_the_head_and_replays_the_preset_list() {
|
||||
let (mut fixture, host) = opened_rig(true, false);
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!((views_ran(&fixture, "HeadProps"), views_ran(&fixture, "ListProps")), (0, 0), "an idle frame runs neither view");
|
||||
let slider = fixture.by_role(Role::SLIDER).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Size"));
|
||||
let slider = slider.expect("the Size slider shows").rect;
|
||||
let from = slider.left_center() + Vec2::new(slider.width() * 0.3, 0.0);
|
||||
fixture.frame(vec![moved(from)]);
|
||||
fixture.frame(vec![press(from)]);
|
||||
for step in 1..=4 {
|
||||
fixture.frame(vec![moved(from + Vec2::new(8.0 * step as f32, 0.0))]);
|
||||
assert!(views_ran(&fixture, "HeadProps") > 0, "move {step} runs the head");
|
||||
assert_eq!(views_ran(&fixture, "ListProps"), 0, "move {step} runs no list view");
|
||||
assert!(views_replayed(&fixture, "ListProps") > 0, "move {step} replays the list");
|
||||
}
|
||||
fixture.frame(vec![release(from + Vec2::new(32.0, 0.0))]);
|
||||
assert_ne!(host.borrow().values.diameter, OPENED.diameter, "the drag edited the size");
|
||||
}
|
||||
|
||||
@@ -185,3 +185,30 @@ fn a_warp_with_its_own_frame_takes_the_frame_and_gives_it_back() {
|
||||
s.apply(TransformEdit::LeaveWarp, 1.0);
|
||||
assert_eq!((s.rect(), s.state().quad), (FRAME, BoxState::from_rect(FRAME).quad));
|
||||
}
|
||||
|
||||
// The revision moves with every change to what Undo, Redo and the Warp phase report, and stays through a drag's moves
|
||||
// and the view-like edits, so an app keys its Edit menu on it.
|
||||
#[trial]
|
||||
fn the_revision_follows_the_undo_steps_and_the_warp_phase() {
|
||||
let mut s = session();
|
||||
let start = s.revision();
|
||||
let id = GestureId::new(1);
|
||||
s.apply(TransformEdit::Box(begin(id)), 0.0);
|
||||
s.apply(TransformEdit::Box(update(id, moved(doc(5.0, 0.0)))), 0.0);
|
||||
s.apply(TransformEdit::Box(update(id, moved(doc(9.0, 0.0)))), 0.0);
|
||||
assert_eq!(s.revision(), start, "a drag's moves record no step");
|
||||
s.apply(TransformEdit::Box(commit(id, moved(doc(9.0, 0.0)))), 0.0);
|
||||
s.settle(0.0, false);
|
||||
let recorded = s.revision();
|
||||
assert!(recorded != start && s.can_undo());
|
||||
assert!(s.undo());
|
||||
let undone = s.revision();
|
||||
assert!(undone != recorded && s.can_redo());
|
||||
s.apply(TransformEdit::Warp(Warp(false)), 0.0);
|
||||
let warped = s.revision();
|
||||
assert!(warped != undone && s.warp().is_some());
|
||||
s.apply(TransformEdit::Warp(Warp(true)), 0.0);
|
||||
assert_eq!(s.revision(), warped, "a warp edit inside the phase opens no phase");
|
||||
s.apply(TransformEdit::LeaveWarp, 0.0);
|
||||
assert!(s.revision() != warped && s.warp().is_none());
|
||||
}
|
||||
|
||||
@@ -307,6 +307,7 @@ type FamilyLoad = Arc<OnceLock<Arc<[LoadedFace]>>>;
|
||||
/// Each family's files load once ([`Catalog::load_family`]): other threads asking for the same
|
||||
/// family wait for that load, other families load at the same time.
|
||||
pub struct Catalog {
|
||||
id: u64,
|
||||
env: FontEnv,
|
||||
config: RwLock<Config>,
|
||||
index: RwLock<Arc<Index>>,
|
||||
@@ -331,7 +332,9 @@ impl Catalog {
|
||||
/// A catalog of the fonts installed on the system `env` describes, the font store, and the
|
||||
/// files the platform's font service lists (with the `system` feature).
|
||||
pub fn new(env: FontEnv) -> Self {
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
|
||||
Self {
|
||||
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
|
||||
env,
|
||||
config: RwLock::new(Config { app_dirs: Vec::new(), listers: Vec::new(), font_service: cfg!(feature = "system") }),
|
||||
index: RwLock::new(Arc::new(Index::default())),
|
||||
@@ -475,6 +478,13 @@ impl Catalog {
|
||||
Watch { stop }
|
||||
}
|
||||
|
||||
/// The catalog's identity: unique among the catalogs of the process, fixed at construction. Clones of the `Arc`
|
||||
/// share it. A holder of derived data keys it by the id and the [`generation`](Catalog::generation), which counts
|
||||
/// changes of this catalog only.
|
||||
pub fn id(&self) -> u64 {
|
||||
self.id
|
||||
}
|
||||
|
||||
/// Counts the catalog's changes: each scan, and each face added or removed.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::Acquire)
|
||||
|
||||
@@ -98,6 +98,9 @@ pub struct FaceInfo {
|
||||
pub code_pages: [u32; 2],
|
||||
/// The file the face is in; `None` for a face added as bytes.
|
||||
pub path: Option<PathBuf>,
|
||||
/// The size in bytes of the file when it was scanned; `None` for a face added as bytes. A caller that draws with the
|
||||
/// face checks it before loading, so no file system read happens while it paints.
|
||||
pub file_bytes: Option<u64>,
|
||||
/// The face's number in its file: its index in a collection (0 in a single font), or for a
|
||||
/// Mac suitcase font the number of its `sfnt` resource.
|
||||
pub index: u32,
|
||||
@@ -329,6 +332,7 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index:
|
||||
fs_type,
|
||||
code_pages,
|
||||
path: path.map(Path::to_path_buf),
|
||||
file_bytes: None,
|
||||
index,
|
||||
source,
|
||||
blob: None,
|
||||
@@ -430,9 +434,11 @@ pub(crate) fn file_faces(path: &Path, max_read: u64, source: Source) -> Vec<Face
|
||||
return vec![];
|
||||
}
|
||||
let mut faces = Vec::new();
|
||||
let file_bytes = Some(crate::suitcase::fork_len(path));
|
||||
for (resource, font) in (0u32..).zip(crate::suitcase::read_fonts(path)) {
|
||||
for mut face in data_faces(&font, 1, Some(path), source) {
|
||||
face.info.index = resource;
|
||||
face.info.file_bytes = file_bytes;
|
||||
faces.push(face);
|
||||
}
|
||||
}
|
||||
@@ -493,6 +499,10 @@ fn reader_faces(mut file: impl std::io::Read + std::io::Seek, max_faces: u32, ma
|
||||
Some(font_faces(&skrifa::FontRef::new(&font).ok()?, outlines, index, Some(path), source))
|
||||
})
|
||||
.flatten()
|
||||
.map(|mut face| {
|
||||
face.info.file_bytes = Some(file_len);
|
||||
face
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ fn key(owner: Owner, face: &FaceInfo) -> String {
|
||||
|
||||
/// The bytes of `face` from `catalog`, unless its file is too large to draw with.
|
||||
fn load(catalog: &Catalog, face: &FaceInfo) -> Option<FaceBytes> {
|
||||
let too_large = face.path.as_ref().and_then(|path| std::fs::metadata(path).ok()).is_some_and(|meta| meta.len() > MAX_FILE_BYTES);
|
||||
let too_large = face.file_bytes.is_some_and(|bytes| bytes > MAX_FILE_BYTES);
|
||||
if too_large {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,8 @@ use egui::{Rect, Response, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::missing::{DocumentFont, FontStatus, MissingFontsWords, document_fonts};
|
||||
use rank::{Info, infos, shown_name};
|
||||
pub use rank::FamilyInfos;
|
||||
use rank::{Info, shown_name};
|
||||
|
||||
craft_ui::words! {
|
||||
/// The picker's words, English by default.
|
||||
@@ -288,9 +289,11 @@ pub struct FamilyRow {
|
||||
|
||||
/// The families `listing` would show, in list order: recents first (when the query is empty and no filter is on),
|
||||
/// then the matching families, the best match first and ties in the order of `language` (its code, `ja`, `pt-BR`).
|
||||
/// For apps that draw their own list from the picker's filtering.
|
||||
/// For apps that draw their own list from the picker's filtering. `infos` is [`FamilyInfos::of`] of `catalog`, built
|
||||
/// again by the app when the catalog's generation moves.
|
||||
pub fn family_rows(
|
||||
catalog: &Arc<Catalog>,
|
||||
infos: &FamilyInfos,
|
||||
query: &str,
|
||||
settings: Option<&FontPickerSettings>,
|
||||
filters: &FontFilters,
|
||||
@@ -299,7 +302,12 @@ pub fn family_rows(
|
||||
) -> Vec<FamilyRow> {
|
||||
let (folder, collator) = (craft_i18n::Folder::new(language), craft_i18n::Collator::new(language));
|
||||
let listing = rank::Listing { query, settings, filters, current, language, served: &[] };
|
||||
rank::list(catalog, &infos(catalog), &listing, &rank::Language { folder: &folder, collator: &collator }, true).0
|
||||
rank::list(catalog, infos, &listing, &rank::Language { folder: &folder, collator: &collator }, true).0
|
||||
}
|
||||
|
||||
/// The family data of `catalog` for the component `cx`: kept across passes while the catalog and its generation are unchanged.
|
||||
pub(super) fn infos_of(ctx: &egui::Context, id: egui::Id, catalog: &Catalog) -> Arc<FamilyInfos> {
|
||||
craft_ui::runtime::derived::derived(ctx, id, &(catalog.id(), catalog.generation()), || FamilyInfos::of(catalog))
|
||||
}
|
||||
|
||||
/// How a [`FontPicker`] lays out its list.
|
||||
@@ -380,7 +388,7 @@ fn text_key() -> TextKey<String> {
|
||||
/// The family field's text: the family's name in the interface language, and a typed name read back as a family.
|
||||
#[derive(Clone)]
|
||||
struct FamilyCodec {
|
||||
infos: Arc<rank::Infos>,
|
||||
infos: Arc<FamilyInfos>,
|
||||
language: String,
|
||||
/// A typed name that is no installed family is a value too (Word's font box applies it as typed).
|
||||
free: bool,
|
||||
@@ -566,13 +574,13 @@ impl<'a> FontPicker<'a> {
|
||||
Some(Label::from(note))
|
||||
}
|
||||
|
||||
fn codec(&self, env: &EnvView<'_>) -> FamilyCodec {
|
||||
FamilyCodec { infos: infos(self.catalog), language: ui_language(env), free: self.kind == FontPickerKind::Plain }
|
||||
fn codec(&self, infos: Arc<FamilyInfos>, env: &EnvView<'_>) -> FamilyCodec {
|
||||
FamilyCodec { infos, language: ui_language(env), free: self.kind == FontPickerKind::Plain }
|
||||
}
|
||||
|
||||
/// The families in list order without filters or recents, which the arrows and the wheel step through.
|
||||
fn ordered(&self, cx: &Cx<'_, Self>, settings: Option<&FontPickerSettings>) -> Vec<FamilyRow> {
|
||||
let infos = infos(self.catalog);
|
||||
let infos = infos_of(&cx.response.ctx, cx.id, self.catalog);
|
||||
let (folder, collator) = (cx.env.folder(), cx.env.collator());
|
||||
let filters = FontFilters::default();
|
||||
let language = ui_language(&cx.env);
|
||||
@@ -631,7 +639,7 @@ impl Component for FontPicker<'_> {
|
||||
.pointer_only("Alt+Down opens the list")
|
||||
.toggles(POPUP);
|
||||
}
|
||||
let codec = self.codec(&cx.env);
|
||||
let codec = self.codec(infos_of(cx.ui.ctx(), cx.id, self.catalog), &cx.env);
|
||||
let mut options = TextOptions::new();
|
||||
options.select_on_focus = true;
|
||||
cx.text(text_key(), placed.text, &codec, &family, &options);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! traits read from the faces' tables, the filtered list and its order, and the sample text of a row.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, PoisonError, Weak};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use craft_font_catalog::{Catalog, FaceInfo, LocalizedName, Outlines};
|
||||
use craft_i18n::matcher::{Matcher, Rank};
|
||||
@@ -53,8 +53,10 @@ impl Traits {
|
||||
}
|
||||
}
|
||||
|
||||
/// The families of one catalog generation with their traits and sample texts, filled on first use.
|
||||
pub(super) struct Infos {
|
||||
/// The families of one catalog generation with their traits and sample texts, filled on first use. Built by
|
||||
/// [`FamilyInfos::of`] and held by the one that lists with it: the picker keeps it in a derived value keyed by the
|
||||
/// catalog's generation, and an app that calls [`family_rows`](super::family_rows) keeps its own while the catalog is unchanged.
|
||||
pub struct FamilyInfos {
|
||||
pub(super) families: HashMap<String, Info>,
|
||||
traits: Mutex<HashMap<String, Option<Traits>>>,
|
||||
samples: Mutex<HashMap<(String, String, String), Samples>>,
|
||||
@@ -78,8 +80,9 @@ fn has_arabic_sample(drawn: &dyn Fn(&str) -> bool, latin: &str, arabic: &str) ->
|
||||
drawn(latin) && drawn(ARABIC_CORE) && drawn(arabic)
|
||||
}
|
||||
|
||||
impl Infos {
|
||||
fn build(catalog: &Catalog) -> Infos {
|
||||
impl FamilyInfos {
|
||||
/// The family data of `catalog` as it is now; build it again when the catalog's generation moves.
|
||||
pub fn of(catalog: &Catalog) -> FamilyInfos {
|
||||
let mut groups: HashMap<String, Vec<FaceInfo>> = HashMap::new();
|
||||
for face in catalog.faces().iter() {
|
||||
groups.entry(face.family.clone()).or_default().push(face.clone());
|
||||
@@ -99,7 +102,7 @@ impl Infos {
|
||||
Some((family, Info { localized, format, styles: faces.len(), regular }))
|
||||
})
|
||||
.collect();
|
||||
Infos { families, traits: Mutex::new(HashMap::new()), samples: Mutex::new(HashMap::new()) }
|
||||
FamilyInfos { families, traits: Mutex::new(HashMap::new()), samples: Mutex::new(HashMap::new()) }
|
||||
}
|
||||
|
||||
/// The family's traits, read from its regular face on first use.
|
||||
@@ -147,24 +150,6 @@ fn draws(catalog: &Catalog, face: &FaceInfo, sample: &str, arabic: &str, shown:
|
||||
Some(Samples { latin: first, arabic: None })
|
||||
}
|
||||
|
||||
type CacheEntry = (Weak<Catalog>, u64, Arc<Infos>);
|
||||
static CACHE: Mutex<Vec<CacheEntry>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The family data of `catalog`, rebuilt when its generation moves.
|
||||
pub(super) fn infos(catalog: &Arc<Catalog>) -> Arc<Infos> {
|
||||
let generation = catalog.generation();
|
||||
let same = |w: &Weak<Catalog>| std::ptr::eq(w.as_ptr(), Arc::as_ptr(catalog));
|
||||
let mut cache = lock(&CACHE);
|
||||
cache.retain(|(w, _, _)| w.strong_count() > 0);
|
||||
if let Some((_, _, infos)) = cache.iter().find(|(w, g, _)| *g == generation && same(w)) {
|
||||
return Arc::clone(infos);
|
||||
}
|
||||
cache.retain(|(w, _, _)| !same(w));
|
||||
let infos = Arc::new(Infos::build(catalog));
|
||||
cache.push((Arc::downgrade(catalog), generation, Arc::clone(&infos)));
|
||||
infos
|
||||
}
|
||||
|
||||
/// The upright face nearest weight 400.
|
||||
pub(super) fn regular_face(faces: &[FaceInfo]) -> Option<&FaceInfo> {
|
||||
faces.iter().min_by_key(|f| (f.italic, (f.weight - 400.0).abs() as u32))
|
||||
@@ -291,7 +276,13 @@ pub(super) struct Language<'a> {
|
||||
/// The rows the list shows for `listing` and whether Show Similar Fonts had a reference to compare with: recents
|
||||
/// first (when the query is empty and no filter is on), then the matching families, the best match first and ties
|
||||
/// in the interface language's order. A list that is not `narrowed` has no filters and no recents.
|
||||
pub(super) fn list(catalog: &Arc<Catalog>, infos: &Infos, listing: &Listing<'_>, language: &Language<'_>, narrowed: bool) -> (Vec<FamilyRow>, bool) {
|
||||
pub(super) fn list(
|
||||
catalog: &Arc<Catalog>,
|
||||
infos: &FamilyInfos,
|
||||
listing: &Listing<'_>,
|
||||
language: &Language<'_>,
|
||||
narrowed: bool,
|
||||
) -> (Vec<FamilyRow>, bool) {
|
||||
let default_filters = FontFilters::default();
|
||||
let filters = if narrowed { listing.filters } else { &default_filters };
|
||||
let settings = listing.settings;
|
||||
|
||||
@@ -22,10 +22,10 @@ use craft_ui::primitives::{ContentPainterCx, IconSpec};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use egui::Rect;
|
||||
|
||||
use super::rank::{Infos, Language, Listing, list, shown_name};
|
||||
use super::rank::{FamilyInfos, Language, Listing, list, shown_name};
|
||||
use super::{
|
||||
FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos, read,
|
||||
ui_language, write,
|
||||
FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos_of,
|
||||
read, ui_language, write,
|
||||
};
|
||||
use crate::panel::faces::{Owner, Shown, paint_sample, shown};
|
||||
use craft_ui::style::DataColor;
|
||||
@@ -256,7 +256,7 @@ fn class_column(ui: &mut egui::Ui, filters: &mut FontFilters, words: &FontPicker
|
||||
|
||||
/// A thumbnail painting `text` in the regular face of `family`; nothing for a family the catalog lacks or an empty
|
||||
/// text, and nothing until the face is loaded.
|
||||
fn face_thumb<'a>(catalog: &'a Arc<Catalog>, infos: &'a Infos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a {
|
||||
fn face_thumb<'a>(catalog: &'a Arc<Catalog>, infos: &'a FamilyInfos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a {
|
||||
move |cx, rect| {
|
||||
let Some(info) = infos.families.get(family) else { return };
|
||||
if text.is_empty() {
|
||||
@@ -270,7 +270,7 @@ fn face_thumb<'a>(catalog: &'a Arc<Catalog>, infos: &'a Infos, family: &'a str,
|
||||
}
|
||||
|
||||
/// The banner: `text` in the face of `family`, on one line cut at the end, in a picture as high as the large thumbnail.
|
||||
fn banner(ui: &mut egui::Ui, catalog: &Arc<Catalog>, infos: &Infos, family: &str, shown_name: &str, text: &str) {
|
||||
fn banner(ui: &mut egui::Ui, catalog: &Arc<Catalog>, infos: &FamilyInfos, family: &str, shown_name: &str, text: &str) {
|
||||
Picture::painter(shown_name.to_owned(), ThumbAspect::new(BANNER_ASPECT.0, BANNER_ASPECT.1), face_thumb(catalog, infos, family, text.to_owned()))
|
||||
.extent(PictureSize::Thumb(ThumbSize::Large))
|
||||
.show(ui);
|
||||
@@ -278,7 +278,7 @@ fn banner(ui: &mut egui::Ui, catalog: &Arc<Catalog>, infos: &Infos, family: &str
|
||||
|
||||
/// The name the banner shows for `family`: its row's shown name when the list holds one, else its name in the
|
||||
/// interface language, else the family key.
|
||||
fn banner_shown_name(slots: &[Slot], infos: &Infos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String {
|
||||
fn banner_shown_name(slots: &[Slot], infos: &FamilyInfos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String {
|
||||
let row = slots.iter().find_map(|slot| match slot {
|
||||
Slot::Family { row, .. } if row.family == family => Some(row.shown.clone()),
|
||||
_ => None,
|
||||
@@ -338,7 +338,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
|
||||
let has_filters = filters.is_some();
|
||||
let narrowing = filters.clone().unwrap_or_default();
|
||||
let catalog = picker.catalog;
|
||||
let infos = infos(catalog);
|
||||
let infos = infos_of(&cx.response.ctx, cx.id, catalog);
|
||||
let language_code = ui_language(&cx.env);
|
||||
let (folder, collator) = (cx.env.folder(), cx.env.collator());
|
||||
let listing = Listing {
|
||||
|
||||
@@ -9,7 +9,7 @@ use craft_behavior::{PartKey, Preview};
|
||||
use craft_font_manager::craft_font_catalog::{Limits, Os, Source};
|
||||
use craft_font_manager::missing::MissingFontsWords;
|
||||
use craft_font_manager::picker::{
|
||||
FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows,
|
||||
FamilyInfos, FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows,
|
||||
};
|
||||
use craft_font_manager::{Catalog, FontEnv};
|
||||
use craft_ui::buttons::ControlPlace;
|
||||
@@ -18,7 +18,7 @@ use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::runtime::env::{Label, with_env};
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::pointer::moved;
|
||||
use craft_ui::testing::{Fixture, Room, trial};
|
||||
use craft_ui::testing::{Fixture, Room, last_frame_derived_builds, trial};
|
||||
use egui::{Event, Key, Modifiers};
|
||||
|
||||
const INTER_REGULAR: &[u8] = include_bytes!("../../../ui-contract/fonts/inter/Inter-Regular.ttf");
|
||||
@@ -125,14 +125,15 @@ fn similar_fonts_put_the_current_family_first_and_leave_the_list_alone_without_a
|
||||
let catalog = catalog_of(&[epaint_default_fonts::HACK_REGULAR, epaint_default_fonts::UBUNTU_LIGHT, INTER_REGULAR]);
|
||||
let mut similar = FontFilters::default();
|
||||
similar.similar = true;
|
||||
let rows = family_rows(&catalog, "", None, &similar, "Inter", "en");
|
||||
let infos = FamilyInfos::of(&catalog);
|
||||
let rows = family_rows(&catalog, &infos, "", None, &similar, "Inter", "en");
|
||||
let names: Vec<&str> = rows.iter().map(|row| row.family.as_str()).collect();
|
||||
assert_eq!(names.first(), Some(&"Inter"), "the current family first, though it is not first by name");
|
||||
assert!(rows.len() <= SIMILAR_COUNT);
|
||||
|
||||
// A current family the catalog lacks has no traits: the list stays as unfiltered.
|
||||
let unfiltered = family_rows(&catalog, "", None, &FontFilters::default(), "", "en");
|
||||
assert_eq!(family_rows(&catalog, "", None, &similar, "Missing", "en"), unfiltered);
|
||||
let unfiltered = family_rows(&catalog, &infos, "", None, &FontFilters::default(), "", "en");
|
||||
assert_eq!(family_rows(&catalog, &infos, "", None, &similar, "Missing", "en"), unfiltered);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
@@ -360,3 +361,42 @@ fn a_squeezed_ribbon_font_box_keeps_a_short_fields_name() {
|
||||
assert!(squeezed > short, "the squeezed font box keeps a name field {short} wide and its arrow: {squeezed}");
|
||||
assert!(squeezed <= picker_width("Inter", true) + 0.5, "and is no wider than where the room allows");
|
||||
}
|
||||
|
||||
/// The family data builds of the last frame.
|
||||
fn family_builds(fx: &Fixture) -> u32 {
|
||||
last_frame_derived_builds(fx.ctx()).iter().map(|(_, builds)| builds).sum()
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_family_data_builds_when_the_catalog_changes_and_not_while_it_is_idle() {
|
||||
let catalog = catalog_of(&[INTER_REGULAR]);
|
||||
let (mut fx, _) = rig(Arc::clone(&catalog), vec![]);
|
||||
open(&mut fx);
|
||||
fx.frame(vec![]);
|
||||
assert_eq!(family_builds(&fx), 0, "an idle open list builds nothing");
|
||||
catalog.add_bytes(INTER_SEMIBOLD.to_vec(), Source::Bundled, &Limits::default()).expect("a font file");
|
||||
fx.frame(vec![]);
|
||||
assert_eq!(family_builds(&fx), 1, "a changed catalog builds the data once, whatever reads it");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_picker_handed_another_catalog_at_the_same_generation_builds_its_family_data_once() {
|
||||
let (one, two) = (catalog_of(&[INTER_REGULAR]), catalog_of(&[INTER_REGULAR]));
|
||||
assert_eq!(one.generation(), two.generation(), "the two catalogs count alike");
|
||||
assert_ne!(one.id(), two.id());
|
||||
let shown = Rc::new(RefCell::new(Arc::clone(&one)));
|
||||
let held = Rc::clone(&shown);
|
||||
let mut family = String::new();
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
let catalog = Arc::clone(&held.borrow());
|
||||
FontPicker::new("Font family", Bind::bound(&mut family), &catalog).show(ui);
|
||||
});
|
||||
fx.in_room(Room::Window);
|
||||
fx.settle();
|
||||
open(&mut fx);
|
||||
fx.frame(vec![]);
|
||||
assert_eq!(family_builds(&fx), 0, "the first catalog's data is kept");
|
||||
*shown.borrow_mut() = Arc::clone(&two);
|
||||
fx.frame(vec![]);
|
||||
assert_eq!(family_builds(&fx), 1, "the second catalog builds the data once");
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
/// A contour point, input and output in 0..=1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
pub struct ContourPoint {
|
||||
/// Input value, 0..=1 (the horizontal axis).
|
||||
pub input: f32,
|
||||
@@ -15,6 +16,7 @@ pub struct ContourPoint {
|
||||
/// Built-in presets carry their preset name; an edited preset is named "Custom"; imported
|
||||
/// contours keep their own name and points.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
|
||||
pub struct Contour {
|
||||
#[allow(missing_docs)]
|
||||
pub name: String,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -207,7 +207,7 @@ impl HistogramData {
|
||||
}
|
||||
|
||||
/// A range of whole levels (bin positions) a plot has selected, both ends included.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct LevelRange {
|
||||
/// The first level.
|
||||
|
||||
@@ -15,7 +15,7 @@ use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::Ui;
|
||||
|
||||
use super::{ContourAction, ContourRequest, ContourWords, SharedSampler, from_curve, to_curve};
|
||||
use super::{ContourAction, ContourRequest, ContourSampler, ContourWords, from_curve, to_curve};
|
||||
use crate::layer_style::Contour;
|
||||
use crate::ui::curve::CurveEditor;
|
||||
|
||||
@@ -49,7 +49,7 @@ pub struct ContourEditorDialog {
|
||||
key: String,
|
||||
initial: Contour,
|
||||
draft: Draft,
|
||||
sampler: Option<SharedSampler>,
|
||||
sampler: Option<ContourSampler>,
|
||||
changed: bool,
|
||||
action: Option<ContourAction>,
|
||||
focus_name: bool,
|
||||
@@ -72,8 +72,8 @@ impl ContourEditorDialog {
|
||||
|
||||
/// The interpolation of the points, as the engine does it. Without it the curve is a monotone cubic.
|
||||
#[must_use]
|
||||
pub fn sampler(mut self, sampler: impl Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync + 'static) -> Self {
|
||||
self.sampler = Some(std::sync::Arc::new(sampler));
|
||||
pub fn sampler(mut self, sampler: ContourSampler) -> Self {
|
||||
self.sampler = Some(sampler);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ impl StackDialog for ContourEditorDialog {
|
||||
let extras = [(Extra::Load, &words.load), (Extra::Save, &words.save), (Extra::New, &words.new)];
|
||||
let named = Cell::new(false);
|
||||
let focus_name = std::mem::take(&mut self.focus_name);
|
||||
let sampler = self.sampler.clone();
|
||||
let sampler = self.sampler;
|
||||
let shown = FormDialog::new(words.editor.clone(), Bind::bound(&mut self.draft))
|
||||
.outer_gesture(true)
|
||||
.history(true)
|
||||
@@ -171,8 +171,8 @@ impl StackDialog for ContourEditorDialog {
|
||||
.percent()
|
||||
.corners()
|
||||
.between(between);
|
||||
if let Some(sampler) = sampler.clone() {
|
||||
editor = editor.sampler(move |points| sampler(points));
|
||||
if let Some(sampler) = sampler {
|
||||
editor = editor.sampler(sampler);
|
||||
}
|
||||
let edit = editor.show(ui);
|
||||
if let Some(next) = edit.events.value().and_then(|curve| from_curve(curve, &draft.contour.name)) {
|
||||
|
||||
@@ -5,14 +5,12 @@ mod editor;
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{EditEvents, Mixed};
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, EditResponse, NoValue, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::list::ThumbAspect;
|
||||
use craft_ui::patterns::presets::{PickerField, PresetEvent, PresetFooterEvent, PresetPicker, PresetRow, PresetState};
|
||||
use craft_ui::patterns::presets::{PickerField, PresetEvent, PresetFns, PresetFooterEvent, PresetPicker, PresetRow, PresetSource, PresetState};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use egui::{Rect, Response, Ui};
|
||||
@@ -78,14 +76,15 @@ impl ContourWords {
|
||||
}
|
||||
}
|
||||
|
||||
/// A host's interpolation of a contour's points, shared with the thumbnails' painters.
|
||||
pub(crate) type SharedSampler = Arc<dyn Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync>;
|
||||
/// A host's interpolation of a contour's points (levels in, levels out), shared with the thumbnails' painters. A `fn`,
|
||||
/// which captures nothing, so the contour presets key it by its address.
|
||||
pub type ContourSampler = fn(&[[f32; 2]]) -> Vec<f32>;
|
||||
|
||||
/// The levels of a contour as a curve: input and output run `0..=255`.
|
||||
const LEVELS: f32 = 255.0;
|
||||
|
||||
/// A contour a picker lists: one of the built-in contours or one of the user's.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum ContourKey {
|
||||
/// The built-in contour at this place of [`Contour::presets`].
|
||||
@@ -153,24 +152,39 @@ impl Outcome for ContourFieldOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the contour picker: the built-in contours, then the user's, named by `words`, with a thumbnail of each
|
||||
/// curve. `sampler` interpolates the points as the engine does; without it the thumbnails use a monotone cubic.
|
||||
pub fn contour_rows(presets: &[Contour], user: &[Contour], words: &ContourWords, sampler: Option<SharedSampler>) -> Vec<PresetRow<ContourKey>> {
|
||||
/// What the contour presets are built from.
|
||||
#[derive(craft_ui::contract::MemoProps)]
|
||||
struct ContourInputs<'a> {
|
||||
presets: &'a [Contour],
|
||||
user: &'a [Contour],
|
||||
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
|
||||
sampler: Option<ContourSampler>,
|
||||
}
|
||||
|
||||
/// The presets of the contour picker: the built-in contours, then the user's, with a thumbnail of each curve; the
|
||||
/// user's may be deleted. `sampler` interpolates the points as the engine does; without it the thumbnails use a
|
||||
/// monotone cubic.
|
||||
pub fn contour_source<'a>(presets: &'a [Contour], user: &'a [Contour], sampler: Option<ContourSampler>) -> PresetSource<'a, ContourKey> {
|
||||
let fns = PresetFns::new(contour_rows).can_delete(|_, key| matches!(key, ContourKey::User(_)));
|
||||
PresetSource::new(ContourInputs { presets, user, sampler }, fns)
|
||||
}
|
||||
|
||||
/// The rows of the contour picker, named by the scope's words.
|
||||
fn contour_rows(inputs: &ContourInputs<'_>, env: &Env) -> Vec<PresetRow<ContourKey>> {
|
||||
let words = env.words::<ContourWords>();
|
||||
let sampler = inputs.sampler;
|
||||
let row = |key: ContourKey, contour: &Contour| {
|
||||
let name = words.contour_name(&contour.name).to_owned();
|
||||
let curve = Arc::new(to_curve(contour));
|
||||
let sampler = sampler.clone();
|
||||
PresetRow::item(key, name, 0).preview(ThumbAspect::SQUARE, move |painter, rect| paint_thumbnail(painter, rect, &curve, sampler.as_deref()))
|
||||
let curve = to_curve(contour);
|
||||
PresetRow::item(key, name, 0).preview(ThumbAspect::SQUARE, move |painter, rect| paint_thumbnail(painter, rect, &curve, sampler))
|
||||
};
|
||||
let presets = presets.iter().enumerate().map(|(i, contour)| row(ContourKey::Preset(i), contour));
|
||||
let user = user.iter().enumerate().map(|(i, contour)| row(ContourKey::User(i), contour));
|
||||
let presets = inputs.presets.iter().enumerate().map(|(i, contour)| row(ContourKey::Preset(i), contour));
|
||||
let user = inputs.user.iter().enumerate().map(|(i, contour)| row(ContourKey::User(i), contour));
|
||||
presets.chain(user).collect()
|
||||
}
|
||||
|
||||
type SamplerFn = dyn Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync;
|
||||
|
||||
/// A thumbnail of a contour: its curve in the curve preview's look (plot, quarter grid, diagonal).
|
||||
fn paint_thumbnail(painter: &ContentPainterCx<'_>, rect: Rect, curve: &Curve, sampler: Option<&SamplerFn>) {
|
||||
fn paint_thumbnail(painter: &ContentPainterCx<'_>, rect: Rect, curve: &Curve, sampler: Option<ContourSampler>) {
|
||||
let Curve::Points { points, corners } = curve else { return };
|
||||
let outputs = Curve::through(points, corners, |points| match sampler {
|
||||
Some(sampler) => sampler(points),
|
||||
@@ -206,21 +220,22 @@ pub fn from_curve(curve: &Curve, name: &str) -> Option<Contour> {
|
||||
pub struct ContourField<'a> {
|
||||
label: Label,
|
||||
contour: Bind<'a, Contour>,
|
||||
rows: &'a [PresetRow<ContourKey>],
|
||||
source: &'a PresetSource<'a, ContourKey>,
|
||||
state: Bind<'a, PresetState<ContourKey>>,
|
||||
user: &'a [Contour],
|
||||
anti_alias: Option<Bind<'a, Option<bool>>>,
|
||||
}
|
||||
|
||||
impl<'a> ContourField<'a> {
|
||||
/// A field named `label` over `contour`, choosing among `rows` ([`contour_rows`]); `state` is the browser's view.
|
||||
/// A field named `label` over `contour`, choosing among `source` ([`contour_source`]); `state` is the browser's
|
||||
/// view.
|
||||
pub fn new(
|
||||
label: impl Into<Label>,
|
||||
contour: Bind<'a, Contour>,
|
||||
rows: &'a [PresetRow<ContourKey>],
|
||||
source: &'a PresetSource<'a, ContourKey>,
|
||||
state: Bind<'a, PresetState<ContourKey>>,
|
||||
) -> Self {
|
||||
Self { label: label.into(), contour, rows, state, user: &[], anti_alias: None }
|
||||
Self { label: label.into(), contour, source, state, user: &[], anti_alias: None }
|
||||
}
|
||||
|
||||
/// The user's contours, the targets of [`ContourKey::User`].
|
||||
@@ -237,7 +252,7 @@ impl<'a> ContourField<'a> {
|
||||
|
||||
/// Shows the field and returns this pass's edit and requests.
|
||||
pub fn show(self, ui: &mut Ui) -> ContourFieldOutput {
|
||||
let Self { label, mut contour, rows, mut state, user, mut anti_alias } = self;
|
||||
let Self { label, mut contour, source, mut state, user, mut anti_alias } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<ContourWords>();
|
||||
let presets = Contour::presets();
|
||||
@@ -254,10 +269,9 @@ impl<'a> ContourField<'a> {
|
||||
let mut anti_events = EditEvents::new();
|
||||
let mut picked = None;
|
||||
Row::new().show(ui, |ui, root| {
|
||||
let picker = PresetPicker::new(label.clone(), Bind::bound(&mut key), rows, state.reborrowed())
|
||||
let picker = PresetPicker::new(label.clone(), Bind::bound(&mut key), source, state.reborrowed())
|
||||
.field(PickerField::Thumbnail)
|
||||
.columns(4)
|
||||
.can_delete(|key| matches!(key, ContourKey::User(_)))
|
||||
.edit_face()
|
||||
.show(ui);
|
||||
for event in &picker.events {
|
||||
|
||||
@@ -3,11 +3,10 @@
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::patterns::presets::PresetState;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::{ContourField, ContourKey, ContourWords, contour_rows};
|
||||
use super::{ContourField, ContourKey, contour_source};
|
||||
use crate::layer_style::{Contour, ContourPoint};
|
||||
|
||||
fn user_contours() -> Vec<Contour> {
|
||||
@@ -18,9 +17,9 @@ fn user_contours() -> Vec<Contour> {
|
||||
/// The field over `start` with its Anti-aliased check box, in the host's Field, and the contour it holds as the
|
||||
/// readout.
|
||||
fn field(ui: &mut Ui, data: &mut StoryData, start: Contour, anti_alias: bool) -> StoryOutput {
|
||||
let words = Env::of(ui).words::<ContourWords>();
|
||||
let user = user_contours();
|
||||
let rows = contour_rows(&Contour::presets(), &user, &words, None);
|
||||
let presets = Contour::presets();
|
||||
let rows = contour_source(&presets, &user, None);
|
||||
let ((contour, state, anti_alias), field_at) = data.value_at("field", (start, PresetState::<ContourKey>::new(), Some(anti_alias)));
|
||||
let shown = Field::new("Contour").show(ui, |ui, _| {
|
||||
ContourField::new("Contour", field_at.bind(&mut *contour), &rows, field_at.bind(&mut *state))
|
||||
|
||||
@@ -8,18 +8,17 @@ use craft_theme::{Srgba, TypeRole};
|
||||
use craft_ui::contract::{CommandSet as _, Entry, NoValue, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::{Divider, Text};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetSource};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use super::blending::{BlendingInput, blending_page};
|
||||
use super::contour::SharedSampler;
|
||||
use super::contour::{ContourAction, ContourRequest, ContourWords};
|
||||
use super::contour::{ContourAction, ContourRequest, ContourSampler};
|
||||
use super::labels::LayerStyleWords;
|
||||
use super::list::{LayerStyleCommand, ListAction, effect_list};
|
||||
use super::page::{PageInput, effect_page, push_edit};
|
||||
use super::styles::{StylePresets, styles_page};
|
||||
use super::styles::styles_page;
|
||||
use craft_behavior::{EditEvent, EditEvents, Mixed};
|
||||
|
||||
use crate::layer_style::{Contour, EffectId, EffectKind, EffectSpec, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams, StyleValue};
|
||||
@@ -102,8 +101,8 @@ impl LayerStyleOutput {
|
||||
/// before the page changes.
|
||||
/// - The page title is the effect's name, plain. New Style… and the Preview check box are the host's, in the button
|
||||
/// column under OK and Cancel (Photoshop's place), the check over [`LayerStyleDraft::preview`].
|
||||
/// - The Styles page ([`StylePresets`]), the Blending Options page, or an effect page drawn from the kind's
|
||||
/// [`EffectSpec`].
|
||||
/// - The Styles page ([`style_presets`](Self::style_presets)), the Blending Options page, or an effect page drawn from
|
||||
/// the kind's [`EffectSpec`].
|
||||
/// - Use Global Light: on an effect that uses it, the Angle edits the shared light angle of every such effect
|
||||
/// ([`LayerStyleDraft::set_param`]).
|
||||
///
|
||||
@@ -123,10 +122,10 @@ pub struct LayerStyleDialog<'a> {
|
||||
specs: Option<&'a [EffectSpec]>,
|
||||
blend_keys: Option<&'a HashMap<String, String>>,
|
||||
blend_modes: &'a [Entry<String>],
|
||||
patterns: &'a [PresetRow<String>],
|
||||
patterns: Option<&'a PresetSource<'a, String>>,
|
||||
user_contours: &'a [Contour],
|
||||
sampler: Option<SharedSampler>,
|
||||
style_presets: Option<StylePresets<'a>>,
|
||||
sampler: Option<ContourSampler>,
|
||||
style_presets: Option<&'a PresetSource<'a, String>>,
|
||||
gradient_presets: &'a [(String, GradientStops)],
|
||||
}
|
||||
|
||||
@@ -141,7 +140,7 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
specs: None,
|
||||
blend_keys: None,
|
||||
blend_modes: &[],
|
||||
patterns: &[],
|
||||
patterns: None,
|
||||
user_contours: &[],
|
||||
sampler: None,
|
||||
style_presets: None,
|
||||
@@ -177,8 +176,8 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
}
|
||||
|
||||
/// The patterns Pattern Overlay offers, keyed by the pattern's key.
|
||||
pub fn patterns(mut self, patterns: &'a [PresetRow<String>]) -> Self {
|
||||
self.patterns = patterns;
|
||||
pub fn patterns(mut self, patterns: &'a PresetSource<'a, String>) -> Self {
|
||||
self.patterns = Some(patterns);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -190,19 +189,14 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
|
||||
/// The host's interpolation of a contour's points: the output of every input level through the points, so the
|
||||
/// contour fields draw the curve the engine renders; a monotone cubic by default.
|
||||
pub fn sampler(mut self, sample: impl Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync + 'static) -> Self {
|
||||
self.sampler = Some(std::sync::Arc::new(sample));
|
||||
pub fn sampler(mut self, sample: ContourSampler) -> Self {
|
||||
self.sampler = Some(sample);
|
||||
self
|
||||
}
|
||||
|
||||
/// [`sampler`](Self::sampler) as the host keeps it: `None` for the default.
|
||||
pub(super) fn shared_sampler(mut self, sampler: Option<SharedSampler>) -> Self {
|
||||
self.sampler = sampler;
|
||||
self
|
||||
}
|
||||
|
||||
/// The Styles page's presets; without them the page shows only its title.
|
||||
pub fn style_presets(mut self, presets: StylePresets<'a>) -> Self {
|
||||
/// The Styles page's presets, keyed by the preset's name and painted by the source's thumbnail painter; without
|
||||
/// them the page shows only its title.
|
||||
pub fn style_presets(mut self, presets: &'a PresetSource<'a, String>) -> Self {
|
||||
self.style_presets = Some(presets);
|
||||
self
|
||||
}
|
||||
@@ -225,7 +219,6 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
} = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<LayerStyleWords>();
|
||||
let contour_words = env.words::<ContourWords>();
|
||||
let units = env.units();
|
||||
let base: Cow<'_, [EffectSpec]> = match specs {
|
||||
Some(specs) => Cow::Borrowed(specs),
|
||||
@@ -239,6 +232,8 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
}
|
||||
None => &base,
|
||||
};
|
||||
let none = PresetSource::new((), PresetFns::new(|_, _| Vec::new()));
|
||||
let patterns = patterns.unwrap_or(&none);
|
||||
let mut work = Work { next: draft.clone(), edit: EditEvents::new(), extras: Extras::default() };
|
||||
let title = page_title(draft.page, draft, &words);
|
||||
let name = label.as_str().to_owned();
|
||||
@@ -252,14 +247,13 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
blend_modes,
|
||||
patterns,
|
||||
user_contours,
|
||||
sampler: sampler.as_ref(),
|
||||
sampler,
|
||||
gradient_presets,
|
||||
channel_names,
|
||||
words: &words,
|
||||
contour_words: &contour_words,
|
||||
units: &units,
|
||||
};
|
||||
work.page(ui, &page, style_presets.as_ref());
|
||||
work.page(ui, &page, style_presets);
|
||||
});
|
||||
if let Some(actions) = list.inner {
|
||||
work.list_actions(actions, specs, &name);
|
||||
@@ -333,13 +327,12 @@ struct PageEnv<'a> {
|
||||
draft: &'a LayerStyleDraft,
|
||||
specs: &'a [EffectSpec],
|
||||
blend_modes: &'a [Entry<String>],
|
||||
patterns: &'a [PresetRow<String>],
|
||||
patterns: &'a PresetSource<'a, String>,
|
||||
user_contours: &'a [Contour],
|
||||
sampler: Option<&'a SharedSampler>,
|
||||
sampler: Option<ContourSampler>,
|
||||
gradient_presets: &'a [(String, GradientStops)],
|
||||
channel_names: &'a [String],
|
||||
words: &'a LayerStyleWords,
|
||||
contour_words: &'a ContourWords,
|
||||
units: &'a craft_ui::runtime::env::Units,
|
||||
}
|
||||
|
||||
@@ -403,7 +396,7 @@ impl Work {
|
||||
}
|
||||
|
||||
/// Draws the page of the pass; its controls add their edits to the pass's.
|
||||
fn page(&mut self, ui: &mut Ui, env: &PageEnv<'_>, presets: Option<&StylePresets<'_>>) {
|
||||
fn page(&mut self, ui: &mut Ui, env: &PageEnv<'_>, presets: Option<&PresetSource<'_, String>>) {
|
||||
let (words, draft) = (env.words, env.draft);
|
||||
let instance = match draft.page {
|
||||
LayerStylePage::Effect(id) => draft.style.effect(id).cloned(),
|
||||
@@ -437,7 +430,6 @@ impl Work {
|
||||
sampler: env.sampler,
|
||||
gradient_presets: env.gradient_presets,
|
||||
words,
|
||||
contour_words: env.contour_words,
|
||||
units: env.units,
|
||||
};
|
||||
let out = effect_page(ui, &input);
|
||||
|
||||
@@ -12,7 +12,7 @@ use craft_ui::contract::{
|
||||
};
|
||||
use craft_ui::dialog::{ButtonPlace, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft_ui::patterns::form_dialogs::FormDialog;
|
||||
use craft_ui::patterns::presets::{PresetRow, ThumbInfo};
|
||||
use craft_ui::patterns::presets::PresetSource;
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
@@ -20,9 +20,9 @@ use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use craft_ui::style::{ComponentStyle, StyleCx};
|
||||
use egui::{Context, Rect, Response, Ui, Vec2};
|
||||
|
||||
use super::contour::SharedSampler;
|
||||
use super::contour::ContourSampler;
|
||||
use super::labels::LayerStyleWords;
|
||||
use super::{ContourAction, ContourRequest, LayerStyleDialog, LayerStyleOutput, StylePresets};
|
||||
use super::{ContourAction, ContourRequest, LayerStyleDialog, LayerStyleOutput};
|
||||
use crate::layer_style::{
|
||||
Contour, EffectId, EffectKind, EffectSpec, FieldKind, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams, StyleValue,
|
||||
};
|
||||
@@ -66,9 +66,6 @@ impl LayerStyleOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints a style preset's thumbnail.
|
||||
type Thumb = dyn Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + Send;
|
||||
|
||||
/// Paints the preview swatch beside the footer buttons from the draft.
|
||||
type PreviewPaint = dyn Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync;
|
||||
|
||||
@@ -158,10 +155,10 @@ pub struct HostedLayerStyle {
|
||||
specs: Option<Vec<EffectSpec>>,
|
||||
blend_keys: Option<HashMap<String, String>>,
|
||||
blend_modes: Vec<Entry<String>>,
|
||||
patterns: Vec<PresetRow<String>>,
|
||||
patterns: Option<PresetSource<'static, String>>,
|
||||
user_contours: Vec<Contour>,
|
||||
sampler: Option<SharedSampler>,
|
||||
styles: Option<(Vec<PresetRow<String>>, Box<Thumb>)>,
|
||||
sampler: Option<ContourSampler>,
|
||||
styles: Option<PresetSource<'static, String>>,
|
||||
gradient_presets: Vec<(String, GradientStops)>,
|
||||
canvas: Option<egui::Id>,
|
||||
preview_thumb: Option<Arc<PreviewPaint>>,
|
||||
@@ -187,7 +184,7 @@ impl HostedLayerStyle {
|
||||
specs: None,
|
||||
blend_keys: None,
|
||||
blend_modes: Vec::new(),
|
||||
patterns: Vec::new(),
|
||||
patterns: None,
|
||||
user_contours: Vec::new(),
|
||||
sampler: None,
|
||||
styles: None,
|
||||
@@ -224,8 +221,8 @@ impl HostedLayerStyle {
|
||||
|
||||
/// [`LayerStyleDialog::patterns`].
|
||||
#[must_use]
|
||||
pub fn patterns(mut self, patterns: Vec<PresetRow<String>>) -> Self {
|
||||
self.patterns = patterns;
|
||||
pub fn patterns(mut self, patterns: PresetSource<'static, String>) -> Self {
|
||||
self.patterns = Some(patterns);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -238,19 +235,15 @@ impl HostedLayerStyle {
|
||||
|
||||
/// [`LayerStyleDialog::sampler`].
|
||||
#[must_use]
|
||||
pub fn sampler(mut self, sample: impl Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync + 'static) -> Self {
|
||||
self.sampler = Some(std::sync::Arc::new(sample));
|
||||
pub fn sampler(mut self, sample: ContourSampler) -> Self {
|
||||
self.sampler = Some(sample);
|
||||
self
|
||||
}
|
||||
|
||||
/// The Styles page's presets `rows`, each thumbnail painted by `thumb` ([`StylePresets::new`]).
|
||||
/// [`LayerStyleDialog::style_presets`].
|
||||
#[must_use]
|
||||
pub fn style_presets(
|
||||
mut self,
|
||||
rows: Vec<PresetRow<String>>,
|
||||
thumb: impl Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + Send + 'static,
|
||||
) -> Self {
|
||||
self.styles = Some((rows, Box::new(thumb)));
|
||||
pub fn style_presets(mut self, presets: PresetSource<'static, String>) -> Self {
|
||||
self.styles = Some(presets);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -379,18 +372,22 @@ impl StackDialog for HostedLayerStyle {
|
||||
}
|
||||
let mut body = LayerStyleDialog::new(label.clone(), draft, channel_names.as_slice())
|
||||
.blend_modes(blend_modes.as_slice())
|
||||
.patterns(patterns.as_slice())
|
||||
.user_contours(user_contours.as_slice())
|
||||
.shared_sampler(sampler.clone())
|
||||
.gradient_presets(gradient_presets.as_slice());
|
||||
if let Some(patterns) = patterns.as_ref() {
|
||||
body = body.patterns(patterns);
|
||||
}
|
||||
if let Some(sampler) = *sampler {
|
||||
body = body.sampler(sampler);
|
||||
}
|
||||
if let Some(specs) = specs.as_deref() {
|
||||
body = body.specs(specs);
|
||||
}
|
||||
if let Some(map) = blend_keys.as_ref() {
|
||||
body = body.blend_keys(map);
|
||||
}
|
||||
if let Some((rows, thumb)) = styles.as_ref() {
|
||||
body = body.style_presets(StylePresets::new(rows, |cx, rect, info| thumb(cx, rect, info)));
|
||||
if let Some(presets) = styles.as_ref() {
|
||||
body = body.style_presets(presets);
|
||||
}
|
||||
let out = body.show(ui);
|
||||
#[cfg(feature = "screen-testing")]
|
||||
|
||||
@@ -36,13 +36,12 @@ mod styles;
|
||||
|
||||
pub use blend_if::{BlendIfBar, BlendIfWords};
|
||||
pub use contour::{
|
||||
ContourAction, ContourEditorDialog, ContourField, ContourFieldOutput, ContourKey, ContourRequest, ContourWords, contour_rows, from_curve,
|
||||
to_curve,
|
||||
ContourAction, ContourEditorDialog, ContourField, ContourFieldOutput, ContourKey, ContourRequest, ContourSampler, ContourWords, contour_source,
|
||||
from_curve, to_curve,
|
||||
};
|
||||
pub use dialog::{LayerStyleDialog, LayerStyleOutput};
|
||||
pub use hosted::{HostedLayerStyle, LayerStyleAsk};
|
||||
pub use labels::LayerStyleWords;
|
||||
pub use list::LayerStyleCommand;
|
||||
pub use styles::StylePresets;
|
||||
|
||||
pub use crate::layer_style::LayerStylePage;
|
||||
|
||||
@@ -12,16 +12,16 @@ use craft_ui::display::Text;
|
||||
use craft_ui::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
|
||||
use craft_ui::layout::RowAlign;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::patterns::presets::{PresetPicker, PresetRow, PresetState};
|
||||
use craft_ui::patterns::presets::{PresetPicker, PresetSource, PresetState};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Label, UnitKind, Units};
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind, Units};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::text::NumberField;
|
||||
use craft_ui::value_drag::AngleDial;
|
||||
use egui::Ui;
|
||||
|
||||
use super::blending::BlendingOp;
|
||||
use super::contour::{ContourAction, ContourField, ContourKey, ContourRequest, ContourWords, SharedSampler, contour_rows};
|
||||
use super::contour::{ContourAction, ContourField, ContourKey, ContourRequest, ContourSampler, contour_source};
|
||||
use super::labels::LayerStyleWords;
|
||||
use crate::layer_style::{
|
||||
Contour, EffectField, EffectId, EffectInstance, EffectSpec, FieldKind, FieldUnit, LayerStyle, LayerStyleDraft, StyleParams, StyleValue,
|
||||
@@ -74,12 +74,11 @@ pub(super) struct PageInput<'a> {
|
||||
pub instance: &'a EffectInstance,
|
||||
pub style: &'a LayerStyle,
|
||||
pub blend_modes: &'a [Entry<String>],
|
||||
pub patterns: &'a [PresetRow<String>],
|
||||
pub patterns: &'a PresetSource<'a, String>,
|
||||
pub user_contours: &'a [Contour],
|
||||
pub sampler: Option<&'a SharedSampler>,
|
||||
pub sampler: Option<ContourSampler>,
|
||||
pub gradient_presets: &'a [(String, GradientStops)],
|
||||
pub words: &'a LayerStyleWords,
|
||||
pub contour_words: &'a ContourWords,
|
||||
pub units: &'a Units,
|
||||
}
|
||||
|
||||
@@ -317,7 +316,7 @@ fn field_row(ui: &mut Ui, input: &PageInput<'_>, field: &EffectField, shown: &St
|
||||
}
|
||||
FieldKind::Pattern => {
|
||||
let stored = text_of(shown.get(key)).filter(|t| !t.is_empty());
|
||||
let first = input.patterns.iter().find(|row| !row.is_group()).map(|row| row.key.clone());
|
||||
let first = input.patterns.rows(ui.ctx(), &Env::of(ui)).iter().find(|row| !row.is_group()).map(|row| row.key.clone());
|
||||
let current = stored.map(str::to_owned).or(first.clone());
|
||||
let picker = Field::new(label.clone())
|
||||
.id_salt(key)
|
||||
@@ -339,7 +338,7 @@ fn field_row(ui: &mut Ui, input: &PageInput<'_>, field: &EffectField, shown: &St
|
||||
let before = anti_alias.as_deref().map(|k| shown.bool(k).unwrap_or(false));
|
||||
let mut checked = before;
|
||||
let presets = Contour::presets();
|
||||
let rows = contour_rows(&presets, input.user_contours, input.contour_words, input.sampler.cloned());
|
||||
let rows = contour_source(&presets, input.user_contours, input.sampler);
|
||||
// A field with no visible label (Emboss's contour under its check box) is still named for assistive tech.
|
||||
let name = if label.as_str().is_empty() {
|
||||
words.field("contour").cloned().unwrap_or_else(|| Label::from(field.key.to_string()))
|
||||
|
||||
@@ -7,10 +7,11 @@ use craft_theme::Srgba;
|
||||
use craft_ui::contract::Entry;
|
||||
use craft_ui::dialog::stories::hosted;
|
||||
use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut, blend_entries};
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
use egui::{Rect, Ui};
|
||||
|
||||
use super::{HostedLayerStyle, LayerStyleDialog};
|
||||
use crate::layer_style::{BlendIf, Blending, EffectId, EffectInstance, EffectKind, EffectSpec, LayerStyle, LayerStyleDraft, LayerStylePage};
|
||||
@@ -71,7 +72,8 @@ fn gradient_presets(words: &LayerStyleStoryWords) -> Vec<(String, GradientStops)
|
||||
]
|
||||
}
|
||||
|
||||
fn patterns(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
|
||||
fn pattern_rows(_: &(), env: &Env) -> Vec<PresetRow<String>> {
|
||||
let words = env.words::<LayerStyleStoryWords>();
|
||||
vec![
|
||||
PresetRow::group("group".to_owned(), words.pattern_group.as_str(), 0),
|
||||
PresetRow::item("bubbles".to_owned(), words.pattern_bubbles.as_str(), 1),
|
||||
@@ -79,7 +81,8 @@ fn patterns(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
|
||||
]
|
||||
}
|
||||
|
||||
fn style_rows(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
|
||||
fn style_rows(_: &(), env: &Env) -> Vec<PresetRow<String>> {
|
||||
let words = env.words::<LayerStyleStoryWords>();
|
||||
vec![
|
||||
PresetRow::group("group".to_owned(), words.style_group.as_str(), 0),
|
||||
PresetRow::item("Soft".to_owned(), words.style_soft.as_str(), 1),
|
||||
@@ -87,6 +90,11 @@ fn style_rows(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The Styles page's fake thumbnails.
|
||||
fn checker(_: &(), cx: &ContentPainterCx<'_>, rect: Rect, _: ThumbInfo<'_, String>) {
|
||||
cx.checker(rect);
|
||||
}
|
||||
|
||||
/// A style with one instance of each of `kinds`, turned on, in `kinds` order.
|
||||
fn style_of(kinds: &[EffectKind]) -> LayerStyle {
|
||||
let effects = kinds
|
||||
@@ -105,9 +113,9 @@ fn host(ui: &mut Ui, data: &mut StoryData, start: impl FnOnce() -> LayerStyleDra
|
||||
hosted(ui, data, (), || {
|
||||
HostedLayerStyle::new("Layer Style", start(), names)
|
||||
.blend_modes(blend_modes(&words))
|
||||
.patterns(patterns(&words))
|
||||
.patterns(PresetSource::new((), PresetFns::new(pattern_rows)))
|
||||
.gradient_presets(gradient_presets(&words))
|
||||
.style_presets(style_rows(&words), |cx, rect, _| cx.checker(rect))
|
||||
.style_presets(PresetSource::new((), PresetFns::new(style_rows).thumb(checker)))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,8 @@
|
||||
use craft_theme::TypeRole;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetRow, PresetState, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use egui::{Rect, Ui};
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetSource, PresetState};
|
||||
use egui::Ui;
|
||||
|
||||
use super::labels::LayerStyleWords;
|
||||
|
||||
@@ -13,23 +12,6 @@ use super::labels::LayerStyleWords;
|
||||
/// dialog page around it scrolls too.
|
||||
const STYLE_ROWS: u16 = 5;
|
||||
|
||||
/// The host's style presets for the Styles page: the rows (groups and presets keyed by the preset's name) and the
|
||||
/// painter of one preset's thumbnail. The page shows them in the library [`PresetBrowser`] grid and keeps the
|
||||
/// browser's view state itself.
|
||||
pub struct StylePresets<'a> {
|
||||
pub(super) rows: &'a [PresetRow<String>],
|
||||
pub(super) thumb: Thumb<'a>,
|
||||
}
|
||||
|
||||
type Thumb<'a> = Box<dyn Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + 'a>;
|
||||
|
||||
impl<'a> StylePresets<'a> {
|
||||
/// The presets `rows`, each thumbnail painted by `thumb`.
|
||||
pub fn new(rows: &'a [PresetRow<String>], thumb: impl Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + 'a) -> Self {
|
||||
StylePresets { rows, thumb: Box::new(thumb) }
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Styles page asked for.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(super) struct StylesOutput {
|
||||
@@ -39,15 +21,13 @@ pub(super) struct StylesOutput {
|
||||
pub apply_style: Option<String>,
|
||||
}
|
||||
|
||||
/// Draws the page: the title, then the browser. Without presets the page shows only the title.
|
||||
pub(super) fn styles_page(ui: &mut Ui, presets: Option<&StylePresets<'_>>, words: &LayerStyleWords) -> StylesOutput {
|
||||
/// Draws the page: the title, then the host's style presets (groups and presets keyed by the preset's name) in the
|
||||
/// library browser grid, whose view state the page keeps. Without presets the page shows only the title.
|
||||
pub(super) fn styles_page(ui: &mut Ui, presets: Option<&PresetSource<'_, String>>, words: &LayerStyleWords) -> StylesOutput {
|
||||
Text::new(words.styles.clone()).role(TypeRole::Title).show(ui);
|
||||
let mut out = StylesOutput { apply_style: None };
|
||||
if let Some(StylePresets { rows, thumb }) = presets {
|
||||
let browser = PresetBrowser::new(words.styles.clone(), Bind::<PresetState<String>>::kept(), rows)
|
||||
.thumb(move |cx, rect, info| thumb(cx, rect, info))
|
||||
.row_menu(false)
|
||||
.max_rows(STYLE_ROWS);
|
||||
if let Some(presets) = presets {
|
||||
let browser = PresetBrowser::new(words.styles.clone(), Bind::<PresetState<String>>::kept(), presets).row_menu(false).max_rows(STYLE_ROWS);
|
||||
for event in browser.show(ui).events {
|
||||
if let PresetEvent::Select { key, .. } | PresetEvent::Activate { key, .. } = event {
|
||||
out.apply_style = Some(key);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -86,7 +86,7 @@ pub use histogram::{
|
||||
};
|
||||
pub use layer_style::{
|
||||
BlendIfBar, BlendIfWords, ContourField, ContourFieldOutput, ContourWords, HostedLayerStyle, LayerStyleAsk, LayerStyleDialog, LayerStyleOutput,
|
||||
LayerStyleWords, StylePresets,
|
||||
LayerStyleWords,
|
||||
};
|
||||
pub use liquify::{
|
||||
LiquifyCommands, LiquifyDone, LiquifyEvent, LiquifyOpen, LiquifyPanel, LiquifyPanelOutput, LiquifySession, LiquifySettings, LiquifySource,
|
||||
|
||||
@@ -4,7 +4,19 @@ use crate::ui::histogram::LevelRange;
|
||||
use crate::ui::scopes::clipping::{ClippingDiagnostic, ClippingMode, ClippingWarnings};
|
||||
|
||||
/// The panel's view (its menu's Compact, Expanded and All Channels View).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(
|
||||
Clone,
|
||||
Copy,
|
||||
Debug,
|
||||
Default,
|
||||
PartialEq,
|
||||
Eq,
|
||||
Hash,
|
||||
serde::Serialize,
|
||||
serde::Deserialize,
|
||||
craft_ui::contract::MemoProps,
|
||||
craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ScopeView {
|
||||
@@ -20,7 +32,7 @@ pub enum ScopeView {
|
||||
/// The scope panel's persisted section: the app keeps it with its preferences (PhotoCraft's
|
||||
/// `histogramPanel` and `filter.cameraRaw.scope`). Unknown fields are ignored, missing ones take
|
||||
/// their defaults.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ScopeSettings {
|
||||
@@ -93,7 +105,7 @@ impl ScopeSettings {
|
||||
|
||||
/// What the panel keeps for the app between passes: the persisted settings and the selected
|
||||
/// level range (not persisted).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct ScopePanelState {
|
||||
/// The persisted section.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -11,9 +11,11 @@
|
||||
//! ```no_run
|
||||
//! use craft_imaging::ui::transform_preview::{PreviewMap, PreviewPixels, PreviewTextures, TransformPreview};
|
||||
//! use craft_ui::contract::Show as _;
|
||||
//! use craft_ui::primitives::Serials;
|
||||
//! # fn demo(ui: &mut egui::Ui, canvas_rect: egui::Rect, image: egui::ColorImage, quad: [kurbo::Point; 4]) {
|
||||
//! // Once per session:
|
||||
//! let textures = PreviewTextures::new("ft-preview", PreviewPixels::new(image, [1.0, 1.0]));
|
||||
//! // Once per session, with the `Serials` the owner of the previews holds:
|
||||
//! let mut serials = Serials::default();
|
||||
//! let textures = PreviewTextures::new(&mut serials, "ft-preview", PreviewPixels::new(image, [1.0, 1.0]));
|
||||
//! // Every pass, in the canvas body under the guides and the box:
|
||||
//! TransformPreview::new("Moving layer", &textures).map(PreviewMap::quad(quad)).opacity(0.8).clip([800, 600]).show_at(ui, canvas_rect);
|
||||
//! # }
|
||||
|
||||
@@ -9,6 +9,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError};
|
||||
use craft_behavior::kurbo::{Point, Rect};
|
||||
use craft_ui::canvas::{PixelRect, RasterSource};
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::primitives::Serials;
|
||||
use craft_ui::testing::canvas_story::StoryDocument;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::{Color32, ColorImage, Ui};
|
||||
@@ -102,7 +103,7 @@ impl Document {
|
||||
return Arc::clone(textures);
|
||||
}
|
||||
let name = format!("transform-story-{}x{}", size[0], size[1]);
|
||||
let textures = Arc::new(PreviewTextures::from_levels(name, pyramid(size), [1.0, 1.0]));
|
||||
let textures = Arc::new(PreviewTextures::from_levels(&mut Serials::default(), name, pyramid(size), [1.0, 1.0]));
|
||||
kept.push((size, Arc::clone(&textures)));
|
||||
textures
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
//! [`PreviewPixels`] and [`PreviewTextures`]: the moving pixels of a transform, read once and
|
||||
//! uploaded as a mip chain built on demand, off the UI thread where a finer level can stand in.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use craft_host::queue::Cancel;
|
||||
use craft_ui::primitives::{
|
||||
LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, TextureLoader, TextureState, TextureStatistics, TextureStore,
|
||||
LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, Serials, TextureLoader, TextureState, TextureStatistics, TextureStore,
|
||||
TextureStoreOptions,
|
||||
};
|
||||
use egui::{Color32, ColorImage, Context, TextureId, TextureOptions};
|
||||
@@ -114,9 +113,6 @@ pub struct TextureChoice {
|
||||
/// The key of a preview's level in the shared stores: the preview's name and the level.
|
||||
type LevelKey = (Arc<str>, u32);
|
||||
|
||||
/// Tells previews apart in the store revisions: a preview made under an old name with new pixels gets a new serial.
|
||||
static SERIAL: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The moving pixels uploaded for the preview: level 0 at once, the other mip levels (2 × 2 box filtered) and the
|
||||
/// nearest-filtered level 0 on first use. The CPU levels are kept for the session.
|
||||
///
|
||||
@@ -137,21 +133,22 @@ pub struct PreviewTextures {
|
||||
}
|
||||
|
||||
impl PreviewTextures {
|
||||
/// The preview of `pixels`, named `name`: the store entries are keyed by it. Nothing is
|
||||
/// uploaded until the preview is painted.
|
||||
pub fn new(name: impl Into<String>, pixels: PreviewPixels) -> Self {
|
||||
/// The preview of `pixels`, named `name`: the store entries are keyed by it. `serials` tells this preview from an
|
||||
/// earlier one of the same name (new pixels under an old name replace its textures); the previews of one owner
|
||||
/// share it. Nothing is uploaded until the preview is painted.
|
||||
pub fn new(serials: &mut Serials, name: impl Into<String>, pixels: PreviewPixels) -> Self {
|
||||
let base_uv = pixels.base_uv;
|
||||
Self::over(name, vec![Arc::new(pixels.image)], base_uv)
|
||||
Self::over(serials, name, vec![Arc::new(pixels.image)], base_uv)
|
||||
}
|
||||
|
||||
/// The preview over `levels` already built, level 0 first, covering the source with `base_uv`.
|
||||
#[cfg(feature = "screen-testing")]
|
||||
pub(crate) fn from_levels(name: impl Into<String>, levels: Vec<Arc<ColorImage>>, base_uv: [f32; 2]) -> Self {
|
||||
Self::over(name, levels, base_uv)
|
||||
pub(crate) fn from_levels(serials: &mut Serials, name: impl Into<String>, levels: Vec<Arc<ColorImage>>, base_uv: [f32; 2]) -> Self {
|
||||
Self::over(serials, name, levels, base_uv)
|
||||
}
|
||||
|
||||
fn over(name: impl Into<String>, levels: Vec<Arc<ColorImage>>, base_uv: [f32; 2]) -> Self {
|
||||
let serial = SERIAL.fetch_add(1, Ordering::Relaxed);
|
||||
fn over(serials: &mut Serials, name: impl Into<String>, levels: Vec<Arc<ColorImage>>, base_uv: [f32; 2]) -> Self {
|
||||
let serial = serials.mint();
|
||||
Self { name: Arc::from(name.into()), serial, images: Arc::new(Mutex::new(levels)), base_uv }
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -4,10 +4,9 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_imaging::layer_style::Contour;
|
||||
use craft_imaging::ui::layer_style::{ContourField, ContourKey, ContourRequest, ContourWords, contour_rows};
|
||||
use craft_imaging::ui::layer_style::{ContourField, ContourKey, ContourRequest, contour_source};
|
||||
use craft_ui::contract::{Bind, Role};
|
||||
use craft_ui::patterns::presets::PresetState;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Rect, pos2};
|
||||
|
||||
@@ -18,8 +17,8 @@ fn rig() -> (Fixture, Rc<RefCell<Vec<ContourRequest>>>) {
|
||||
let mut contour = Contour::linear();
|
||||
let mut state = PresetState::<ContourKey>::new();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let words = Env::of(ui).words::<ContourWords>();
|
||||
let rows = contour_rows(&Contour::presets(), &[], &words, None);
|
||||
let presets = Contour::presets();
|
||||
let rows = contour_source(&presets, &[], None);
|
||||
let out = ContourField::new("Contour", Bind::bound(&mut contour), &rows, Bind::bound(&mut state)).show(ui);
|
||||
seen.borrow_mut().extend(out.edit_contour);
|
||||
});
|
||||
|
||||
@@ -10,9 +10,9 @@ use craft_imaging::layer_style::{
|
||||
EffectField, EffectId, EffectInstance, EffectKind, EffectSpec, FieldKind, FieldUnit, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams,
|
||||
StyleValue,
|
||||
};
|
||||
use craft_imaging::ui::layer_style::{LayerStyleDialog, StylePresets};
|
||||
use craft_imaging::ui::layer_style::LayerStyleDialog;
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::testing::access::{NodeKey, name};
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, Target, pointer, trial};
|
||||
@@ -26,7 +26,6 @@ struct Host {
|
||||
draft: LayerStyleDraft,
|
||||
specs: Vec<EffectSpec>,
|
||||
channels: Vec<String>,
|
||||
patterns: Vec<PresetRow<String>>,
|
||||
edits: Vec<EditEvent<LayerStyle>>,
|
||||
made: Vec<StyleParams>,
|
||||
}
|
||||
@@ -40,26 +39,24 @@ fn instance(id: u32, kind: EffectKind, on: bool) -> EffectInstance {
|
||||
}
|
||||
|
||||
fn host(draft: LayerStyleDraft, specs: Vec<EffectSpec>) -> Host {
|
||||
Host { draft, specs, channels: ["R", "G", "B"].map(String::from).to_vec(), patterns: Vec::new(), edits: Vec::new(), made: Vec::new() }
|
||||
Host { draft, specs, channels: ["R", "G", "B"].map(String::from).to_vec(), edits: Vec::new(), made: Vec::new() }
|
||||
}
|
||||
|
||||
fn rig_of(host: Host) -> (Fixture, Rc<RefCell<Host>>) {
|
||||
let host = Rc::new(RefCell::new(host));
|
||||
let shown = host.clone();
|
||||
let rows = vec![
|
||||
PresetRow::group("g".to_owned(), "Basics", 0),
|
||||
PresetRow::item("Soft".to_owned(), "Soft", 1),
|
||||
PresetRow::item("Hard".to_owned(), "Hard", 1),
|
||||
];
|
||||
let rows = |_: &(), _: &_| {
|
||||
vec![
|
||||
PresetRow::group("g".to_owned(), "Basics", 0),
|
||||
PresetRow::item("Soft".to_owned(), "Soft", 1),
|
||||
PresetRow::item("Hard".to_owned(), "Hard", 1),
|
||||
]
|
||||
};
|
||||
let presets = PresetSource::new((), PresetFns::new(rows).thumb(|_, cx, rect, _| cx.checker(rect)));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut guard = shown.borrow_mut();
|
||||
let host = &mut *guard;
|
||||
let presets = StylePresets::new(&rows, |cx, rect, _| cx.checker(rect));
|
||||
let out = LayerStyleDialog::new("Layer Style", &host.draft, &host.channels)
|
||||
.specs(&host.specs)
|
||||
.patterns(&host.patterns)
|
||||
.style_presets(presets)
|
||||
.show(ui);
|
||||
let out = LayerStyleDialog::new("Layer Style", &host.draft, &host.channels).specs(&host.specs).style_presets(&presets).show(ui);
|
||||
out.apply_view(&mut host.draft);
|
||||
for event in out.edit {
|
||||
if let Some(value) = event.value() {
|
||||
|
||||
@@ -15,6 +15,7 @@ use craft_imaging::ui::transform_preview::{
|
||||
use craft_imaging::ui::warp::WarpMesh;
|
||||
use craft_ui::canvas::{Canvas, PixelRect};
|
||||
use craft_ui::contract::{MemoProps, MemoView, PlainData, Show as _, ShowContainer as _, Tracked};
|
||||
use craft_ui::primitives::Serials;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Color32, ColorImage, Shape};
|
||||
|
||||
@@ -31,7 +32,7 @@ fn shown(map: fn() -> PreviewMap<'static>, opacity: f32, clip: Option<[u32; 2]>,
|
||||
let meshes = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen_view = Rc::new(Cell::new(None));
|
||||
let (sink, view_sink) = (Rc::clone(&meshes), Rc::clone(&seen_view));
|
||||
let textures = PreviewTextures::new("t", PreviewPixels::new(solid([2, 2], Color32::from_gray(u8::MAX)), [1.0, 1.0]));
|
||||
let textures = PreviewTextures::new(&mut Serials::default(), "t", PreviewPixels::new(solid([2, 2], Color32::from_gray(u8::MAX)), [1.0, 1.0]));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let view = CanvasView::new(room, pt(100.0, 100.0), 1.0).rotation(rotation);
|
||||
@@ -224,7 +225,7 @@ fn a_style_plan_stays_within_its_budget_at_screen_size_and_refuses_hostile_boxes
|
||||
fn a_monitor_conversion_changes_only_the_shown_upload() {
|
||||
let ctx = egui::Context::default();
|
||||
let raw = solid([2, 2], Color32::from_rgb(140, 89, 51));
|
||||
let textures = PreviewTextures::new("monitor", PreviewPixels::new(raw.clone(), [1.0, 1.0]));
|
||||
let textures = PreviewTextures::new(&mut Serials::default(), "monitor", PreviewPixels::new(raw.clone(), [1.0, 1.0]));
|
||||
// The trial stands in for the renderer: it takes the texture deltas it reads and applies none.
|
||||
let uploaded = |id: egui::TextureId| {
|
||||
let mut delta = ctx.tex_manager().write().take_delta();
|
||||
@@ -316,7 +317,7 @@ fn frame(textures: &PreviewTextures, quad: [Point; 4], zoom: f32) -> StyledFrame
|
||||
}
|
||||
|
||||
fn styled_textures() -> PreviewTextures {
|
||||
PreviewTextures::new("styled", PreviewPixels::new(solid([4, 4], Color32::from_rgb(200, 100, 50)), [1.0, 1.0]))
|
||||
PreviewTextures::new(&mut Serials::default(), "styled", PreviewPixels::new(solid([4, 4], Color32::from_rgb(200, 100, 50)), [1.0, 1.0]))
|
||||
}
|
||||
|
||||
fn context() -> (Fixture, egui::Context) {
|
||||
@@ -424,7 +425,7 @@ struct Mips {
|
||||
}
|
||||
|
||||
fn white(name: &str) -> Rc<PreviewTextures> {
|
||||
Rc::new(PreviewTextures::new(name, PreviewPixels::new(solid([5, 3], Color32::WHITE), [1.0, 1.0])))
|
||||
Rc::new(PreviewTextures::new(&mut Serials::default(), name, PreviewPixels::new(solid([5, 3], Color32::WHITE), [1.0, 1.0])))
|
||||
}
|
||||
|
||||
impl Mips {
|
||||
@@ -597,11 +598,12 @@ fn a_new_preview_under_the_same_name_shows_its_own_pixels() {
|
||||
delta.clear();
|
||||
texel
|
||||
};
|
||||
let first = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::WHITE), [1.0, 1.0]));
|
||||
let mut serials = Serials::default();
|
||||
let first = PreviewTextures::new(&mut serials, "same", PreviewPixels::new(solid([2, 2], Color32::WHITE), [1.0, 1.0]));
|
||||
let (id, _) = first.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded");
|
||||
assert_eq!(uploaded(id), Some(Color32::WHITE));
|
||||
drop(first);
|
||||
let second = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::BLACK), [1.0, 1.0]));
|
||||
let second = PreviewTextures::new(&mut serials, "same", PreviewPixels::new(solid([2, 2], Color32::BLACK), [1.0, 1.0]));
|
||||
let (id, _) = second.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded");
|
||||
assert_eq!(uploaded(id), Some(Color32::BLACK), "the new pixels go up");
|
||||
}
|
||||
|
||||
@@ -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,92 @@ 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> {
|
||||
pub(in crate::ui::panel) tree: Revision,
|
||||
pub(in crate::ui::panel) filter: &'a LayerFilter,
|
||||
#[memo_props(hash = "tree ids are plain model ids (LayerTree::Id: PlainData); Hash covers them")]
|
||||
pub(in crate::ui::panel) opened: &'a [Id],
|
||||
}
|
||||
|
||||
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 +121,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 +137,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,23 @@ 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, 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(Clone, PartialEq, Eq, Hash, Debug, PlainData)]
|
||||
/// struct LayerId(u64);
|
||||
///
|
||||
/// #[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 +36,15 @@ 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 is plain model data
|
||||
/// (`#[derive(PlainData)]`), so the panel keys it by its `Hash`, including in the memo key of the display order
|
||||
/// when a reveal opens groups. Its `Hash` must tell distinct ids apart (as `#[memo_props(hash)]` requires):
|
||||
/// two unequal ids that feed the same bytes would share a cached display order. Derived `Hash` on an integer or a
|
||||
/// tuple of integers does.
|
||||
type Id: Clone + Eq + Hash + Debug + Send + Sync + PlainData + 'static;
|
||||
|
||||
/// Children of `parent` (`None`: the top level), topmost first. The app leaves out what the
|
||||
/// panel never shows: layers outside an Isolate Layers set, a Type Mask session's working text.
|
||||
@@ -107,18 +117,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 +242,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 +252,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 +286,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 +305,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 +318,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 +380,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 +408,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 +448,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 +465,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".
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user