mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
Merge remote-tracking branch 'upstream/next' into frame-cost-15493
# Conflicts: # docs/contract-api.md
This commit is contained in:
Generated
+15
-14
@@ -4252,6 +4252,7 @@ name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-ui-macros",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5449,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -5505,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5540,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -5559,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5578,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"bytemuck",
|
||||
@@ -5598,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -5611,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5688,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -5761,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5787,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
@@ -15118,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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
|
||||
[[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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
|
||||
[[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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
|
||||
[[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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
|
||||
|
||||
+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 = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
|
||||
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
|
||||
|
||||
@@ -303,13 +303,18 @@ impl Codec for NumberCodec {
|
||||
|
||||
fn format(&self, v: &Option<f64>) -> String {
|
||||
let Some(number) = v else { return String::new() };
|
||||
let fixed = format!("{number:.*}", self.decimals);
|
||||
let written = format!("{number:.*}", self.decimals);
|
||||
// A value that rounds to zero at these decimals carries no sign.
|
||||
let fixed = match written.strip_prefix('-') {
|
||||
Some(digits) if digits.bytes().all(|byte| matches!(byte, b'0' | b'.')) => digits,
|
||||
_ => &written,
|
||||
};
|
||||
let trimmed = if self.fixed {
|
||||
&fixed
|
||||
fixed
|
||||
} else if fixed.contains('.') {
|
||||
fixed.trim_end_matches('0').trim_end_matches('.')
|
||||
} else {
|
||||
&fixed
|
||||
fixed
|
||||
};
|
||||
trimmed.replace('.', &self.reader.decimal_separator().to_string())
|
||||
}
|
||||
@@ -345,3 +350,17 @@ impl Codec for NumberCodec {
|
||||
Cow::Borrowed(NUMBER_SAMPLE)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_value_that_rounds_to_zero_is_written_without_a_sign() {
|
||||
let one = NumberCodec::new(Reader::new(), 1);
|
||||
assert_eq!(one.format(&Some(-0.0)), "0");
|
||||
assert_eq!(one.format(&Some(-0.04)), "0");
|
||||
assert_eq!(one.format(&Some(-0.06)), "-0.1");
|
||||
assert_eq!(NumberCodec::new(Reader::new(), 1).fixed().format(&Some(-0.04)), "0.0");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +93,11 @@ pub struct Location<P> {
|
||||
/// restoring creates a new group, column, dock or window for the panel.
|
||||
#[serde(default)]
|
||||
pub group: Option<GroupLocation>,
|
||||
/// The panels of its group that closed in the same batch of actions, itself included, in group order; empty
|
||||
/// when it closed alone. Reopening any of them brings back the others that are still hidden and were closed with
|
||||
/// it.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub closed_with: Vec<P>,
|
||||
}
|
||||
|
||||
/// Groups, columns and floating windows are named by a panel they contain.
|
||||
@@ -340,7 +345,7 @@ pub enum Action<P> {
|
||||
impl<P> Location<P> {
|
||||
/// A location relative to `anchor` by `placement`, with no recorded sizes or siblings.
|
||||
pub fn new(anchor: Option<P>, placement: DockPlacement<P>) -> Self {
|
||||
Self { floating: None, anchor, placement, size: None, stack: None, sibling: Vec::new(), group: None }
|
||||
Self { floating: None, anchor, placement, size: None, stack: None, sibling: Vec::new(), group: None, closed_with: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -554,7 +554,7 @@ pub(super) fn group_location<P: Clone + Eq>(panels: &[P], panel: &P) -> Option<L
|
||||
let index = panels.iter().position(|p| p == panel)?;
|
||||
let anchor = panels.iter().find(|p| *p != panel).cloned();
|
||||
let before = panels.get(index + 1).cloned();
|
||||
Some(Location { floating: None, anchor, placement: DockPlacement::Tab { before }, size: None, stack: None, sibling: Vec::new(), group: None })
|
||||
Some(Location::new(anchor, DockPlacement::Tab { before }))
|
||||
}
|
||||
|
||||
pub(super) fn first_panel<P>(node: &Node<P>) -> Option<&P> {
|
||||
|
||||
@@ -12,7 +12,7 @@ use super::{
|
||||
DockSide,
|
||||
action::{Action, DockPlacement, Location},
|
||||
edit::tree_panels,
|
||||
groups::{Column, DockEdge, PanelPlace, Target},
|
||||
groups::{Column, DockEdge, PanelPlace, Target, Unit},
|
||||
layout::Layout,
|
||||
limits::MAX_PANELS,
|
||||
node::Node,
|
||||
@@ -163,7 +163,7 @@ impl<P> Workspace<P> {
|
||||
|
||||
impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
/// Check the version, the layout, that every hidden panel is hidden once and absent
|
||||
/// from the layout, and that the floated records are bounded and one per panel.
|
||||
/// from the layout and its record is bounded, and that the floated records are bounded and one per panel.
|
||||
pub fn validate(&self) -> Result<(), DockError> {
|
||||
if self.version > Self::VERSION {
|
||||
return Err(DockError::UnsupportedVersion);
|
||||
@@ -174,10 +174,13 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
}
|
||||
let visible: HashSet<&P> = self.layout.panels().into_iter().collect();
|
||||
let mut seen = HashSet::new();
|
||||
for (panel, _) in &self.hidden {
|
||||
for (panel, location) in &self.hidden {
|
||||
if visible.contains(panel) || !seen.insert(panel) {
|
||||
return Err(DockError::DuplicatePanel);
|
||||
}
|
||||
if location.closed_with.len() > MAX_PANELS {
|
||||
return Err(DockError::LimitExceeded);
|
||||
}
|
||||
}
|
||||
if self.floated.len() > MAX_PANELS {
|
||||
return Err(DockError::LimitExceeded);
|
||||
@@ -211,8 +214,11 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
let policy = |panel: &P| if locked { permissions(panel).locked() } else { permissions(panel) };
|
||||
let mut proposed = self.clone();
|
||||
let mut all_closed = Vec::new();
|
||||
// The group of each panel as it closes, in closing order.
|
||||
let mut closing_groups = Vec::new();
|
||||
for action in actions {
|
||||
let closed = proposed.layout.closed_by(&action)?;
|
||||
closing_groups.extend(closed.iter().map(|panel| proposed.layout.members(panel, Unit::Group).unwrap_or_else(|_| vec![panel.clone()])));
|
||||
let locations = close_locations(&proposed.layout, &closed);
|
||||
let before = proposed.layout.clone();
|
||||
// Opening a hidden panel puts it back where it was.
|
||||
@@ -240,6 +246,7 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
proposed.hidden.retain(|(p, _)| !visible.contains(p));
|
||||
let mut seen = HashSet::new();
|
||||
all_closed.retain(|p| !visible.contains(p) && seen.insert(p.clone()));
|
||||
proposed.record_closed_together(&all_closed, &closing_groups);
|
||||
proposed.validate()?;
|
||||
let Workspace { layout, hidden, floated, .. } = proposed;
|
||||
(self.layout, self.hidden, self.floated) = (layout, hidden, floated);
|
||||
@@ -248,10 +255,11 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
}
|
||||
|
||||
/// Show or hide one panel. Showing restores its recorded location, following the chain of
|
||||
/// hidden anchors when its own anchor is hidden too; otherwise it opens as
|
||||
/// [`Action::Open`] with `fallback` as the anchor, following `permissions`. The hidden
|
||||
/// panels on that chain reopen beside it later, so a group or window closed one panel at a
|
||||
/// time comes back as one.
|
||||
/// hidden anchors when its own anchor is hidden too, and brings back the hidden panels of its
|
||||
/// group that closed with it in one batch (Close Tab Group, a preset) as tabs of its group;
|
||||
/// otherwise it opens as [`Action::Open`] with `fallback` as the anchor, following
|
||||
/// `permissions`. The other hidden panels on that chain reopen beside it later, so a group or
|
||||
/// window closed one panel at a time comes back as one.
|
||||
/// A shown panel becomes the active tab of its group. Hiding follows `permissions` and
|
||||
/// `locked`, as [`Self::apply`] does, so a protected canvas stays shown.
|
||||
pub fn set_visible(
|
||||
@@ -276,29 +284,91 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
self.apply_all([open, Action::Activate { panel }], locked, permissions).map(drop)
|
||||
}
|
||||
|
||||
/// Restore a hidden `panel` to its recorded place and make it the active tab. `Ok(false)` when the record
|
||||
/// cannot be restored, or the place it restores to refuses the panel under `permissions`; the workspace stays
|
||||
/// as it was and the caller opens the panel by the ordinary, checked path.
|
||||
/// Restore a hidden `panel` to its recorded place, with the hidden panels closed with it, and make it the
|
||||
/// active tab. The set is restored in group order, each panel by its own record, so the group comes back in
|
||||
/// the order it had; a panel closed with it whose place refuses it stays hidden. `Ok(false)` when `panel`'s
|
||||
/// record cannot be restored, or the place it restores to refuses the panel under `permissions`; the workspace
|
||||
/// stays as it was and the caller opens the panel by the ordinary, checked path.
|
||||
fn reopen(&mut self, panel: &P, permissions: &impl Fn(&P) -> Permissions) -> Result<bool, DockError> {
|
||||
// The restore also rewrites the records of the hidden panels it passed, so it runs on a copy.
|
||||
let mut restored = self.clone();
|
||||
for member in self.closed_together(panel) {
|
||||
match restored.restored(&member, permissions) {
|
||||
Some(next) => restored = next,
|
||||
None if &member == panel => return Ok(false),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
restored.layout.apply(Action::Activate { panel: panel.clone() })?;
|
||||
self.layout = restored.layout;
|
||||
self.hidden = restored.hidden;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The workspace with the hidden `panel` restored to its recorded place, `None` when the record cannot be
|
||||
/// restored or the place refuses the panel under `permissions`. The restore also rewrites the records of the
|
||||
/// hidden panels it passed, so it runs on a copy.
|
||||
fn restored(&self, panel: &P, permissions: &impl Fn(&P) -> Permissions) -> Option<Self> {
|
||||
let mut trial = self.clone();
|
||||
let mut layout = self.layout.clone();
|
||||
if trial.restore_from_hidden(&mut layout, panel).is_err() {
|
||||
return Ok(false);
|
||||
}
|
||||
trial.restore_from_hidden(&mut layout, panel).ok()?;
|
||||
let allowed = layout
|
||||
.location(panel)
|
||||
.ok()
|
||||
.and_then(|location| location.anchor.map(|anchor| location.placement.allowed_by(permissions(&anchor))))
|
||||
.unwrap_or(true);
|
||||
if !allowed || layout.breaks_columns_beyond(&self.layout, permissions) {
|
||||
return Ok(false);
|
||||
return None;
|
||||
}
|
||||
trial.layout = layout;
|
||||
trial.hidden.retain(|(p, _)| p != panel);
|
||||
Some(trial)
|
||||
}
|
||||
|
||||
/// The hidden `panel` and the hidden panels closed with it, in group order: those its record's
|
||||
/// [`closed_with`](Location::closed_with) names whose own records name it back. A panel that closed again on
|
||||
/// its own since names it no more. `[panel]` when it closed alone.
|
||||
fn closed_together(&self, panel: &P) -> Vec<P> {
|
||||
let record = |p: &P| self.hidden.iter().find(|(q, _)| q == p).map(|(_, location)| location);
|
||||
let mut seen = HashSet::new();
|
||||
let together: Vec<P> = record(panel)
|
||||
.map(|location| &location.closed_with[..])
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter(|&p| p == panel || record(p).is_some_and(|location| location.closed_with.contains(panel)))
|
||||
.filter(|&p| seen.insert(p))
|
||||
.cloned()
|
||||
.collect();
|
||||
if together.len() > 1 && together.contains(panel) { together } else { vec![panel.clone()] }
|
||||
}
|
||||
|
||||
/// Records on the hidden panels `closed`, which this batch closed, the panels of their group that closed with
|
||||
/// them. `groups` holds each closing panel's group as it closed, in closing order. The closed panels of one
|
||||
/// group, or of groups that share one, form one set in the order the groups name them.
|
||||
fn record_closed_together(&mut self, closed: &[P], groups: &[Vec<P>]) {
|
||||
let closed: HashSet<&P> = closed.iter().collect();
|
||||
let mut sets: Vec<Vec<P>> = Vec::new();
|
||||
for group in groups {
|
||||
let members: Vec<&P> = group.iter().filter(|p| closed.contains(p)).collect();
|
||||
let (joined, rest): (Vec<Vec<P>>, Vec<Vec<P>>) =
|
||||
std::mem::take(&mut sets).into_iter().partition(|set| set.iter().any(|p| members.contains(&p)));
|
||||
let mut set: Vec<P> = joined.into_iter().flatten().collect();
|
||||
for panel in members {
|
||||
if !set.contains(panel) {
|
||||
set.push(panel.clone());
|
||||
}
|
||||
}
|
||||
sets = rest;
|
||||
if !set.is_empty() {
|
||||
sets.push(set);
|
||||
}
|
||||
}
|
||||
for set in sets.into_iter().filter(|set| set.len() > 1) {
|
||||
for (panel, location) in &mut self.hidden {
|
||||
if set.contains(panel) {
|
||||
location.closed_with.clone_from(&set);
|
||||
}
|
||||
}
|
||||
}
|
||||
layout.apply(Action::Activate { panel: panel.clone() })?;
|
||||
self.layout = layout;
|
||||
self.hidden = trial.hidden;
|
||||
self.hidden.retain(|(p, _)| p != panel);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Update the floated records after an action that turned `before` into the current layout: drop the records of
|
||||
|
||||
@@ -97,6 +97,10 @@ pub struct PlaceRequest {
|
||||
/// Beside the anchor, the overlay lines up with the anchor's other end when it runs past the bounds from the
|
||||
/// aligned end and fits from the other, instead of sliding: a submenu of a low row opens upward.
|
||||
pub flips_across: bool,
|
||||
/// Below or above the anchor, an overlay that fits on neither side but fits the bounds keeps its height and slides
|
||||
/// over the anchor from the preferred side; only one taller than the bounds is capped. For a context menu, whose
|
||||
/// anchor is a point or a row.
|
||||
pub covers_anchor: bool,
|
||||
}
|
||||
|
||||
impl PlaceRequest {
|
||||
@@ -113,6 +117,7 @@ impl PlaceRequest {
|
||||
bounds,
|
||||
kept: None,
|
||||
flips_across: false,
|
||||
covers_anchor: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,6 +168,12 @@ impl PlaceRequest {
|
||||
self.flips_across = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Below or above the anchor, slides over the anchor when the overlay fits neither side but fits the bounds.
|
||||
pub const fn covers_anchor(mut self, on: bool) -> Self {
|
||||
self.covers_anchor = on;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `place` put the overlay.
|
||||
@@ -200,9 +211,10 @@ fn room(anchor: Rect, bounds: Rect, side: Side, rtl: bool, gap: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to
|
||||
/// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Beside the anchor, a request that
|
||||
/// flips across lines up with the anchor's other end when it runs past the bounds from the aligned end and fits from the
|
||||
/// other. The rect is always finite and inside the bounds.
|
||||
/// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Below or above the anchor, a
|
||||
/// request that covers its anchor and fits neither side keeps the preferred side and its height up to the bounds' and
|
||||
/// slides over the anchor. Beside the anchor, a request that flips across lines up with the anchor's other end when it
|
||||
/// runs past the bounds from the aligned end and fits from the other. The rect is always finite and inside the bounds.
|
||||
pub fn place(request: &PlaceRequest) -> Placement {
|
||||
let anchor = clean(request.anchor);
|
||||
let bounds = clean(request.bounds);
|
||||
@@ -213,12 +225,15 @@ pub fn place(request: &PlaceRequest) -> Placement {
|
||||
let need = if request.side.vertical() { wanted.y } else { wanted.x };
|
||||
let preferred = room(anchor, bounds, request.side, rtl, gap);
|
||||
let other = room(anchor, bounds, request.side.flipped(), rtl, gap);
|
||||
let covers = request.covers_anchor && request.side.vertical();
|
||||
let side = match request.kept {
|
||||
Some(kept) => kept,
|
||||
None if preferred >= need || preferred >= other => request.side,
|
||||
None if covers && other < need => request.side,
|
||||
None => request.side.flipped(),
|
||||
};
|
||||
let available = room(anchor, bounds, side, rtl, gap).max(0.0);
|
||||
// Covering the anchor, the overlay may take the bounds' height: the shift inside them moves it over the anchor.
|
||||
let available = if covers { bounds.height() } else { room(anchor, bounds, side, rtl, gap).max(0.0) };
|
||||
let size = if side.vertical() {
|
||||
Vec2::new(wanted.x.min(bounds.width()), wanted.y.min(available).min(bounds.height()))
|
||||
} else {
|
||||
@@ -275,6 +290,20 @@ mod tests {
|
||||
assert_eq!(neither.bottom(), BOUNDS.bottom(), "fits neither way: slides up to stay inside");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_menu_that_covers_its_anchor_and_fits_neither_side_keeps_its_height_and_slides_over_the_anchor() {
|
||||
let point = rect(300.0, 400.0, 0.0, 0.0);
|
||||
let request = PlaceRequest::new(point, Vec2::new(200.0, 450.0), BOUNDS).covers_anchor(true);
|
||||
let placed = place(&request).rect;
|
||||
assert_eq!(placed.height(), 450.0, "fits the bounds: its whole height");
|
||||
assert!(BOUNDS.contains_rect(placed) && placed.top() < point.top(), "slides up over the point: {placed:?}");
|
||||
assert_eq!(place(&request.size(Vec2::new(200.0, 700.0))).rect.height(), BOUNDS.height(), "taller than the bounds: capped");
|
||||
let above = place(&request.size(Vec2::new(200.0, 350.0)));
|
||||
assert!(above.side == Side::Above && above.rect.bottom() == point.top(), "fits above: opens above the point: {above:?}");
|
||||
let without = place(&request.covers_anchor(false));
|
||||
assert!(without.side == Side::Above && without.rect.height() < 450.0, "without it: capped to the larger side: {without:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overlay_at_least_as_wide_as_its_anchor_takes_that_width_below_it_but_not_beside_it() {
|
||||
let field = rect(100.0, 100.0, 300.0, 24.0);
|
||||
@@ -298,7 +327,8 @@ mod tests {
|
||||
.side(side)
|
||||
.align(align)
|
||||
.rtl(i % 2 == 0)
|
||||
.gap(if i == 1 { 4.0 } else { 0.0 });
|
||||
.gap(if i == 1 { 4.0 } else { 0.0 })
|
||||
.covers_anchor(align != Align::Start);
|
||||
let placed = place(&request).rect;
|
||||
assert!(placed.min.is_finite() && placed.max.is_finite(), "{request:?}");
|
||||
assert!(BOUNDS.contains_rect(placed), "{request:?} gave {placed:?}");
|
||||
|
||||
@@ -188,6 +188,42 @@ fn opening_a_closed_floating_panel_restores_its_window_place() {
|
||||
assert_eq!(group_members(workspace.layout(), 11), [11, 12, 50]);
|
||||
}
|
||||
|
||||
/// The active tab of the dock or floating group holding `panel`.
|
||||
fn front(layout: &Layout<u32>, panel: u32) -> u32 {
|
||||
*layout.group(&layout.place(&panel).unwrap()).unwrap().active_panel().unwrap()
|
||||
}
|
||||
|
||||
/// Tabs closed in one batch (one at a time, as a preset does, or by Close Tab Group) come back together with whichever
|
||||
/// of them reopens, in their order and with that one in front, after a save and a load; a tab closed in a batch of its
|
||||
/// own stays closed.
|
||||
#[test]
|
||||
fn tabs_closed_together_reopen_together_and_a_tab_closed_alone_stays_closed() {
|
||||
let batches = [vec![Action::close(2), Action::close(3)], vec![Action::close(3), Action::close(2)], vec![Action::close_group(2)]];
|
||||
for batch in batches {
|
||||
for open in [2, 3] {
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply_all(batch.clone(), false, allow).unwrap();
|
||||
let saved = serde_json::to_string(&workspace).unwrap();
|
||||
let mut workspace: Workspace<u32> = serde_json::from_str(&saved).unwrap();
|
||||
workspace.apply(Action::open(open, None), false, allow).unwrap();
|
||||
let layout = workspace.layout();
|
||||
assert_eq!(group_members(layout, open), [2, 3], "{batch:?}, then {open} opens");
|
||||
assert_eq!(front(layout, open), open, "{batch:?}: the reopened tab is in front");
|
||||
assert_eq!(end_dock(layout)[0].groups[0].panels, [2, 3], "{batch:?}: back above 4 in its column");
|
||||
assert!(workspace.hidden().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply(Action::close(3), false, allow).unwrap();
|
||||
workspace.apply(Action::close(2), false, allow).unwrap();
|
||||
workspace.apply(Action::open(2, None), false, allow).unwrap();
|
||||
assert_eq!(group_members(workspace.layout(), 2), [2]);
|
||||
assert!(workspace.layout().place(&3).is_none(), "3 closed on its own stays closed");
|
||||
workspace.apply(Action::open(3, None), false, allow).unwrap();
|
||||
assert_eq!(group_members(workspace.layout(), 2), [2, 3], "it reopens beside 2");
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
|
||||
@@ -32,7 +32,7 @@ where
|
||||
let (entries, _) = entries_of(model, state, collator);
|
||||
let searching = !state.search.trim().is_empty();
|
||||
let shown = Cards::new(model, entries);
|
||||
let mods = craft_ui::runtime::pointer::frame(ui.ctx()).mods;
|
||||
let mods = craft_ui::runtime::pointer::mods(ui.ctx());
|
||||
if let Some(key) = rename {
|
||||
request_rename(ui.ctx(), id, &key);
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ where
|
||||
let (entries, user_order) = entries_of(model, state, collator);
|
||||
let searching = !state.search.trim().is_empty();
|
||||
let cards = Cards::new(model, entries);
|
||||
let mods = craft_ui::runtime::pointer::frame(ui.ctx()).mods;
|
||||
let mods = craft_ui::runtime::pointer::mods(ui.ctx());
|
||||
if let Some(key) = rename {
|
||||
request_rename(ui.ctx(), id, &key);
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ where
|
||||
let thumb = state.settings.thumbnails;
|
||||
let specs = columns_of(columns, &state.settings.widths, words.name.clone());
|
||||
let value_columns: Vec<ColumnKey> = specs.iter().map(|spec| spec.key.clone()).filter(|key| *key != NAME).collect();
|
||||
let mods = craft_ui::runtime::pointer::frame(ui.ctx()).mods;
|
||||
let mods = craft_ui::runtime::pointer::mods(ui.ctx());
|
||||
let tile_words = Env::of(ui).words::<TileWords>();
|
||||
if let Some(key) = rename {
|
||||
request_rename(ui.ctx(), id, &key);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -226,7 +226,8 @@ impl Component for ColorDisc<'_> {
|
||||
|
||||
/// A band across the width it is given, as tall as the square that fits it: the picture is centred in it.
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(cx.picture_width(cx.style.least, f32::INFINITY), cx.picture_width(cx.style.least, cx.style.most))
|
||||
let most = cx.style.most.max(cx.style.least);
|
||||
cx.picture_size(cx.style.least, f32::INFINITY, |width| width.min(most))
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
|
||||
@@ -4,8 +4,10 @@ use craft_behavior::ColumnWidth;
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::contract::{Outcome as _, Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::contract::{Gap, Outcome as _, Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::{Divider, Text};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout::{CellAlign, GridFit};
|
||||
use craft_ui::layout_components::{Grid, Stack};
|
||||
use craft_ui::notices::{Notice, NoticeLayout};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
@@ -19,9 +21,8 @@ pub(crate) mod stories;
|
||||
/// What a missing value shows.
|
||||
const DASH: &str = "–";
|
||||
|
||||
/// The grid's columns: a name and its value, twice, so that the two readouts of a line stand side by side and each
|
||||
/// column lines up down the grid.
|
||||
const COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content];
|
||||
/// A block's two halves, equal in width.
|
||||
const HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)];
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of the Info panel, in the installed language unless set.
|
||||
@@ -179,9 +180,10 @@ impl<'a> InfoReadings<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A read-only grid: RGB beside CMYK, the Ruler tool's measure (the angle A beside the length L, or a protractor's arms
|
||||
/// L1 and L2 stacked beside it), X/Y beside W/H, the document size, then one row group per sampler; a dash for a
|
||||
/// missing value; `document: None` shows "No document" as a centred notice in place of the grid.
|
||||
/// A read-only panel of blocks, a rule between them, each block two equal halves of labelled readouts: RGB beside CMYK
|
||||
/// (in percent), the Ruler tool's measure (the angle A beside the length L, or a protractor's arms L1 and L2 stacked
|
||||
/// beside it), X/Y beside W/H, the document size, then a position block and a colour block per sampler; a dash for a
|
||||
/// missing value; `document: None` shows "No document" as a centred notice in place of the blocks.
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct InfoPanel<'a> {
|
||||
@@ -192,43 +194,38 @@ pub struct InfoPanel<'a> {
|
||||
/// A name and its value, or `None` for a dash.
|
||||
type Cell = (Label, Option<Label>);
|
||||
|
||||
/// One block: the readouts of its left and right halves.
|
||||
type Block = [Vec<Cell>; 2];
|
||||
|
||||
/// The value of a number, or `None` when it is missing.
|
||||
fn number(value: Option<impl ToString>) -> Option<Label> {
|
||||
value.map(|value| Label::from(value.to_string()))
|
||||
}
|
||||
|
||||
/// A name and its value in two grid cells, or two empty cells.
|
||||
fn pair(ui: &mut Ui, cell: Option<Cell>) {
|
||||
match cell {
|
||||
Some((name, value)) => {
|
||||
Text::new(name).show(ui);
|
||||
Text::new(value.unwrap_or_else(|| Label::from(DASH))).show(ui);
|
||||
}
|
||||
None => {
|
||||
Text::new(Label::from("")).show(ui);
|
||||
Text::new(Label::from("")).show(ui);
|
||||
}
|
||||
}
|
||||
/// The value of a CMYK percent, or `None` when it is missing.
|
||||
fn percent(value: Option<u8>) -> Option<Label> {
|
||||
value.map(|value| Label::from(format!("{value}%")))
|
||||
}
|
||||
|
||||
/// A grid of lines, each two name and value pairs.
|
||||
fn table(ui: &mut Ui, lines: Vec<[Option<Cell>; 2]>) {
|
||||
let _ = Grid::new(&COLUMNS).show(ui, |ui, _| {
|
||||
for [left, right] in lines.iter().cloned() {
|
||||
pair(ui, left);
|
||||
pair(ui, right);
|
||||
/// A half of a block: its readouts as the fields of one form group, so the names carry their colons and share a
|
||||
/// column and the values line up.
|
||||
fn half(ui: &mut Ui, cells: &[Cell]) {
|
||||
let _ = FieldGroup::new(Label::from("")).gap(Gap::Tight).show(ui, |ui, _| {
|
||||
for (name, value) in cells {
|
||||
let value = value.clone().unwrap_or_else(|| Label::from(DASH));
|
||||
let _ = Field::new(name.clone()).value(value.as_str()).show(ui, |ui, _| {
|
||||
Text::new(value.clone()).show(ui);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// `cells` two to a line.
|
||||
fn in_pairs(cells: Vec<Cell>) -> Vec<[Option<Cell>; 2]> {
|
||||
let mut cells = cells.into_iter();
|
||||
let mut lines = Vec::new();
|
||||
while let Some(left) = cells.next() {
|
||||
lines.push([Some(left), cells.next()]);
|
||||
}
|
||||
lines
|
||||
/// A block: two equal halves, which stay beside each other in a narrow panel.
|
||||
fn block(ui: &mut Ui, [left, right]: &Block) {
|
||||
let _ = Grid::new(&HALVES).fit(GridFit::Fixed).cells(CellAlign::Top).show(ui, |ui, _| {
|
||||
half(ui, left);
|
||||
half(ui, right);
|
||||
});
|
||||
}
|
||||
|
||||
impl<'a> InfoPanel<'a> {
|
||||
@@ -250,38 +247,47 @@ impl<'a> InfoPanel<'a> {
|
||||
Stack::new()
|
||||
.label(label)
|
||||
.show(ui, |ui, _| {
|
||||
let mut lines = Vec::new();
|
||||
for (at, cmyk_name) in cmyk_names.iter().enumerate() {
|
||||
let rgb = rgb_names.get(at).map(|rgb_name| (rgb_name.clone(), number(readings.color.map(|color| color.rgb[at]))));
|
||||
lines.push([rgb, Some((cmyk_name.clone(), number(readings.color.map(|color| color.cmyk[at]))))]);
|
||||
}
|
||||
let color = readings.color;
|
||||
let rgb = rgb_names.iter().enumerate().map(|(at, name)| (name.clone(), number(color.map(|color| color.rgb[at])))).collect();
|
||||
let cmyk = cmyk_names.iter().enumerate().map(|(at, name)| (name.clone(), percent(color.map(|color| color.cmyk[at])))).collect();
|
||||
let mut blocks = vec![[rgb, cmyk]];
|
||||
match &readings.measure {
|
||||
Some(InfoMeasure::Line { angle, length }) => {
|
||||
lines.push([Some((name(&words.angle), Some(angle.clone()))), Some((name(&words.length), Some(length.clone())))]);
|
||||
blocks.push([vec![(name(&words.angle), Some(angle.clone()))], vec![(name(&words.length), Some(length.clone()))]]);
|
||||
}
|
||||
Some(InfoMeasure::Protractor { angle, first, second }) => {
|
||||
lines.push([Some((name(&words.angle), Some(angle.clone()))), Some((name(&words.length1), Some(first.clone())))]);
|
||||
lines.push([None, Some((name(&words.length2), Some(second.clone())))]);
|
||||
blocks.push([
|
||||
vec![(name(&words.angle), Some(angle.clone()))],
|
||||
vec![(name(&words.length1), Some(first.clone())), (name(&words.length2), Some(second.clone()))],
|
||||
]);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let (position, extent) = (readings.position.as_ref(), readings.extent.as_ref());
|
||||
let axes = [(name(&words.x), name(&words.w)), (name(&words.pos_y), name(&words.h))];
|
||||
let (mut at, mut size) = (Vec::new(), Vec::new());
|
||||
for (axis, (position_name, extent_name)) in axes.into_iter().enumerate() {
|
||||
lines.push([
|
||||
Some((position_name, position.map(|at| at[axis].clone()))),
|
||||
Some((extent_name, extent.map(|size| size[axis].clone()))),
|
||||
]);
|
||||
at.push((position_name, position.map(|at| at[axis].clone())));
|
||||
size.push((extent_name, extent.map(|size| size[axis].clone())));
|
||||
}
|
||||
blocks.push([at, size]);
|
||||
for (at, readings) in blocks.iter().enumerate() {
|
||||
if at > 0 {
|
||||
Divider::horizontal().show(ui);
|
||||
}
|
||||
block(ui, readings);
|
||||
}
|
||||
table(ui, lines);
|
||||
let size = words.document.fill(&[("width", &width.to_string()), ("height", &height.to_string())]);
|
||||
Divider::horizontal().show(ui);
|
||||
Text::new(Label::from(size)).show(ui);
|
||||
for (readout, position) in readings.samplers {
|
||||
Divider::horizontal().show(ui);
|
||||
Text::new(Label::from(format!("#{}", readout.number))).show(ui);
|
||||
let mut lines = vec![[Some((name(&words.x), Some(position[0].clone()))), Some((name(&words.pos_y), Some(position[1].clone())))]];
|
||||
lines.extend(in_pairs(rgb_names.iter().zip(readout.rgb).map(|(name, value)| (name.clone(), number(Some(value)))).collect()));
|
||||
lines.extend(in_pairs(cmyk_names.iter().zip(readout.cmyk).map(|(name, value)| (name.clone(), number(Some(value)))).collect()));
|
||||
table(ui, lines);
|
||||
let place = [vec![(name(&words.x), Some(position[0].clone()))], vec![(name(&words.pos_y), Some(position[1].clone()))]];
|
||||
let rgb = rgb_names.iter().zip(readout.rgb).map(|(name, value)| (name.clone(), number(Some(value)))).collect();
|
||||
let cmyk = cmyk_names.iter().zip(readout.cmyk).map(|(name, value)| (name.clone(), percent(Some(value)))).collect();
|
||||
block(ui, &place);
|
||||
block(ui, &[rgb, cmyk]);
|
||||
}
|
||||
})
|
||||
.output
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -307,7 +307,8 @@ impl Component for ColorWheel<'_> {
|
||||
|
||||
/// A band across the width it is given, as tall as the square that fits it: the picture is centred in it.
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(cx.picture_width(cx.style.least, f32::INFINITY), cx.picture_width(cx.style.least, cx.style.most))
|
||||
let most = cx.style.most.max(cx.style.least);
|
||||
cx.picture_size(cx.style.least, f32::INFINITY, |width| width.min(most))
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
|
||||
@@ -421,6 +421,30 @@ fn measure_names(measure: Option<craft_color_ui::ui::InfoMeasure>) -> [bool; 4]
|
||||
["A", "L", "L1", "L2"].map(|name| fixture.by_label(name).is_some())
|
||||
}
|
||||
|
||||
/// The painted run whose text is `text`, without a colon.
|
||||
fn run(fixture: &Fixture, text: &str) -> egui::Rect {
|
||||
fixture.texts().iter().find(|run| run.text.trim_end_matches(':') == text).unwrap_or_else(|| panic!("no run \"{text}\"")).rect
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_info_panel_shows_rgb_and_cmyk_as_two_aligned_columns() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let color = craft_color_ui::ui::InfoColor::from_parts([10, 200, 30], [1, 22, 33, 44]);
|
||||
let readings = craft_color_ui::ui::InfoReadings::new().color(Some(color)).document(Some([640, 480]));
|
||||
let _ = craft_color_ui::ui::InfoPanel::new("Info", &readings).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
let [r, g, b] = ["10", "200", "30"].map(|value| run(&fixture, value));
|
||||
let [c, m, y, k] = ["1%", "22%", "33%", "44%"].map(|value| run(&fixture, value));
|
||||
assert!(c.left() > r.right().max(g.right()).max(b.right()), "CMYK starts right of RGB: {r:?} {c:?}");
|
||||
assert!(r.left() == g.left() && g.left() == b.left(), "the RGB values share a column");
|
||||
assert!(c.left() == m.left() && m.left() == y.left() && y.left() == k.left(), "the CMYK values share a column");
|
||||
let [rn, gn, bn] = ["R", "G", "B"].map(|name| run(&fixture, name));
|
||||
assert!(rn.right() == gn.right() && gn.right() == bn.right(), "the RGB labels end at one x");
|
||||
assert!(rn.right() < r.left(), "the labels sit left of their values");
|
||||
assert!(fixture.texts().iter().any(|run| run.text == ":"), "a label carries its colon");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_info_panel_shows_the_rulers_measure_while_it_has_one() {
|
||||
use craft_color_ui::ui::InfoMeasure;
|
||||
|
||||
@@ -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 = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1";
|
||||
|
||||
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
|
||||
pub const PACKAGES: &[&str] = &[
|
||||
|
||||
@@ -161,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"),
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -260,7 +260,7 @@ impl CropTool {
|
||||
// Straighten surface is there for a press on the pass after the key came down; a line in progress keeps the
|
||||
// state it started with, so letting go of the key mid-line does not turn it into a frame drag.
|
||||
if !self.dragging {
|
||||
self.session.straighten_mut().set_held(pointer::frame(ui.ctx()).mods.cmd);
|
||||
self.session.straighten_mut().set_held(pointer::mods(ui.ctx()).cmd);
|
||||
}
|
||||
let (ratio, default, straighten, dismissed) =
|
||||
(settings.ratio_value(document, &units), self.session.is_default(), self.session.straighten().on(), self.session.dismissed());
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::ops::RangeInclusive;
|
||||
|
||||
use craft_behavior::{Metrics, Mixed, Proposal, Sense, decimals_for_step};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Outcome, PaintUi, Props as _, Role, WordSetCx as _,
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Outcome, PaintUi, Props as _, Role, Sizing, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::runtime::env::Label;
|
||||
@@ -165,10 +165,6 @@ pub struct LevelsEditorStyle {
|
||||
bar_row: f32,
|
||||
/// The height of a row of fields.
|
||||
fields: f32,
|
||||
/// The width of a levels field: three digits.
|
||||
field: f32,
|
||||
/// The width of the gamma field: a value like 9.99.
|
||||
gamma_field: f32,
|
||||
/// The width the editor asks for when the parent offers none.
|
||||
width: f32,
|
||||
/// The light end of the output bar: the channel's bar colour.
|
||||
@@ -256,6 +252,8 @@ pub struct LevelsEditor<'a> {
|
||||
#[prop]
|
||||
captions: bool,
|
||||
clip: Option<LevelsClip>,
|
||||
/// The width of a levels field and of the gamma field, as the fields measure themselves (`measure`).
|
||||
field_widths: [f32; 2],
|
||||
}
|
||||
|
||||
impl<'a> LevelsEditor<'a> {
|
||||
@@ -274,6 +272,7 @@ impl<'a> LevelsEditor<'a> {
|
||||
stale: false,
|
||||
captions: true,
|
||||
clip: None,
|
||||
field_widths: [0.0; 2],
|
||||
}
|
||||
.label(label)
|
||||
}
|
||||
@@ -327,6 +326,17 @@ impl<'a> LevelsEditor<'a> {
|
||||
if self.stale { plot.stale(StaleMark::Mark(Label::Empty)) } else { plot }
|
||||
}
|
||||
|
||||
/// The three input fields (black, gamma, white) showing `base`, with the thumbs at `placed`.
|
||||
fn input_fields<'c>(&self, words: &LevelsWords, base: &Levels, placed: [f64; 3]) -> [NumberField<'c>; 3] {
|
||||
let labels = [words.in_black.clone(), words.gamma.clone(), words.in_white.clone()];
|
||||
let values = [base.in_black, base.gamma, base.in_white];
|
||||
std::array::from_fn(|i| {
|
||||
let step = if i == 1 { GAMMA_STEP } else { self.step };
|
||||
let field = self.field(labels[i].clone(), values[i], input_range(self, i, placed), step);
|
||||
if i == 1 { field.fixed_decimals(decimals_for_step(GAMMA_STEP)) } else { field }
|
||||
})
|
||||
}
|
||||
|
||||
/// A field named `label` showing `value`, within `range`.
|
||||
fn field<'c>(&self, label: Label, value: f64, range: RangeInclusive<f64>, step: f64) -> NumberField<'c> {
|
||||
let shown = Some(value).filter(|value| value.is_finite());
|
||||
@@ -431,8 +441,6 @@ impl Component for LevelsEditor<'_> {
|
||||
row: control.icon,
|
||||
bar_row: control.icon + cx.tokens.size.ramp.bar,
|
||||
fields: row,
|
||||
field: cx.text_width(TypeRole::Body, "000") + 2.0 * control.pad_x,
|
||||
gamma_field: cx.text_width(TypeRole::Body, "0.00") + 2.0 * control.pad_x,
|
||||
width: cx.tokens.size.plot.width,
|
||||
bar: key.channel.bar(cx),
|
||||
}
|
||||
@@ -448,6 +456,13 @@ impl Component for LevelsEditor<'_> {
|
||||
let empty = HistogramData::tone(&[0u32; 256], self.channel);
|
||||
let mut plot = self.plot(&words, self.histogram.unwrap_or(&empty));
|
||||
let plot = cx.child("plot", &mut plot, Proposal::Width(width)).y;
|
||||
let base = cx.value().copied().unwrap_or_else(|| Levels::identity(self.range.clone()));
|
||||
let placed = self.input_row(&words, cx.value().copied()).rules().placed(&base.input());
|
||||
let mut widths = [0.0f32; 3];
|
||||
for (i, field) in self.input_fields(&words, &base, placed).into_iter().enumerate() {
|
||||
widths[i] = cx.child(("in-field", i), &mut field.sizing(Sizing::Content), Proposal::Ideal).x;
|
||||
}
|
||||
self.field_widths = [widths[0].max(widths[2]), widths[1]];
|
||||
Vec2::new(width, fixed_height(self.captions, cx.style) + plot)
|
||||
}
|
||||
|
||||
@@ -484,20 +499,16 @@ impl Component for LevelsEditor<'_> {
|
||||
let empty = HistogramData::tone(&[0u32; 256], self.channel);
|
||||
let plot = Rect::from_x_y_ranges(input.travel, at(rows.plot).y_range());
|
||||
ui.child("plot", plot, self.plot(&words, self.histogram.unwrap_or(&empty)));
|
||||
let fields = field_rects(rows.fields_in, cx.style.field, cx.style.gamma_field, 3);
|
||||
let labels = [words.in_black.clone(), words.gamma.clone(), words.in_white.clone()];
|
||||
let values = [base.in_black, base.gamma, base.in_white];
|
||||
let typed: Vec<_> = (0..3)
|
||||
.map(|i| {
|
||||
let step = if i == 1 { GAMMA_STEP } else { self.step };
|
||||
let field = self.field(labels[i].clone(), values[i], input_range(self, i, placed), step);
|
||||
let field = if i == 1 { field.fixed_decimals(decimals_for_step(GAMMA_STEP)) } else { field };
|
||||
ui.child(("in-field", i), at(fields[i]), field)
|
||||
})
|
||||
let fields = field_rects(rows.fields_in, self.field_widths[0], self.field_widths[1], 3);
|
||||
let typed: Vec<_> = self
|
||||
.input_fields(&words, &base, placed)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| ui.child(("in-field", i), at(fields[i]), field))
|
||||
.collect();
|
||||
|
||||
let output = ui.child("output", at(rows.output), self.output_row(&words, shown, &bar));
|
||||
let fields = field_rects(rows.fields_out, cx.style.field, 0.0, 2);
|
||||
let fields = field_rects(rows.fields_out, self.field_widths[0], 0.0, 2);
|
||||
let (low, high) = self.ends();
|
||||
let out_labels = [words.out_black.clone(), words.out_white.clone()];
|
||||
let out_values = [base.out_black, base.out_white];
|
||||
|
||||
@@ -154,7 +154,7 @@ impl<'a, K: Clone + Eq + Hash + Debug + Send + Sync + 'static> ChannelsPanel<'a,
|
||||
events.borrow_mut().extend(out);
|
||||
})
|
||||
.show(ui, |ui, stack| {
|
||||
let mods = craft_ui::runtime::pointer::frame(&ctx).mods;
|
||||
let mods = craft_ui::runtime::pointer::mods(&ctx);
|
||||
while let Some((command, _)) = stack.take_command::<ChannelsCommands>() {
|
||||
match (command, targeted_row(rows)) {
|
||||
(ChannelsCommands::RenameChannel, Some(row)) if row.kind.renames() => request_rename(&ctx, list, &row.key),
|
||||
|
||||
@@ -223,7 +223,7 @@ impl<'a> ColorRangeDialog<'a> {
|
||||
let preview_words = env.words::<SelectionWords>();
|
||||
// Holding ⌘ (Ctrl off macOS; `Mods` folds Ctrl into `cmd` there) shows the other view while held: view only,
|
||||
// `show_image` does not change.
|
||||
let swapped = pointer::frame(ui.ctx()).mods.cmd;
|
||||
let swapped = pointer::mods(ui.ctx()).cmd;
|
||||
let image_shown = show_image != swapped;
|
||||
let source = if image_shown { image } else { mask };
|
||||
let state = match (&error, source) {
|
||||
@@ -288,7 +288,7 @@ impl<'a> ColorRangeDialog<'a> {
|
||||
f64::from(p.x.floor().max(0.0)) * f64::from(k) + f64::from(k / 2),
|
||||
f64::from(p.y.floor().max(0.0)) * f64::from(k) + f64::from(k / 2),
|
||||
];
|
||||
let mods = pointer::frame(ui.ctx()).mods;
|
||||
let mods = pointer::mods(ui.ctx());
|
||||
let mut next = pass.current.clone();
|
||||
next.samples.pick(at, document, tool, mods);
|
||||
pass.set(&words.eyedropper, next);
|
||||
|
||||
@@ -516,7 +516,7 @@ impl Component for CurveGraph<'_> {
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::splat(cx.picture_width(cx.style.least, cx.style.most))
|
||||
cx.picture_size(cx.style.least, cx.style.most, |width| width)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
|
||||
@@ -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, StyleOp, effect_page, push_edit, set_edit};
|
||||
use super::styles::{StylePresets, styles_page};
|
||||
use super::styles::styles_page;
|
||||
use craft_behavior::EditEvents;
|
||||
|
||||
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();
|
||||
@@ -255,14 +250,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);
|
||||
});
|
||||
});
|
||||
let Work { next, edit, extras } = work;
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -389,7 +382,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(),
|
||||
@@ -423,7 +416,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, EffectKind, EffectSpec, FieldKind, FieldUnit, LayerStyle, LayerStyleDraft, StyleParams,
|
||||
@@ -86,12 +86,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,
|
||||
}
|
||||
|
||||
@@ -329,7 +328,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)
|
||||
@@ -351,7 +350,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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -524,7 +524,7 @@ impl FullWindowWorkspace for RawDevelopWorkspace {
|
||||
let words = env.words::<RawDevelopWords>();
|
||||
let common = env.words::<CommonWords>();
|
||||
let ctx = ui.ctx().clone();
|
||||
let alt = craft_ui::runtime::pointer::frame(&ctx).mods.alt;
|
||||
let alt = craft_ui::runtime::pointer::mods(&ctx).alt;
|
||||
self.open_scope(&ctx, source);
|
||||
|
||||
let name = if self.target == RawTarget::OpenRaw { words.name.clone() } else { words.name_filter.clone() };
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
//! The Levels editor and panel, the Curves panel's point helper and the tone pickers, driven through the public
|
||||
//! widgets as a host would show them.
|
||||
|
||||
use craft_imaging::ui::adjust::{CurvesPanel, Levels, ToneChannels, ToneCurves, ToneSpace};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_imaging::ui::adjust::{CurvesPanel, Levels, LevelsEditor, ToneChannels, ToneCurves, ToneSpace};
|
||||
use craft_imaging::ui::curve::Curve;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::testing::trial;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::Vec2;
|
||||
|
||||
fn grey(v: f32) -> Srgba {
|
||||
Srgba { r: v, g: v, b: v, a: 1.0 }
|
||||
@@ -73,3 +78,28 @@ fn a_curves_point_from_a_sample_goes_on_the_shown_channel_or_on_each_colour() {
|
||||
assert_eq!(xs(&curves, 2), [0.0, 153.0, 255.0]);
|
||||
assert_eq!((xs(&curves, 1).len(), xs(&curves, 3).len()), (2, 2), "the other colours stay as they were");
|
||||
}
|
||||
|
||||
/// Every value field of the editor holds its value whole: the gamma at both ends of its range and the levels at both
|
||||
/// ends of theirs lie inside the field, not cut by its edge.
|
||||
#[trial]
|
||||
fn the_levels_fields_hold_their_values_whole() {
|
||||
for (levels, shown) in
|
||||
[(Levels::new(0.0, 1.0, 255.0, 0.0, 255.0), ["0", "1.00", "255"]), (Levels::new(255.0, 9.99, 255.0, 255.0, 255.0), ["255", "9.99", "255"])]
|
||||
{
|
||||
let state = Rc::new(RefCell::new(levels));
|
||||
let held = Rc::clone(&state);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = LevelsEditor::new("Levels", Bind::bound(&mut *held.borrow_mut())).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(800.0, 600.0));
|
||||
fixture.settle();
|
||||
for value in shown {
|
||||
let painted: Vec<_> = fixture.texts().iter().filter(|text| text.text == value).collect();
|
||||
assert!(!painted.is_empty(), "{value} is painted");
|
||||
for text in painted {
|
||||
assert!(!text.elided, "{value} is not elided");
|
||||
assert!(text.clip.contains_rect(text.rect), "{value} {:?} lies inside its field's clip {:?}", text.rect, text.clip);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! The Channels panel in a host's memoized view: a pointer move beside it replays it (#2812).
|
||||
|
||||
use craft_ui::contract::{MemoProps, MemoView};
|
||||
use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, pointer, trial};
|
||||
use egui::{Modifiers, Pos2, Rect, UiBuilder, Vec2};
|
||||
|
||||
use crate::ui::channels::{ChannelKind, ChannelRow, ChannelsPanel};
|
||||
|
||||
const PANEL: Vec2 = Vec2::new(320.0, 400.0);
|
||||
|
||||
/// What a host's view of the panel reads: its rows, which the host's revision stands for.
|
||||
#[derive(MemoProps)]
|
||||
struct Host<'a> {
|
||||
revision: u64,
|
||||
#[memo_props(covered_by = "revision", reason = "the rows are fixed in this trial")]
|
||||
rows: &'a [ChannelRow<u8>],
|
||||
}
|
||||
|
||||
fn host(props: &mut Host<'_>, ui: &mut egui::Ui) {
|
||||
let _ = ChannelsPanel::new(props.rows).show(ui);
|
||||
}
|
||||
|
||||
/// The panel reads the modifiers its commands take, not the pointer: a pointer move beside it replays its view, and a
|
||||
/// modifier change runs it. Before, every pointer move in the window ran it.
|
||||
#[trial]
|
||||
fn a_pointer_move_beside_the_panel_replays_it_and_a_modifier_runs_it() {
|
||||
let rows =
|
||||
[(0, ChannelKind::Composite, "RGB"), (1, ChannelKind::Color, "Red"), (2, ChannelKind::Color, "Green"), (3, ChannelKind::Color, "Blue")]
|
||||
.map(|(key, kind, name)| ChannelRow::new(key, kind, name));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let at = Rect::from_min_size(ui.max_rect().min, PANEL);
|
||||
ui.scope_builder(UiBuilder::new().max_rect(at), |ui| {
|
||||
MemoView::new("channels", Host { revision: 0, rows: &rows }, host).show(ui);
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::new(PANEL.x + 400.0, PANEL.y)).settle().idle(2);
|
||||
let runs = |fixture: &Fixture| {
|
||||
let runs = last_frame_memo_runs(fixture.ctx());
|
||||
let count = |wanted: MemoRun| runs.iter().filter(|(name, _, run)| name.contains("Host") && *run == wanted).count();
|
||||
(count(MemoRun::Ran), count(MemoRun::Replayed))
|
||||
};
|
||||
// The pointer enters the window beside the panel; in an app it is already there.
|
||||
fixture.frame(vec![pointer::moved(Pos2::new(PANEL.x + 200.0, 90.0))]);
|
||||
for step in 0..3 {
|
||||
fixture.frame(vec![pointer::moved(Pos2::new(PANEL.x + 200.0, 100.0 + step as f32 * 10.0))]);
|
||||
assert_eq!(runs(&fixture), (0, 1), "pointer move {step} beside the panel replays its view");
|
||||
}
|
||||
fixture.hold(Modifiers::ALT).frame(Vec::new());
|
||||
assert_eq!(runs(&fixture).0, 1, "Alt held runs the view");
|
||||
fixture.frame(Vec::new());
|
||||
assert_eq!(runs(&fixture), (0, 1), "and it replays while Alt stays held");
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -5,8 +5,10 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_imaging::layer_style::{EffectId, EffectInstance, EffectKind, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams};
|
||||
use craft_imaging::ui::adjust::{BrightnessContrast, BrightnessContrastEditor, HostedAdjustDialog};
|
||||
use craft_imaging::ui::adjust::{BrightnessContrast, BrightnessContrastEditor, CurvesPanel, HostedAdjustDialog, ToneChannels, ToneCurves, ToneSpace};
|
||||
use craft_imaging::ui::curve::Curve;
|
||||
use craft_imaging::ui::layer_style::{HostedLayerStyle, LayerStyleAsk};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, StackDialog, dialog_id};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
@@ -226,3 +228,66 @@ fn a_held_adjustment_ok_refused_stays_open_and_an_accepted_one_closes() {
|
||||
let answered = host.borrow_mut().take_keyed::<Adjust>().and_then(|(result, _)| result.ok()).map(|value| value.brightness);
|
||||
assert_eq!(answered, Some(5.0), "the accepted OK closes the dialog with the held value");
|
||||
}
|
||||
|
||||
/// The Curves value of the dialog trial: three points on the composite curve.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
struct Curves(ToneCurves);
|
||||
|
||||
impl Default for Curves {
|
||||
fn default() -> Self {
|
||||
let mut curves = ToneCurves::identity(&ToneChannels::of(ToneSpace::Rgb, false));
|
||||
curves.curves[0] = Curve::smooth(vec![[0.0, 0.0], [128.0, 160.0], [255.0, 255.0]]);
|
||||
Curves(curves)
|
||||
}
|
||||
}
|
||||
|
||||
type CurvesDialog = HostedAdjustDialog<Curves, &'static str>;
|
||||
|
||||
// The dialog sizes its content column from what the editor takes, and the graph is a square picture that shows across
|
||||
// that column: everything under it (its tone bar, the selected point's Input and Output, the hint) lies inside the
|
||||
// dialog, not pushed past its edge.
|
||||
#[trial]
|
||||
fn the_curves_dialog_shows_the_tone_bar_the_point_fields_and_the_hint() {
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let mut fixture = fixture(&host);
|
||||
host.borrow_mut().open(CurvesDialog::new("image.adjustments.curves", "Curves", Curves::default(), |ui, value, cx| {
|
||||
let mut panel =
|
||||
CurvesPanel::new("Curves", craft_ui::contract::Bind::bound(&mut value.0), ToneChannels::of(ToneSpace::Rgb, false)).context(cx.context);
|
||||
if let Some(point) = cx.select_point {
|
||||
panel = panel.select(point);
|
||||
}
|
||||
let _ = panel.show(ui);
|
||||
None
|
||||
}));
|
||||
fixture.idle(10);
|
||||
if let Some(dialog) = host.borrow_mut().get_mut::<CurvesDialog>() {
|
||||
dialog.select_point(1);
|
||||
}
|
||||
fixture.settle();
|
||||
let dialog = fixture.by_role(Role::DIALOG).first().map(|dialog| dialog.rect).expect("the Curves dialog shows");
|
||||
let point = fixture.by_label("Point 2 of 3").expect("the middle point");
|
||||
let tree = fixture.tree();
|
||||
let graph = tree.parent_of_key(point.node).and_then(|graph| tree.bounds_of(graph)).expect("the graph holds its points");
|
||||
let input = fixture.by_label("Input").expect("the Input field").rect;
|
||||
let output = fixture.by_label("Output").expect("the Output field").rect;
|
||||
let hint = fixture.texts().iter().find(|text| text.text.starts_with("Click to add a point")).expect("the hint is painted").rect;
|
||||
for (part, rect) in [("the graph and its tone bar", graph), ("Input", input), ("Output", output), ("the hint", hint)] {
|
||||
assert!(dialog.contains_rect(rect), "{part} {rect:?} lies inside the dialog {dialog:?}");
|
||||
}
|
||||
assert!(input.top() >= graph.bottom() && hint.top() >= input.bottom(), "graph, fields, hint top to bottom: {graph:?} {input:?} {hint:?}");
|
||||
|
||||
// The fields read the selected point, and Input moves it.
|
||||
let field = |fixture: &Fixture, name: &str| {
|
||||
let target = fixture.by_label(name).unwrap_or_else(|| panic!("the {name} field"));
|
||||
fixture.tree().value_of(target.node).map(str::to_owned)
|
||||
};
|
||||
assert_eq!(field(&fixture, "Input").as_deref(), Some("128"), "Input reads the selected point's input");
|
||||
assert_eq!(field(&fixture, "Output").as_deref(), Some("160"), "Output reads the selected point's output");
|
||||
let input = fixture.by_label("Input").expect("the Input field");
|
||||
fixture.click(&input).settle();
|
||||
// Tab commits the field; Enter would answer the dialog.
|
||||
fixture.key(Key::A, Modifiers::COMMAND).type_text("96");
|
||||
fixture.key(Key::Tab, Modifiers::NONE).settle();
|
||||
let point = host.borrow().get::<CurvesDialog>().and_then(|dialog| dialog.value().0.curves[0].points().map(|points| points[1]));
|
||||
assert_eq!(point, Some([96.0, 160.0]), "setting Input moves the point");
|
||||
}
|
||||
|
||||
@@ -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, 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() {
|
||||
|
||||
@@ -4,6 +4,7 @@ pub(crate) mod adjust_editors;
|
||||
pub(crate) mod adjust_tone;
|
||||
pub(crate) mod blur_pins;
|
||||
pub(crate) mod channels_delete;
|
||||
pub(crate) mod channels_memo;
|
||||
pub(crate) mod color_range;
|
||||
pub(crate) mod contour_field;
|
||||
pub(crate) mod curve;
|
||||
|
||||
@@ -76,9 +76,7 @@ pub(super) fn show_body<T: LayerTree>(
|
||||
.columns(columns)
|
||||
.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(|drag: &ListDrag<LayerRowKey<T::Id>>, _over, insert| accepts_drop(tree, drag, order, insert, craft_ui::runtime::pointer::mods(&ctx)))
|
||||
.drag_payload({
|
||||
let document = cx.document;
|
||||
move |drag: &ListDrag<LayerRowKey<T::Id>>| Some(LayersDrag::of_rows(drag, document))
|
||||
|
||||
@@ -378,7 +378,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
|
||||
lock_column,
|
||||
visibility_key,
|
||||
trailing: trailing.as_deref(),
|
||||
held: craft_ui::runtime::pointer::frame(ui.ctx()).mods,
|
||||
held: craft_ui::runtime::pointer::mods(ui.ctx()),
|
||||
};
|
||||
let events = RefCell::new(Vec::new());
|
||||
let current = RefCell::new(LayerFilter::default());
|
||||
|
||||
@@ -132,3 +132,35 @@ fn a_clicks_event_is_delivered_once_across_the_run_and_the_replays() {
|
||||
let selects = rig.seen.borrow().iter().filter(|event| matches!(event, LayersEvent::Select(_))).count();
|
||||
assert_eq!(selects, 1, "{:?}", rig.seen.borrow());
|
||||
}
|
||||
|
||||
/// A pointer move beside the panel replays its view: the panel reads the modifiers it shows its rows with, not the
|
||||
/// pointer, so only a modifier change runs it (#2812). Before, every pointer move in the window ran it.
|
||||
#[trial]
|
||||
fn a_pointer_move_beside_the_panel_replays_it_and_a_modifier_runs_it() {
|
||||
let tree = Tracked::new(FakeLayers::fifty());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut filter = LayerFilter::default();
|
||||
let mut events = Vec::new();
|
||||
let at = egui::Rect::from_min_size(ui.max_rect().min, PANEL);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(at), |ui| {
|
||||
MemoView::new("layers", Host { tree: &tree, filter: Bind::bound(&mut filter), events: Outbox::new(&mut events) }, host).show(ui);
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::new(PANEL.x + 400.0, PANEL.y));
|
||||
fixture.settle().idle(2);
|
||||
let runs = |fixture: &Fixture| {
|
||||
let runs = last_frame_memo_runs(fixture.ctx());
|
||||
let count = |wanted: MemoRun| runs.iter().filter(|(name, _, run)| name.contains("Host") && *run == wanted).count();
|
||||
(count(MemoRun::Ran), count(MemoRun::Replayed))
|
||||
};
|
||||
// The pointer enters the window beside the panel; in an app it is already there.
|
||||
fixture.frame(vec![pointer::moved(egui::Pos2::new(PANEL.x + 200.0, 90.0))]);
|
||||
for step in 0..3 {
|
||||
fixture.frame(vec![pointer::moved(egui::Pos2::new(PANEL.x + 200.0, 100.0 + step as f32 * 10.0))]);
|
||||
assert_eq!(runs(&fixture), (0, 1), "pointer move {step} beside the panel replays its view");
|
||||
}
|
||||
fixture.hold(egui::Modifiers::ALT).frame(Vec::new());
|
||||
assert_eq!(runs(&fixture).0, 1, "Alt held runs the view");
|
||||
fixture.frame(Vec::new());
|
||||
assert_eq!(runs(&fixture), (0, 1), "and it replays while Alt stays held");
|
||||
}
|
||||
|
||||
@@ -132,7 +132,9 @@ app translates. The dialog never opens a file dialog or touches the file system.
|
||||
|
||||
## Windows, Linux and web: the in-window bar
|
||||
|
||||
`MenuBarUi` draws a laid-out bar in a top panel and returns the titles' rect (`MenuBarOutput`).
|
||||
`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a
|
||||
`Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold
|
||||
into "…".
|
||||
Each item is a command row: its enabled state, check mark and chord follow the command in the
|
||||
runtime's command state and keymap, and a choice is a `Fired` with `FireSource::Menu` in the
|
||||
frame's output. `.help_search(true)` starts the Help menu with a search field over every command
|
||||
@@ -141,7 +143,9 @@ frame's output. `.help_search(true)` starts the Help menu with a search field ov
|
||||
```rust
|
||||
let laid_out = craft_menu::layout(&menu_bar, Target::current(), &LayoutOptions::new("Sample")).bar;
|
||||
egui::Panel::top("menu-bar").show(ui, |ui| {
|
||||
MenuBarUi::new(&laid_out).keyboard(!dialog_open).help_search(true).show(ui);
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
MenuBarUi::new(&laid_out).keyboard(!dialog_open).help_search(true).show(ui);
|
||||
});
|
||||
});
|
||||
// The commands chosen arrive in `FrameOutput.fired`.
|
||||
```
|
||||
@@ -156,7 +160,7 @@ egui::Panel::top("menu-bar").show(ui, |ui| {
|
||||
they are off unless set. `.mnemonics(&[("View", 'W'), ("file.open", 'P')])` names preferred
|
||||
letters by title as shown or by command id. A label without an ASCII letter or digit shows its
|
||||
English label's letter after it, "文件(F)", before a trailing ellipsis ("開く(O)…"), when
|
||||
`.english(&hook)` returns that English label for the `Labeled::Command` or `Labeled::Title`.
|
||||
the item, submenu or menu carries that English label (`Item::english`, `Node::english`, `Menu::english`).
|
||||
- **Items:** a command the runtime's gate forbids, or whose state is disabled, is greyed and never
|
||||
fires. A submenu whose items are all disabled is greyed. The shortcut column shows the command's
|
||||
chord, else the item's own shortcut, in the shell's names (⌘ glyphs on a Mac). `.target(..)`
|
||||
|
||||
+19
-55
@@ -13,8 +13,8 @@ pub(crate) mod stories;
|
||||
|
||||
use craft_host::target::Os;
|
||||
use craft_i18n::Words;
|
||||
use craft_keymap::{CommandRef, Platform};
|
||||
use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless, Tracked};
|
||||
use craft_keymap::Platform;
|
||||
use craft_ui::contract::{MemoProps, MemoView, Show as _, Tracked};
|
||||
use craft_ui::menu::{MenuBar as Bar, MenuHelp, MenuTitle};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use egui::{Rect, Ui};
|
||||
@@ -27,19 +27,6 @@ use crate::palette::entries_of;
|
||||
/// Whether a menu of the bar is open; the app's single-key shortcuts wait while it is true.
|
||||
pub use craft_ui::menu::bar::{is_focused, is_open};
|
||||
|
||||
/// A row or title, as the bar names it to the app's mnemonic hooks ([`MenuBarUi::english`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Labeled<'s> {
|
||||
/// An item, by its command.
|
||||
Command(&'s CommandRef),
|
||||
/// A menu or submenu, by its title as shown.
|
||||
Title(&'s str),
|
||||
}
|
||||
|
||||
/// The app's English labels ([`MenuBarUi::english`]).
|
||||
pub type EnglishHook<'h> = dyn Fn(Labeled<'_>) -> Option<String> + 'h;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of the in-window bar that the menu family does not hold.
|
||||
struct BarWords {
|
||||
@@ -78,21 +65,17 @@ pub struct MenuBarOutput {
|
||||
pub titles: Rect,
|
||||
}
|
||||
|
||||
/// The English-label hook a bar takes by default: none is set, so this type only names the slot.
|
||||
pub type EnglishFn = fn(Labeled<'_>) -> Option<String>;
|
||||
|
||||
/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, in a top panel.
|
||||
/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, inside a `Stack` (a top
|
||||
/// panel's body) or the title bar's row: there it folds the titles that don't fit its room into "…".
|
||||
/// The commands chosen come back through the command queue, not from `show`.
|
||||
///
|
||||
/// The bar is a memoized view: while its model, options, place and environment are those of its last run and nothing
|
||||
/// reaches it (pointer, focus, keys, an open menu), it adds that run again in place of running.
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
#[pattern(probe(MenuBarUi<'static, EnglishFn>))]
|
||||
pub struct MenuBarUi<'a, E = EnglishFn> {
|
||||
pub struct MenuBarUi<'a> {
|
||||
bar: &'a Tracked<MenuBar>,
|
||||
/// The platform set with [`target`](Self::target); the shell's when none is.
|
||||
target: Option<Target>,
|
||||
english: Option<Stateless<E>>,
|
||||
preferred: &'a [(&'a str, char)],
|
||||
keyboard: Option<bool>,
|
||||
help_search: bool,
|
||||
@@ -100,10 +83,9 @@ pub struct MenuBarUi<'a, E = EnglishFn> {
|
||||
|
||||
/// Every input of the bar's view.
|
||||
#[derive(MemoProps)]
|
||||
struct BarProps<'a, #[memo_props(stateless)] E> {
|
||||
struct BarProps<'a> {
|
||||
bar: &'a Tracked<MenuBar>,
|
||||
target: Target,
|
||||
english: Option<Stateless<E>>,
|
||||
preferred: &'a [(&'a str, char)],
|
||||
keyboard: bool,
|
||||
help: Option<usize>,
|
||||
@@ -113,47 +95,37 @@ struct BarProps<'a, #[memo_props(stateless)] E> {
|
||||
impl<'a> MenuBarUi<'a> {
|
||||
/// The bar for `bar`, already laid out ([`crate::layout`]), on the shell's platform ([`Target::of_shell`]).
|
||||
pub fn new(bar: &'a Tracked<MenuBar>) -> MenuBarUi<'a> {
|
||||
MenuBarUi { bar, target: None, english: None, preferred: &[], keyboard: None, help_search: false }
|
||||
MenuBarUi { bar, target: None, preferred: &[], keyboard: None, help_search: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static> MenuBarUi<'a, E> {
|
||||
impl<'a> MenuBarUi<'a> {
|
||||
/// The platform the bar is on, for the shortcut column ([`craft_keymap::Chord::display`]): ⌘ glyphs on
|
||||
/// [`Target::Mac`] and in a browser on a Mac, Ctrl names everywhere else. On [`Target::Mac`] the native bar
|
||||
/// has the keys, and this one takes none unless [`keyboard`](Self::keyboard) says so.
|
||||
pub fn target(mut self, target: Target) -> MenuBarUi<'a, E> {
|
||||
pub fn target(mut self, target: Target) -> MenuBarUi<'a> {
|
||||
self.target = Some(target);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the bar takes F10, Alt and Alt with a letter. By default it does, except on [`Target::Mac`]. The
|
||||
/// app turns it off while a modal dialog or the shortcut recorder has the keys.
|
||||
pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a, E> {
|
||||
pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a> {
|
||||
self.keyboard = Some(on);
|
||||
self
|
||||
}
|
||||
|
||||
/// The English label of a row or title, for labels the keyboard can't type a letter of (Chinese, Japanese,
|
||||
/// Korean…): such a label shows its English label's mnemonic after it, "文件(F)", before a trailing ellipsis
|
||||
/// ("開く(O)…"), as Windows menus do. Without this hook (or when it returns `None`) such a label has no
|
||||
/// mnemonic. The Help menu's search also matches the English labels, on every target. The hook is a fn item or a
|
||||
/// closure that captures nothing ([`Stateless`]): the bar's key follows its type.
|
||||
pub fn english<F: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(self, english: F) -> MenuBarUi<'a, F> {
|
||||
let MenuBarUi { bar, target, english: _, preferred, keyboard, help_search } = self;
|
||||
MenuBarUi { bar, target, english: Some(Stateless::new(english)), preferred, keyboard, help_search }
|
||||
}
|
||||
|
||||
/// Preferred mnemonics, each for a menu or submenu by its title as shown or for an item by its command id:
|
||||
/// the row takes that letter when its label has it and no row before it in its menu took it. Every other row
|
||||
/// takes the first unused letter of its label, word starts first.
|
||||
pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a, E> {
|
||||
pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a> {
|
||||
self.preferred = preferred;
|
||||
self
|
||||
}
|
||||
|
||||
/// Start the [`MenuRole::Help`] menu with a search field over every command of the bar
|
||||
/// ([`MenuBar::help_entries`]). A bar with no Help menu has no field.
|
||||
pub fn help_search(mut self, on: bool) -> MenuBarUi<'a, E> {
|
||||
pub fn help_search(mut self, on: bool) -> MenuBarUi<'a> {
|
||||
self.help_search = on;
|
||||
self
|
||||
}
|
||||
@@ -168,24 +140,18 @@ impl<'a, E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static> MenuBarUi<'a, E>
|
||||
let props = BarProps {
|
||||
bar: self.bar,
|
||||
target,
|
||||
english: self.english,
|
||||
preferred: self.preferred,
|
||||
keyboard: self.keyboard.unwrap_or(target != Target::Mac),
|
||||
help,
|
||||
label: env.words::<BarWords>().label.clone(),
|
||||
};
|
||||
MemoView::new("menu-bar", props, show_bar::<E>).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING })
|
||||
MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING })
|
||||
}
|
||||
}
|
||||
|
||||
/// The bar's view: the titles through [`craft_ui::menu::MenuBar`], each menu's rows as command rows.
|
||||
fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut BarProps<'_, E>, ui: &mut Ui) -> MenuBarOutput {
|
||||
let hook = props.english.map(|english| {
|
||||
let english = english.get();
|
||||
move |labeled: Labeled<'_>| english(labeled)
|
||||
});
|
||||
let english: Option<&EnglishHook<'_>> = hook.as_ref().map(|hook| hook as &EnglishHook<'_>);
|
||||
let rows = Rows::new(props.target).english(english).preferred(props.preferred);
|
||||
fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput {
|
||||
let rows = Rows::new(props.target).preferred(props.preferred);
|
||||
let env = Env::of(ui);
|
||||
let os = env.view().shell().os;
|
||||
// The text of every menu is worked out once for these inputs and kept: a pass that shows an open menu again writes none of it.
|
||||
@@ -194,7 +160,6 @@ fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut B
|
||||
target: props.target,
|
||||
os,
|
||||
preferred: props.preferred,
|
||||
english: props.english,
|
||||
words: &env.words,
|
||||
keymap: craft_ui::runtime::commands::keymap_generation(ui.ctx()),
|
||||
};
|
||||
@@ -212,7 +177,7 @@ fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut B
|
||||
.collect();
|
||||
// Collecting the search's commands walks every row of every menu: the bar does it only while Help is open.
|
||||
let bar_model: &MenuBar = props.bar;
|
||||
let entries = move || entries_of(bar_model, english);
|
||||
let entries = move || entries_of(bar_model);
|
||||
let mut bar = Bar::new(props.label.clone(), titles).keyboard(props.keyboard);
|
||||
if let Some(menu) = props.help {
|
||||
bar = bar.help(MenuHelp::new(menu, &entries));
|
||||
@@ -220,15 +185,14 @@ fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut B
|
||||
MenuBarOutput { titles: bar.show(ui).titles }
|
||||
}
|
||||
|
||||
/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the mnemonic and English
|
||||
/// hooks, the language and the keymap.
|
||||
/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics,
|
||||
/// the language and the keymap. The English names are part of the model.
|
||||
#[derive(MemoProps)]
|
||||
struct LabelKey<'a, #[memo_props(stateless)] E> {
|
||||
struct LabelKey<'a> {
|
||||
bar: &'a Tracked<MenuBar>,
|
||||
target: Target,
|
||||
os: Os,
|
||||
preferred: &'a [(&'a str, char)],
|
||||
english: Option<Stateless<E>>,
|
||||
words: &'a Words,
|
||||
keymap: u64,
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use craft_ui::runtime::pointer;
|
||||
use craft_ui::runtime::windows::{WindowAction, WindowHost};
|
||||
use egui::{Ui, ViewportId};
|
||||
|
||||
use crate::bar::{EnglishHook, Labeled, keymap_platform};
|
||||
use crate::bar::keymap_platform;
|
||||
use crate::layout::Target;
|
||||
use crate::model::{Builtin, Item, ItemKind, Node};
|
||||
|
||||
@@ -54,22 +54,16 @@ pub(crate) struct BarLabels {
|
||||
pub(crate) menus: Vec<LevelLabels>,
|
||||
}
|
||||
|
||||
/// How the rows of a menu are written: the target that names the shortcuts, the app's English labels and its
|
||||
/// preferred mnemonic letters.
|
||||
/// How the rows of a menu are written: the target that names the shortcuts and the app's preferred mnemonic
|
||||
/// letters.
|
||||
pub(crate) struct Rows<'a> {
|
||||
target: Target,
|
||||
english: Option<&'a EnglishHook<'a>>,
|
||||
preferred: &'a [(&'a str, char)],
|
||||
}
|
||||
|
||||
impl<'a> Rows<'a> {
|
||||
pub(crate) fn new(target: Target) -> Self {
|
||||
Rows { target, english: None, preferred: &[] }
|
||||
}
|
||||
|
||||
pub(crate) fn english(mut self, english: Option<&'a EnglishHook<'a>>) -> Self {
|
||||
self.english = english;
|
||||
self
|
||||
Rows { target, preferred: &[] }
|
||||
}
|
||||
|
||||
pub(crate) fn preferred(mut self, preferred: &'a [(&'a str, char)]) -> Self {
|
||||
@@ -112,10 +106,6 @@ impl<'a> Rows<'a> {
|
||||
self.preferred.iter().find(|(k, _)| *k == key).map(|(_, c)| *c)
|
||||
}
|
||||
|
||||
pub(crate) fn english_of(&self, labeled: Labeled<'_>) -> Option<String> {
|
||||
self.english.and_then(|hook| hook(labeled))
|
||||
}
|
||||
|
||||
/// The label a node shows as the menu's sibling, for the preferred letters and the English labels.
|
||||
pub(crate) fn node_labels(&self, nodes: &[Node]) -> Vec<String> {
|
||||
let shown: Vec<&Node> = nodes.iter().filter(|node| !matches!(node, Node::Separator | Node::Standard { .. })).collect();
|
||||
@@ -133,8 +123,8 @@ impl<'a> Rows<'a> {
|
||||
_ => "",
|
||||
},
|
||||
|node| match node {
|
||||
Node::Item(item) => self.english_of(Labeled::Command(&item.command)),
|
||||
Node::Submenu { label, .. } => self.english_of(Labeled::Title(label)),
|
||||
Node::Item(item) => item.english.clone(),
|
||||
Node::Submenu { english, .. } => english.clone(),
|
||||
_ => None,
|
||||
},
|
||||
)
|
||||
@@ -164,7 +154,7 @@ impl<'a> Rows<'a> {
|
||||
|
||||
/// The text of a whole bar: the titles and each menu's rows.
|
||||
pub(crate) fn bar_labels(&self, menus: &[crate::model::Menu], platform: Platform) -> BarLabels {
|
||||
let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| self.english_of(Labeled::Title(&menu.title)));
|
||||
let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| menu.english.clone());
|
||||
BarLabels { titles, menus: menus.iter().map(|menu| self.level_labels(&menu.children, platform)).collect() }
|
||||
}
|
||||
|
||||
|
||||
@@ -103,6 +103,11 @@ impl<'a> LayoutOptions<'a> {
|
||||
(self.label)(english).replace("{app}", self.app_name)
|
||||
}
|
||||
|
||||
/// The English text of a label `text` writes, `{app}` filled in.
|
||||
fn english_text(&self, english: &'static str) -> String {
|
||||
english.replace("{app}", self.app_name)
|
||||
}
|
||||
|
||||
fn standard(&self, kind: Standard) -> Node {
|
||||
Node::Standard { kind, label: self.text(kind.english()) }
|
||||
}
|
||||
@@ -181,6 +186,7 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout {
|
||||
let mut menu = Vec::new();
|
||||
if let Some(Node::Item(mut it)) = about {
|
||||
it.label = options.text("About {app}");
|
||||
it.english = Some(options.english_text("About {app}"));
|
||||
menu.extend([Node::Item(it), Node::Separator]);
|
||||
}
|
||||
if let Some(s) = settings {
|
||||
@@ -188,8 +194,9 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout {
|
||||
menu.push(settings_node(s, comma, options, &mut clashes));
|
||||
}
|
||||
if let Some(mut l) = language {
|
||||
if let Node::Submenu { label, .. } = &mut l {
|
||||
if let Node::Submenu { label, english, .. } = &mut l {
|
||||
*label = options.text("Language");
|
||||
*english = Some("Language".to_owned());
|
||||
}
|
||||
menu.push(l);
|
||||
}
|
||||
@@ -228,6 +235,7 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout {
|
||||
_ => Item::new(Builtin::Quit.command(), "").role(ItemRole::Quit),
|
||||
};
|
||||
quit.label = options.text("Quit {app}");
|
||||
quit.english = Some(options.english_text("Quit {app}"));
|
||||
match taken(CMD_Q, std::slice::from_ref(&quit.command)) {
|
||||
Some(command) => {
|
||||
clashes.push(Clash { shortcut: CMD_Q, system: "Quit", command, resolution: "Quit has no shortcut" });
|
||||
@@ -349,15 +357,19 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option
|
||||
_ => Item::new(Builtin::Quit.command(), "").role(ItemRole::Quit),
|
||||
};
|
||||
it.label = options.text(label);
|
||||
it.english = Some(options.english_text(label));
|
||||
ensure_menu(&mut bar, MenuRole::File, "File", options).children.extend([Node::Separator, Node::Item(it)]);
|
||||
}
|
||||
if let Some(s) = settings {
|
||||
let s = match s {
|
||||
Node::Item(mut it) => {
|
||||
it.label = options.text("Preferences…");
|
||||
it.english = Some("Preferences…".to_owned());
|
||||
Node::Item(it)
|
||||
}
|
||||
Node::Submenu { children, role, platforms, .. } => Node::Submenu { label: options.text("Preferences"), children, role, platforms },
|
||||
Node::Submenu { children, role, platforms, .. } => {
|
||||
Node::Submenu { label: options.text("Preferences"), english: Some("Preferences".to_owned()), children, role, platforms }
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
ensure_menu(&mut bar, MenuRole::Edit, "Edit", options).children.extend([Node::Separator, s]);
|
||||
@@ -370,6 +382,7 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option
|
||||
}
|
||||
if let Some(Node::Item(mut it)) = about {
|
||||
it.label = options.text("About {app}");
|
||||
it.english = Some(options.english_text("About {app}"));
|
||||
ensure_menu(&mut bar, MenuRole::Help, "Help", options).children.extend([Node::Separator, Node::Item(it)]);
|
||||
}
|
||||
finish(&mut bar, |_| false);
|
||||
@@ -383,9 +396,13 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar {
|
||||
let shown = nodes.iter().filter_map(|n| match n {
|
||||
Node::Item(it) if !it.platforms.contains(on) => None,
|
||||
Node::Submenu { platforms, .. } if !platforms.contains(on) => None,
|
||||
Node::Submenu { label, children, role, platforms } => {
|
||||
Some(Node::Submenu { label: label.clone(), children: keep(children, on, appkit), role: *role, platforms: *platforms })
|
||||
}
|
||||
Node::Submenu { label, english, children, role, platforms } => Some(Node::Submenu {
|
||||
label: label.clone(),
|
||||
english: english.clone(),
|
||||
children: keep(children, on, appkit),
|
||||
role: *role,
|
||||
platforms: *platforms,
|
||||
}),
|
||||
Node::Standard { .. } if !appkit => None,
|
||||
other => Some(other.clone()),
|
||||
});
|
||||
@@ -420,7 +437,7 @@ fn ensure_menu<'b>(bar: &'b mut MenuBar, role: MenuRole, english: &'static str,
|
||||
MenuRole::Help => bar.menus.len(),
|
||||
_ => bar.menus.iter().position(|m| m.role == MenuRole::Help).unwrap_or(bar.menus.len()),
|
||||
};
|
||||
bar.menus.insert(at, Menu::new(options.text(english), Vec::new()).role(role));
|
||||
bar.menus.insert(at, Menu::new(options.text(english), Vec::new()).english(english).role(role));
|
||||
at
|
||||
}
|
||||
};
|
||||
@@ -450,6 +467,7 @@ fn settings_node(node: Node, comma_taken: Option<CommandRef>, options: &LayoutOp
|
||||
match node {
|
||||
Node::Item(mut it) => {
|
||||
it.label = options.text("Settings…");
|
||||
it.english = Some("Settings…".to_owned());
|
||||
give(&mut it);
|
||||
Node::Item(it)
|
||||
}
|
||||
@@ -457,7 +475,7 @@ fn settings_node(node: Node, comma_taken: Option<CommandRef>, options: &LayoutOp
|
||||
if let Some(Node::Item(first)) = children.iter_mut().find(|n| matches!(n, Node::Item(i) if i.enabled)) {
|
||||
give(first);
|
||||
}
|
||||
Node::Submenu { label: options.text("Settings"), children, role, platforms }
|
||||
Node::Submenu { label: options.text("Settings"), english: Some("Settings".to_owned()), children, role, platforms }
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
@@ -478,7 +496,7 @@ fn appearance_node(bar: &mut MenuBar, options: &LayoutOptions) -> Vec<Node> {
|
||||
children.push(Node::Separator);
|
||||
children.extend(items);
|
||||
}
|
||||
vec![Node::Submenu { label: options.text("Appearance"), children, role, platforms }]
|
||||
vec![Node::Submenu { label: options.text("Appearance"), english: Some("Appearance".to_owned()), children, role, platforms }]
|
||||
}
|
||||
_ => items,
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ pub mod mac;
|
||||
pub mod ribbon;
|
||||
pub mod shortcuts;
|
||||
|
||||
pub use bar::{EnglishHook, Labeled, MenuBarOutput, MenuBarUi};
|
||||
pub use bar::{MenuBarOutput, MenuBarUi};
|
||||
pub use craft_keymap::{Chord, CommandRef};
|
||||
pub use customize::Customization;
|
||||
pub use documents::DOCUMENT_COMMAND_PREFIX;
|
||||
|
||||
@@ -57,6 +57,9 @@ impl Document {
|
||||
pub struct Menu {
|
||||
/// The title in the bar.
|
||||
pub title: String,
|
||||
/// The title's English name, when `title` is a translation: the bar takes the mnemonic of a title the keyboard
|
||||
/// can't type from it.
|
||||
pub english: Option<String>,
|
||||
/// What the menu is for.
|
||||
pub role: MenuRole,
|
||||
/// The menu's entries, top to bottom.
|
||||
@@ -145,6 +148,8 @@ pub enum Node {
|
||||
Submenu {
|
||||
/// The submenu's title.
|
||||
label: String,
|
||||
/// The title's English name, when `label` is a translation ([`Menu::english`]).
|
||||
english: Option<String>,
|
||||
/// The submenu's entries.
|
||||
children: Vec<Node>,
|
||||
/// The place a layout gives it, if any.
|
||||
@@ -172,6 +177,9 @@ pub struct Item {
|
||||
pub command: CommandRef,
|
||||
/// The text shown.
|
||||
pub label: String,
|
||||
/// The label's English name, when `label` is a translation. A label the keyboard can't type (Chinese, Japanese,
|
||||
/// Korean…) takes its mnemonic from it in the in-window bar, and the Help search matches it on every target.
|
||||
pub english: Option<String>,
|
||||
/// `cmd` is ⌘ and `ctrl` the Control key: ⌃⌘M and ⌘M are different shortcuts.
|
||||
pub shortcut: Option<Chord>,
|
||||
/// Whether the item can be chosen.
|
||||
@@ -354,6 +362,7 @@ impl Item {
|
||||
Item {
|
||||
command: command.into(),
|
||||
label: label.into(),
|
||||
english: None,
|
||||
shortcut: None,
|
||||
enabled: true,
|
||||
kind: ItemKind::Plain,
|
||||
@@ -402,6 +411,12 @@ impl Item {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the label's English name ([`Item::english`] field).
|
||||
pub fn english(mut self, english: impl Into<String>) -> Item {
|
||||
self.english = Some(english.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Show the item only on `platforms`.
|
||||
pub fn platforms(mut self, platforms: Platforms) -> Item {
|
||||
self.platforms = platforms;
|
||||
@@ -435,7 +450,17 @@ impl Node {
|
||||
|
||||
/// A submenu shown on every platform.
|
||||
pub fn submenu(label: impl Into<String>, children: Vec<Node>) -> Node {
|
||||
Node::Submenu { label: label.into(), children, role: None, platforms: Platforms::ALL }
|
||||
Node::Submenu { label: label.into(), english: None, children, role: None, platforms: Platforms::ALL }
|
||||
}
|
||||
|
||||
/// Set the English name of an item's label or a submenu's title.
|
||||
pub fn english(mut self, english: impl Into<String>) -> Node {
|
||||
match &mut self {
|
||||
Node::Item(it) => it.english = Some(english.into()),
|
||||
Node::Submenu { english: e, .. } => *e = Some(english.into()),
|
||||
Node::Separator | Node::Standard { .. } => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Give an item or a submenu a role: `Node::submenu("Theme", pages).role(ItemRole::Appearance)`.
|
||||
@@ -462,7 +487,13 @@ impl Node {
|
||||
impl Menu {
|
||||
/// A menu with no special role.
|
||||
pub fn new(title: impl Into<String>, children: Vec<Node>) -> Menu {
|
||||
Menu { title: title.into(), role: MenuRole::Other, children }
|
||||
Menu { title: title.into(), english: None, role: MenuRole::Other, children }
|
||||
}
|
||||
|
||||
/// Set the title's English name ([`Menu::english`] field).
|
||||
pub fn english(mut self, english: impl Into<String>) -> Menu {
|
||||
self.english = Some(english.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the menu's role.
|
||||
@@ -580,6 +611,8 @@ pub struct Row {
|
||||
pub command: CommandRef,
|
||||
/// The text shown.
|
||||
pub label: String,
|
||||
/// The label's English name, when `label` is a translation ([`Item::english`]).
|
||||
pub english: Option<String>,
|
||||
/// The row's shortcut.
|
||||
pub shortcut: Option<Chord>,
|
||||
/// Whether the row can be chosen.
|
||||
@@ -601,6 +634,7 @@ impl Row {
|
||||
path: path.iter().map(|s| (*s).to_owned()).collect(),
|
||||
command: command.into(),
|
||||
label: label.into(),
|
||||
english: None,
|
||||
shortcut: None,
|
||||
enabled: true,
|
||||
kind: ItemKind::Plain,
|
||||
@@ -610,6 +644,12 @@ impl Row {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the label's English name.
|
||||
pub fn english(mut self, english: impl Into<String>) -> Row {
|
||||
self.english = Some(english.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the row can be chosen.
|
||||
pub fn enabled(mut self, on: bool) -> Row {
|
||||
self.enabled = on;
|
||||
@@ -682,6 +722,7 @@ pub fn from_items(tops: &[&str], rows: &[Row]) -> MenuBar {
|
||||
match slot {
|
||||
Slot::Leaf(it) if it.label == "---" => out.push(Node::Separator),
|
||||
Slot::Leaf(it) => out.push(Node::Item(Item {
|
||||
english: it.english.clone(),
|
||||
shortcut: it.shortcut,
|
||||
enabled: it.enabled,
|
||||
kind: it.kind,
|
||||
|
||||
+10
-12
@@ -2,7 +2,6 @@
|
||||
|
||||
use craft_ui::menu::HelpEntry;
|
||||
|
||||
use crate::bar::{EnglishHook, Labeled};
|
||||
use crate::model::{Builtin, MenuBar, Node};
|
||||
use crate::{LayoutOptions, Target, layout};
|
||||
|
||||
@@ -18,39 +17,38 @@ impl MenuBar {
|
||||
/// Building the list lays out the whole bar, so a host caches the result and rebuilds it when the bar
|
||||
/// changes, not every frame.
|
||||
///
|
||||
/// `english` gives a command's or menu title's English name (as [`crate::MenuBarUi::english`]), asked on
|
||||
/// every target, so the search finds a translated command by its English name.
|
||||
pub fn help_entries(&self, target: Target, options: &LayoutOptions, english: Option<&EnglishHook<'_>>) -> Vec<HelpEntry> {
|
||||
entries_of(&layout(self, target, options).bar, english)
|
||||
/// An item's [`english`](crate::Item::english) name is listed with it, on every target, so the search finds a
|
||||
/// translated command by its English name.
|
||||
pub fn help_entries(&self, target: Target, options: &LayoutOptions) -> Vec<HelpEntry> {
|
||||
entries_of(&layout(self, target, options).bar)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries of an already laid-out bar.
|
||||
pub(crate) fn entries_of(bar: &MenuBar, english: Option<&EnglishHook<'_>>) -> Vec<HelpEntry> {
|
||||
let english_of = |labeled: Labeled<'_>| english.and_then(|hook| hook(labeled));
|
||||
pub(crate) fn entries_of(bar: &MenuBar) -> Vec<HelpEntry> {
|
||||
let mut entries = Vec::new();
|
||||
let mut path: Vec<String> = Vec::new();
|
||||
for menu in &bar.menus {
|
||||
path.push(menu.title.clone());
|
||||
collect(&menu.children, &mut path, &english_of, &mut entries);
|
||||
collect(&menu.children, &mut path, &mut entries);
|
||||
path.pop();
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
fn collect(nodes: &[Node], path: &mut Vec<String>, english_of: &dyn Fn(Labeled<'_>) -> Option<String>, entries: &mut Vec<HelpEntry>) {
|
||||
fn collect(nodes: &[Node], path: &mut Vec<String>, entries: &mut Vec<HelpEntry>) {
|
||||
for node in nodes {
|
||||
match node {
|
||||
Node::Item(item) if Builtin::of(&item.command).is_none() => {
|
||||
let mut entry = HelpEntry::new(item.command.clone(), item.label.clone()).with_path(path.iter().cloned());
|
||||
if let Some(english) = english_of(Labeled::Command(&item.command)) {
|
||||
entry = entry.with_english(english);
|
||||
if let Some(english) = &item.english {
|
||||
entry = entry.with_english(english.clone());
|
||||
}
|
||||
entries.push(entry);
|
||||
}
|
||||
Node::Submenu { label, children, .. } => {
|
||||
path.push(label.clone());
|
||||
collect(children, path, english_of, entries);
|
||||
collect(children, path, entries);
|
||||
path.pop();
|
||||
}
|
||||
Node::Item(_) | Node::Separator | Node::Standard { .. } => {}
|
||||
|
||||
@@ -12,6 +12,7 @@ pub(crate) mod ribbon;
|
||||
pub(crate) mod ribbon_gallery;
|
||||
mod sample;
|
||||
pub(crate) mod shortcuts;
|
||||
pub(crate) mod title_bar;
|
||||
|
||||
craft_ui::registry!();
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The in-window bar is a memoized view: idle frames replay it, a title rename or Alt runs it once, and an open menu
|
||||
//! runs it while it is open.
|
||||
//! replays with it while nothing reaches the menu.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
@@ -67,18 +67,26 @@ fn alt_runs_the_menu_bar_once_each_way() {
|
||||
assert_eq!(counted(&fixture).0, 1, "Alt up runs the bar once");
|
||||
}
|
||||
|
||||
/// A menu the bar opens is an overlay inside its run, which keeps the run from being replayed while it is open. The
|
||||
/// run in which the menu's fade ends is the last that shows it, so the replays after it match a real run (the audit).
|
||||
/// A menu the bar opens is an overlay of its run: with the focus on the menu's first row, an idle frame replays the bar
|
||||
/// and the open menu, and a key the menu takes runs the bar in its frame.
|
||||
#[trial]
|
||||
fn an_open_menu_runs_the_bar_and_closing_it_replays_it() {
|
||||
fn an_idle_open_menu_replays_and_a_key_in_it_runs_the_bar() {
|
||||
let bar = Rc::new(RefCell::new(model("File")));
|
||||
let mut fixture = fixture(&bar);
|
||||
audit_replays(fixture.ctx(), true);
|
||||
fixture.key(Key::F, Modifiers::ALT);
|
||||
fixture.settle();
|
||||
assert!(fixture.by_label("New").is_some(), "Alt+F opened File");
|
||||
for _ in 0..3 {
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(counted(&fixture), (0, 1), "an idle frame replays the bar and its open menu");
|
||||
assert!(fixture.by_label("New").is_some(), "the replayed menu keeps its rows' nodes");
|
||||
}
|
||||
fixture.key(Key::ArrowDown, Modifiers::NONE);
|
||||
assert!(counted(&fixture).0 > 0, "a key in the open menu runs the bar in its frame");
|
||||
fixture.settle();
|
||||
fixture.frame(vec![]);
|
||||
assert!(counted(&fixture).0 > 0, "the bar runs while a menu is open");
|
||||
assert_eq!(counted(&fixture), (0, 1), "then the bar replays again");
|
||||
// The first Escape closes the menu; the bar keeps the keyboard until the second one hands it back.
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
fixture.settle();
|
||||
@@ -104,10 +112,12 @@ fn an_idle_bar_and_an_open_menu_build_no_labels() {
|
||||
fixture.key(Key::F, Modifiers::ALT);
|
||||
fixture.settle();
|
||||
assert!(fixture.by_label("New").is_some(), "Alt+F opened File");
|
||||
fixture.key(Key::ArrowDown, Modifiers::NONE);
|
||||
assert!(counted(&fixture).0 > 0, "a key in the open menu runs the bar");
|
||||
assert_eq!(label_builds(&fixture), 0, "and builds no labels");
|
||||
for _ in 0..3 {
|
||||
fixture.frame(vec![]);
|
||||
assert!(counted(&fixture).0 > 0, "the bar runs each pass while a menu is open");
|
||||
assert_eq!(label_builds(&fixture), 0, "and builds no labels");
|
||||
assert_eq!(label_builds(&fixture), 0, "an idle open menu builds no labels");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,21 +5,18 @@ use std::sync::Arc;
|
||||
|
||||
use craft_host::target::Os;
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_menu::{CommandRef, Labeled, MenuBarUi, Row, from_items};
|
||||
use craft_menu::{CommandRef, LayoutOptions, MenuBarUi, Row, Target, from_items};
|
||||
use craft_ui::contract::Tracked;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
#[trial]
|
||||
fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() {
|
||||
let bar = Tracked::new(from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")]));
|
||||
let english = |labeled: Labeled<'_>| match labeled {
|
||||
Labeled::Title("文件") => Some("File".to_owned()),
|
||||
Labeled::Command(command) if *command == CommandRef::new("file.new") => Some("New".to_owned()),
|
||||
_ => None,
|
||||
};
|
||||
let mut bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建").english("New")]);
|
||||
bar.menus[0].english = Some("File".to_owned());
|
||||
let bar = Tracked::new(bar);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
MenuBarUi::new(&bar).english(english).show(ui);
|
||||
MenuBarUi::new(&bar).show(ui);
|
||||
});
|
||||
// A Mac bar has no letters.
|
||||
fixture.os(Os::Linux);
|
||||
@@ -30,6 +27,14 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() {
|
||||
assert!(fixture.by_label("新建(N)").is_some(), "Alt+F opens the title's menu, whose row shows its own English letter");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn help_search_lists_an_item_by_its_english_name_in_a_translated_model() {
|
||||
let bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建").english("New")]);
|
||||
let entries = bar.help_entries(Target::Linux, &LayoutOptions::new("Sample"));
|
||||
let entry = entries.iter().find(|entry| *entry.command() == CommandRef::new("file.new")).expect("the command is listed");
|
||||
assert_eq!(entry.english().map(|label| label.as_str()), Some("New"));
|
||||
}
|
||||
|
||||
/// A host whose interface language is Turkish, with an empty catalog.
|
||||
pub(crate) fn turkish() -> Arc<Host> {
|
||||
let (i18n, _) = craft_i18n::I18n::from_owned([("tr".to_owned(), String::new(), String::new())], &["tr"]);
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title
|
||||
//! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". In a `Stack`
|
||||
//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_host::target::{Os, WindowChrome};
|
||||
use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items};
|
||||
use craft_ui::contract::{Role, Show as _, ShowContainer as _, Tracked};
|
||||
use craft_ui::display::Picture;
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::WindowKey;
|
||||
use craft_ui::shell::{AppShell, Caption, CaptionFamily, Captions, Frame, Title, TitleBar};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::vec2;
|
||||
|
||||
const MENUS: [&str; 10] = ["File", "Edit", "Image", "Layer", "Type", "Select", "Filter", "View", "Window", "Help"];
|
||||
const PREFERRED: [(&str, char); 10] = [
|
||||
("File", 'F'),
|
||||
("Edit", 'E'),
|
||||
("Image", 'I'),
|
||||
("Layer", 'L'),
|
||||
("Type", 'Y'),
|
||||
("Select", 'S'),
|
||||
("Filter", 'T'),
|
||||
("View", 'V'),
|
||||
("Window", 'W'),
|
||||
("Help", 'H'),
|
||||
];
|
||||
const DOCUMENT: &str = "Untitled-1.psd";
|
||||
|
||||
fn model() -> Tracked<MenuBar> {
|
||||
let rows: Vec<Row> = MENUS.iter().map(|menu| Row::new(&[menu], CommandRef::new(format!("{}.first", menu.to_lowercase())), "First")).collect();
|
||||
Tracked::new(from_items(&MENUS, &rows))
|
||||
}
|
||||
|
||||
fn brand() -> egui::ColorImage {
|
||||
egui::ColorImage::filled([128, 128], egui::Color32::RED)
|
||||
}
|
||||
|
||||
/// An app window `width` points wide at `pixels_per_point` whose frame the app draws (Windows), with the title bar as
|
||||
/// PhotoCraft lays it out: a brand picture, the menu bar, then the document title, and the captions at the end.
|
||||
fn window(width: f32, pixels_per_point: f32) -> Fixture {
|
||||
let bar = Rc::new(model());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let bar = Rc::clone(&bar);
|
||||
AppShell::new(WindowKey::main())
|
||||
.title_bar(move |ui, _, _: &mut ()| {
|
||||
let bar = Rc::clone(&bar);
|
||||
let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] };
|
||||
TitleBar::new().frame(Frame::Integrated(Captions { family: CaptionFamily::Windows, layout })).show_titled(
|
||||
ui,
|
||||
Title::new(DOCUMENT),
|
||||
move |ui, _| {
|
||||
Picture::new("", 7, &brand).show(ui);
|
||||
MenuBarUi::new(&bar).target(Target::Windows).mnemonics(&PREFERRED).help_search(true).show(ui);
|
||||
},
|
||||
|_, _| {},
|
||||
);
|
||||
})
|
||||
.body(|ui, _, _| {
|
||||
ui.label("Document");
|
||||
})
|
||||
.show(ui, &mut ());
|
||||
});
|
||||
fixture.os(Os::Windows).chrome(WindowChrome::Integrated).pixels_per_point(pixels_per_point).room(vec2(width, 600.0)).settle();
|
||||
fixture
|
||||
}
|
||||
|
||||
/// The bar's title nodes by name.
|
||||
fn titles(fixture: &Fixture) -> Vec<String> {
|
||||
let tree = fixture.tree();
|
||||
fixture.by_role(Role::MENU_ITEM).iter().filter_map(|title| tree.name_of(title.node).map(str::to_owned)).collect()
|
||||
}
|
||||
|
||||
/// Where `text` was painted, and whether it was cut.
|
||||
fn painted(fixture: &Fixture, text: &str) -> Option<(egui::Rect, bool)> {
|
||||
fixture.texts().iter().find(|run| run.text == text).map(|run| (run.rect, run.elided))
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn every_menu_title_and_the_document_title_show_in_a_wide_title_bar() {
|
||||
for pixels_per_point in [1.0, 1.25] {
|
||||
for width in [960.0, 1280.0, 1520.0] {
|
||||
let fixture = window(width, pixels_per_point);
|
||||
let at = format!("{width} pt at {pixels_per_point}x");
|
||||
assert_eq!(titles(&fixture), MENUS, "{at} shows every title and no \"…\"");
|
||||
let (help, _) = painted(&fixture, "Help").unwrap_or_else(|| panic!("{at}: Help is painted"));
|
||||
let (title, cut) = painted(&fixture, DOCUMENT).unwrap_or_else(|| panic!("{at}: the document title is painted"));
|
||||
assert!(title.left() > help.right(), "{at}: the document title {title:?} lies after Help {help:?}");
|
||||
assert!(!cut, "{at}: the document title is whole");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_narrow_title_bar_folds_the_last_menus_into_more() {
|
||||
for pixels_per_point in [1.0, 1.25] {
|
||||
let mut fixture = window(400.0, pixels_per_point);
|
||||
let shown = titles(&fixture);
|
||||
assert_eq!(shown.last().map(String::as_str), Some("…"), "{pixels_per_point}x: {shown:?}");
|
||||
assert!(!shown.iter().any(|title| title == "Help"), "{pixels_per_point}x: Help is not a title: {shown:?}");
|
||||
let more = fixture.by_label("…").expect("the \"…\" title");
|
||||
fixture.click(&more).settle();
|
||||
assert!(fixture.by_label("Help").is_some(), "{pixels_per_point}x: Help is a row of the \"…\" menu");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_bar_in_a_stack_narrower_than_its_titles_folds_them_and_draws_nothing_past_its_edge() {
|
||||
let bar = Rc::new(model());
|
||||
let stack = Rc::new(Cell::new(egui::Rect::NOTHING));
|
||||
let seen = Rc::clone(&stack);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let bar = Rc::clone(&bar);
|
||||
let shown = Stack::new().show(ui, |ui, _| {
|
||||
MenuBarUi::new(&bar).target(Target::Windows).show(ui);
|
||||
});
|
||||
seen.set(shown.output.rect);
|
||||
});
|
||||
fixture.os(Os::Windows).room(vec2(240.0, 600.0)).settle();
|
||||
let shown = titles(&fixture);
|
||||
assert_eq!(shown.last().map(String::as_str), Some("…"), "{shown:?}");
|
||||
assert!(!shown.iter().any(|title| title == "Help"), "Help is not a title: {shown:?}");
|
||||
let edge = stack.get().right();
|
||||
for run in fixture.texts().iter().filter(|run| MENUS.contains(&run.text.as_str()) || run.text == "…") {
|
||||
assert!(run.rect.right() <= edge + 0.5, "{:?} at {:?} reaches past the stack's edge {edge}", run.text, run.rect);
|
||||
}
|
||||
let more = fixture.by_label("…").expect("the \"…\" title");
|
||||
fixture.click(&more).settle();
|
||||
assert!(fixture.by_label("Help").is_some(), "Help is a row of the \"…\" menu");
|
||||
}
|
||||
@@ -445,7 +445,7 @@ impl Rows<'_> {
|
||||
.id_salt((path.to_vec(), "add"))
|
||||
.show(ui);
|
||||
if clicked(&plus) {
|
||||
let group = pointer::frame(ui.ctx()).mods.alt && depth < MAX_DEPTH;
|
||||
let group = pointer::mods(ui.ctx()).alt && depth < MAX_DEPTH;
|
||||
let item = if group { ConditionItem::Group(self.new_group()) } else { ConditionItem::Rule(self.new_rule()) };
|
||||
*insert = Some((at + 1, item));
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ mod picker;
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
pub use picker::{NamedStyleRow, StylePreview, style_rows};
|
||||
pub use picker::{NamedStyleRow, StylePreview, style_source};
|
||||
|
||||
craft_ui::words! {
|
||||
/// The panels' words, English by default.
|
||||
@@ -407,9 +407,9 @@ impl<'a> TextStylesPanel<'a> {
|
||||
});
|
||||
let (events, second) = (shown_rows.events, shown_rows.activation_clicks >= 2);
|
||||
|
||||
let pointer = craft_ui::runtime::pointer::frame(ui.ctx());
|
||||
let alt = pointer.mods.alt;
|
||||
let plain = !pointer.mods.shift && !pointer.mods.cmd;
|
||||
let mods = craft_ui::runtime::pointer::mods(ui.ctx());
|
||||
let alt = mods.alt;
|
||||
let plain = !mods.shift && !mods.cmd;
|
||||
for event in events {
|
||||
match event {
|
||||
CollectionEvent::Activate(id) if second && (id != 0 || paragraph) => action.set(Some(TextStyleAction::Options(id))),
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
//! The rows of the style picker: the document's named styles as the rows of a `PresetPicker`.
|
||||
//! The presets of the style picker: the document's named styles as the source of a `PresetPicker`.
|
||||
|
||||
use crate::styles::{group_by_folder, style_leaf};
|
||||
use craft_behavior::IconId;
|
||||
use craft_theme::Rgba;
|
||||
use craft_ui::patterns::presets::{PresetKey, PresetRow};
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetKey, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::style::TypeRole;
|
||||
|
||||
/// What a style row shows before its name.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub enum StylePreview {
|
||||
/// A swatch (colour and fill styles).
|
||||
@@ -25,7 +26,7 @@ pub enum StylePreview {
|
||||
}
|
||||
|
||||
/// One style in the picker; its folder is the name's ([`crate::styles::style_folder`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct NamedStyleRow {
|
||||
/// The style's id.
|
||||
@@ -59,11 +60,15 @@ impl NamedStyleRow {
|
||||
}
|
||||
}
|
||||
|
||||
/// The picker's rows: styles with no folder first, then each folder as a group row over its styles, in order of
|
||||
/// The picker's presets: styles with no folder first, then each folder as a group row over its styles, in order of
|
||||
/// first appearance. A style's key is `PresetKey::Item(id)`.
|
||||
pub fn style_rows(styles: &[NamedStyleRow]) -> Vec<PresetRow<PresetKey<u64>>> {
|
||||
pub fn style_source(styles: &[NamedStyleRow]) -> PresetSource<'_, PresetKey<u64>> {
|
||||
PresetSource::new(styles, PresetFns::new(style_rows))
|
||||
}
|
||||
|
||||
fn style_rows(styles: &&[NamedStyleRow], _: &Env) -> Vec<PresetRow<PresetKey<u64>>> {
|
||||
let mut rows = Vec::new();
|
||||
for (folder, group) in group_by_folder(styles, |style: &NamedStyleRow| style.name.as_str()) {
|
||||
for (folder, group) in group_by_folder(*styles, |style: &NamedStyleRow| style.name.as_str()) {
|
||||
let depth = usize::from(!folder.is_empty());
|
||||
if depth == 1 {
|
||||
rows.push(PresetRow::group(PresetKey::group([folder.clone()]), folder.clone(), 0).count(group.len()));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Stories of `TextStylesPanel` and of the style picker built on `PresetPicker`.
|
||||
|
||||
use super::{NamedStyleRow, StylePreview, TextStyleKind, TextStyleRow, TextStylesPanel, style_rows};
|
||||
use super::{NamedStyleRow, StylePreview, TextStyleKind, TextStyleRow, TextStylesPanel, style_source};
|
||||
use craft_behavior::{IconId, Mixed, Selection};
|
||||
use craft_ui::patterns::presets::{PresetKey, PresetPicker, PresetState};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
@@ -54,7 +54,8 @@ fn picker_styles() -> Vec<NamedStyleRow> {
|
||||
|
||||
#[story(TextStylesPanel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn style_picker_over_style_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let rows = style_rows(&picker_styles());
|
||||
let styles = picker_styles();
|
||||
let rows = style_source(&styles);
|
||||
let ((applied, state), picker_at) = data.value_at("picker", (Mixed::Same(Some(PresetKey::Item(2_u64))), PresetState::<PresetKey<u64>>::new()));
|
||||
PresetPicker::new("Style", picker_at.bind_mixed(applied), &rows, picker_at.bind(state)).show(ui).into()
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ use craft_theme::{ContrastChoice, ModeChoice, MotionChoice, Size, TextSize, Them
|
||||
use craft_ui::choice::RadioGroup;
|
||||
use craft_ui::contract::{Bind, Entry, Held, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::menu::Menu;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
@@ -110,7 +110,7 @@ impl<'a> AppearancePage<'a> {
|
||||
let mut held = Held::new(draft);
|
||||
let mut toggled = None;
|
||||
let mut changed = false;
|
||||
let mut shown = FieldGroup::new(words.appearance.clone()).show(ui, |ui, cx| {
|
||||
let mut shown = Stack::new().label(words.appearance.clone()).show(ui, |ui, cx| {
|
||||
let before = held.read(cx).unwrap_or_default();
|
||||
let mut now = before.clone();
|
||||
let shown = now.applied_to(&suite.shown);
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::{SelectionChange, SuiteClient};
|
||||
use craft_theme::{ThemeId, builtins};
|
||||
use craft_ui::choice::RadioGroup;
|
||||
use craft_ui::contract::{Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::form::FieldGroup;
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
@@ -18,13 +19,18 @@ fn favorites() -> Vec<ThemeId> {
|
||||
fn appearance_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let client = SuiteClient::memory().view();
|
||||
let favorites = favorites();
|
||||
AppearancePage::new(&client, data.bind("draft", SelectionChange::default())).favorites(&favorites).show(ui).into()
|
||||
let mut draft = data.bind("draft", SelectionChange::default());
|
||||
FieldGroup::new("Appearance").show(ui, |ui, _| AppearancePage::new(&client, draft.reborrowed()).favorites(&favorites).show(ui)).output.into()
|
||||
}
|
||||
|
||||
#[story(AppearancePage<'static>, covers = [], drive = Drive::Never)]
|
||||
fn appearance_page_without_text_size(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let client = SuiteClient::memory().view();
|
||||
AppearancePage::new(&client, data.bind("plain", SelectionChange::default())).text_size(false).system_dark(true).show(ui).into()
|
||||
let mut draft = data.bind("plain", SelectionChange::default());
|
||||
FieldGroup::new("Appearance")
|
||||
.show(ui, |ui, _| AppearancePage::new(&client, draft.reborrowed()).text_size(false).system_dark(true).show(ui))
|
||||
.output
|
||||
.into()
|
||||
}
|
||||
|
||||
/// One theme's chips in a group: plain, chosen, favourite, and both. A click on a star toggles the chip's favourite.
|
||||
|
||||
@@ -10,7 +10,13 @@ description = "Tracked<T>: app data whose every write moves a revision, so a rea
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
# No dependencies, so engine crates can hold and move a revision without the UI.
|
||||
# No dependencies but an optional serde, so engine crates can hold and move a revision without the UI.
|
||||
[dependencies]
|
||||
serde = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
# `Serialize` and `Deserialize` for `Tracked<T>`: saved as its value, loaded as a new source.
|
||||
serde = ["dep:serde"]
|
||||
|
||||
[dev-dependencies]
|
||||
# `#[derive(PlainData)]` in the doc tests.
|
||||
|
||||
@@ -326,13 +326,38 @@ impl<T: PlainData + Clone> Clone for Tracked<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two values are equal when what they hold is: the revision says which writes a value saw, not what it is.
|
||||
/// `value`, as a new source at count 0 ([`Tracked::new`]).
|
||||
impl<T: PlainData> From<T> for Tracked<T> {
|
||||
fn from(value: T) -> Tracked<T> {
|
||||
Tracked::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Equal values compare equal, whatever their revisions.
|
||||
impl<T: PlainData + PartialEq> PartialEq for Tracked<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
fn eq(&self, other: &Tracked<T>) -> bool {
|
||||
self.value == other.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PlainData + Eq> Eq for Tracked<T> {}
|
||||
|
||||
/// Saved as its value.
|
||||
#[cfg(feature = "serde")]
|
||||
impl<T: PlainData + serde::Serialize> serde::Serialize for Tracked<T> {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
self.value.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Loaded as a new source.
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de, T: PlainData + serde::Deserialize<'de>> serde::Deserialize<'de> for Tracked<T> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Tracked<T>, D::Error> {
|
||||
T::deserialize(deserializer).map(Tracked::new)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PlainData> Deref for Tracked<T> {
|
||||
type Target = T;
|
||||
|
||||
|
||||
@@ -66,6 +66,22 @@ pub enum Extent {
|
||||
Tiled,
|
||||
}
|
||||
|
||||
/// `outer` without `inner`: the bands above, below, left and right of it, empty ones left out.
|
||||
fn ring(outer: PixelRect, inner: PixelRect) -> impl Iterator<Item = PixelRect> {
|
||||
let i = inner.intersect(&outer);
|
||||
let bands = if i.is_empty() {
|
||||
[outer, PixelRect::default(), PixelRect::default(), PixelRect::default()]
|
||||
} else {
|
||||
[
|
||||
PixelRect::new(outer.x0, outer.y0, outer.x1, i.y0),
|
||||
PixelRect::new(outer.x0, i.y1, outer.x1, outer.y1),
|
||||
PixelRect::new(outer.x0, i.y0, i.x0, i.y1),
|
||||
PixelRect::new(i.x1, i.y0, outer.x1, i.y1),
|
||||
]
|
||||
};
|
||||
bands.into_iter().filter(|band| !band.is_empty())
|
||||
}
|
||||
|
||||
/// Most copies a tiled display draws along each axis, the document included. A tiny document zoomed far out would
|
||||
/// otherwise need thousands of copies per pass; past this the pattern stops, and the run is centred on the view.
|
||||
const MOST_COPIES: i32 = 31;
|
||||
@@ -262,6 +278,10 @@ pub struct RasterDisplay<'a> {
|
||||
/// How far the picture reaches past the document's edge.
|
||||
#[prop]
|
||||
extent: Extent,
|
||||
/// What the region of [`Extent::Region`] shows past the document, under the picture: the checkerboard when none,
|
||||
/// else this colour (Crop's preview of the area a crop adds to a Background, which takes the background colour).
|
||||
#[prop]
|
||||
region_fill: Option<Color32>,
|
||||
/// The display paints in the canvas's picture slot, under every canvas control of the body, when the canvas
|
||||
/// space carries a slot; otherwise it paints in place. A display under the controls fills its canvas, so the
|
||||
/// canvas content rect, the slot's clip, is its clip. It declares no faded look of its own (`DisabledLook::States`):
|
||||
@@ -331,6 +351,7 @@ impl<'a> RasterDisplay<'a> {
|
||||
checkerboard: None,
|
||||
outlined: false,
|
||||
extent: Extent::Document,
|
||||
region_fill: None,
|
||||
under_controls: false,
|
||||
read: PixelRect::default(),
|
||||
shown: None,
|
||||
@@ -540,6 +561,14 @@ impl Component for RasterDisplay<'_> {
|
||||
painter.painter.add(checker.shape(painter.painter.ctx(), &ui.env.tokens, CheckerArea::Quad(area), origin));
|
||||
}
|
||||
}
|
||||
// The region's colour past the document, over the checkerboard and under the picture. Only a region reaches
|
||||
// past the document: a mapped or tiled picture's bounds are the document.
|
||||
if let Some(fill) = self.region_fill {
|
||||
for band in ring(shown.bounds, PixelRect::of_size(shown.size)) {
|
||||
let band = Rect64::new(f64::from(band.x0), f64::from(band.y0), f64::from(band.x1), f64::from(band.y1));
|
||||
painter.painter.add(Shape::convex_polygon(shown.view.quad(band).to_vec(), fill, egui::Stroke::NONE));
|
||||
}
|
||||
}
|
||||
match (&mut self.picture, &shown.textures, &self.mapping) {
|
||||
(Picture::Source(_), Some(textures), Some(mapping)) => {
|
||||
let (texture, factor) = textures.base;
|
||||
|
||||
@@ -479,7 +479,7 @@ impl Component for Guides<'_> {
|
||||
/// `run_pointer` reads only declared parts, so this is the one gate of the pointer.
|
||||
fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let held = cx.press_slot::<HeldGuide>().is_some() || cx.gesture_running();
|
||||
let takes = self.interactive || (self.moves_with_command && (crate::runtime::pointer::frame(cx.ui.ctx()).mods.cmd || held));
|
||||
let takes = self.interactive || (self.moves_with_command && (crate::runtime::pointer::mods(cx.ui.ctx()).cmd || held));
|
||||
let (Some(space), Some(guides), true) = (canvas_space(&cx.env), cx.value(), takes) else { return };
|
||||
let mut any = false;
|
||||
for &at in &place::keyboard_order(guides) {
|
||||
@@ -526,10 +526,11 @@ impl Component for Guides<'_> {
|
||||
for guide in guides {
|
||||
let Some([a, b]) = place::segment(&space.view, guide.along, guide.position, guide.span, cx.rect) else { continue };
|
||||
let color = if self.selected == Some(guide.key) { style.selected.egui() } else { guide.color.map_or(style.line.egui(), data_color) };
|
||||
let look = RuleLook { color, width: RuleWidth::Points(style.width) };
|
||||
match guide.line {
|
||||
GuideLine::Solid => painter.painter.extend(Rule::shapes(&RuleLook { color, width: RuleWidth::Points(style.width) }, a, b, ppp)),
|
||||
GuideLine::Solid => painter.painter.extend(Rule::shapes(&look, a, b, ppp)),
|
||||
GuideLine::Dashed => painter.dashed(&[a, b], Dashes::new(style.dash, style.gap), StrokeWidth::Thin, color),
|
||||
GuideLine::Dots => painter.dashed(&[a, b], Dashes::new(style.width, style.gap), StrokeWidth::Thin, color),
|
||||
GuideLine::Dots => painter.painter.extend(Rule::dotted(&look, a, b, style.gap, ppp)),
|
||||
}
|
||||
if focused == Some(guide.key.get()) && (b - a).length() > 0.0 {
|
||||
painter.painter.extend(FocusRing::shapes(&style.focus, FocusKind::Halo, &footprint(&space, a, b, style.width), ppp));
|
||||
|
||||
@@ -26,12 +26,15 @@ fn on_guides_canvas(ui: &mut Ui, mut control: impl FnMut(&mut Ui, Rect, Id) -> G
|
||||
on_canvas_with(ui, room, Canvas::new("Document").id(canvas).view(view), Some(document), |ui, at| control(ui, at, canvas))
|
||||
}
|
||||
|
||||
/// Every line a guide draws: solid, dotted and dashed, and a locked one.
|
||||
fn guides() -> Vec<Guide> {
|
||||
let mut dotted = Guide::new(GuideKey::new(2), Axis::X, 120.0);
|
||||
dotted.line = GuideLine::Dots;
|
||||
let mut dashed = Guide::new(GuideKey::new(3), Axis::X, 280.0);
|
||||
dashed.line = GuideLine::Dashed;
|
||||
let mut locked = Guide::new(GuideKey::new(4), Axis::Y, 480.0);
|
||||
locked.locked = true;
|
||||
vec![Guide::new(GuideKey::new(1), Axis::Y, 160.0), Guide::new(GuideKey::new(2), Axis::X, 120.0), dashed, locked]
|
||||
vec![Guide::new(GuideKey::new(1), Axis::Y, 160.0), dotted, dashed, locked]
|
||||
}
|
||||
|
||||
/// Drags the first guide across itself by twice the drag threshold.
|
||||
|
||||
@@ -420,6 +420,72 @@ fn a_region_past_the_document_draws_out_to_the_region() {
|
||||
assert!(document.reads.borrow().contains(&(moved, 1)), "a moved region is read: {:?}", document.reads.borrow());
|
||||
}
|
||||
|
||||
/// One frame of a display of `document` reaching out to `region`, with `fill` past the document: its shapes and the
|
||||
/// view.
|
||||
fn region_fill_shapes(document: &Rc<Document>, extent: Extent, fill: Option<Color32>, painted: bool) -> (Vec<Shape>, CanvasView) {
|
||||
let center = Point::new(70.0, 45.0);
|
||||
let view = CanvasView::new(Rect::from_min_size(Pos2::ZERO, CANVAS), center, 2.0);
|
||||
let document = Rc::clone(document);
|
||||
let callback: Arc<dyn std::any::Any + Send + Sync> = Arc::new(());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
Canvas::new("Document").view(view).show(ui, |ui, body| {
|
||||
let display = if painted {
|
||||
let callback = Arc::clone(&callback);
|
||||
let paint = AppPaint::new(move |painter, view: CanvasView| {
|
||||
painter.painter.add(Shape::Callback(PaintCallback { rect: view.rect, callback: Arc::clone(&callback) }));
|
||||
});
|
||||
RasterDisplay::painted("Picture", document.size, paint)
|
||||
} else {
|
||||
RasterDisplay::new("Picture", &*document)
|
||||
};
|
||||
let display = display.checkerboard(Checker::new()).extent(extent);
|
||||
let display = match fill {
|
||||
Some(fill) => display.region_fill(fill),
|
||||
None => display,
|
||||
};
|
||||
display.show_at(ui, body.rect);
|
||||
});
|
||||
});
|
||||
fixture.room(CANVAS);
|
||||
fixture.settle();
|
||||
(fixture.frame_shapes(), view)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_region_fill_shows_past_the_document_under_the_picture() {
|
||||
// Crop's preview of a crop that grows a Background: the area past the canvas takes the background colour.
|
||||
let document = Document::new(100, 70);
|
||||
let region = PixelRect::new(-60, -30, 200, 120);
|
||||
let red = Color32::from_rgb(255, 0, 0);
|
||||
let filled = |shape: &Shape| matches!(shape, Shape::Path(path) if path.fill == red);
|
||||
for painted in [false, true] {
|
||||
let (shapes, view) = region_fill_shapes(&document, Extent::Region(region), Some(red), painted);
|
||||
let at = |x: f64, y: f64| view.to_screen(Point::new(x, y));
|
||||
// Left of, above, below and right of the document, and at a corner of the region: the fill.
|
||||
for (x, y) in [(-30.0, 10.0), (50.0, -10.0), (50.0, 100.0), (150.0, 10.0), (-55.0, 115.0)] {
|
||||
assert_eq!(colour_at(&shapes, at(x, y)), [255.0, 0.0, 0.0, 255.0], "painted {painted}: ({x}, {y}) past the document is filled");
|
||||
}
|
||||
assert_ne!(colour_at(&shapes, at(50.0, 35.0)), [255.0, 0.0, 0.0, 255.0], "painted {painted}: the document itself is not filled");
|
||||
assert_ne!(colour_at(&shapes, at(-70.0, 10.0)), [255.0, 0.0, 0.0, 255.0], "painted {painted}: nothing past the region is filled");
|
||||
// The fill lies over the checkerboard and under the picture, which shows layers past the canvas over it.
|
||||
let first_fill = shapes.iter().position(filled).expect("a fill");
|
||||
let last_fill = shapes.iter().rposition(filled).expect("a fill");
|
||||
let checker = shapes.iter().position(|shape| matches!(shape, Shape::Mesh(mesh) if mesh.texture_id != TextureId::default()));
|
||||
let picture = shapes
|
||||
.iter()
|
||||
.rposition(|shape| matches!(shape, Shape::Callback(_)) || matches!(shape, Shape::Mesh(mesh) if mesh.texture_id != TextureId::default()));
|
||||
assert!(checker.is_some_and(|c| c < first_fill), "painted {painted}: over the checkerboard");
|
||||
assert!(picture.is_some_and(|p| last_fill < p), "painted {painted}: under the picture");
|
||||
|
||||
// No fill: the checkerboard alone, as before.
|
||||
let (plain, _) = region_fill_shapes(&document, Extent::Region(region), None, painted);
|
||||
assert!(!plain.iter().any(filled), "painted {painted}: no fill without a colour");
|
||||
// A fill with nothing past the document draws nothing.
|
||||
let (document_only, _) = region_fill_shapes(&document, Extent::Document, Some(red), painted);
|
||||
assert!(!document_only.iter().any(filled), "painted {painted}: no region, no fill");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_picture_whose_area_is_off_the_document_has_its_checkerboard_and_edge_there() {
|
||||
// A 100 x 70 document; its picture turned a quarter about the document's centre (70 x 100), then moved past the
|
||||
|
||||
@@ -295,7 +295,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
self.fixed_height = self.fixed_height(props, at);
|
||||
self.passes = self.passes_width(props, &env, at);
|
||||
self.held = self.held(props, &env);
|
||||
self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(_)));
|
||||
self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..)));
|
||||
self.in_column = label::in_column(ui);
|
||||
self.given.1 |= self.over_room(props, &env, at, ui.ctx(), id);
|
||||
let measured = self.measured_body.unwrap_or(Vec2::ZERO);
|
||||
@@ -416,10 +416,15 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
layout_memory::measured(ctx, sub(id, "first")).map(|found| found.took.y)
|
||||
}
|
||||
|
||||
/// A container with no header whose body is an unwrapped row reports that row's line as its first line.
|
||||
/// A container with no header whose body is an unwrapped row reports that row's line as its first line, and one
|
||||
/// labelled above its body the line of its body's first control: it sits on a row's line by that control, as a
|
||||
/// control labelled above does.
|
||||
fn first_is_row_line(&self, comp: &C) -> bool {
|
||||
let props = comp.props(Internal::new());
|
||||
props.header.is_none() && super::size::unwrapped_row(props)
|
||||
let above = props.label.as_ref().is_some_and(|side| {
|
||||
matches!(side.layout, label::FieldLayout::Above | label::FieldLayout::Caption(_)) && side.kind != label::LabelKind::Hidden
|
||||
});
|
||||
props.header.is_none() && (above || super::size::unwrapped_row(props))
|
||||
}
|
||||
|
||||
fn member(&self, comp: &C) -> bool {
|
||||
@@ -1827,9 +1832,9 @@ impl BodyHooks<'_> {
|
||||
self.fixed_height = self.fixed_height(&props, at.at);
|
||||
self.passes = self.passes_width(&props, at.env, at.at);
|
||||
self.held = self.held(&props, at.env);
|
||||
self.across = self.held && matches!(at.env.column, Some(ColumnSweep::Column(_)));
|
||||
self.across = self.held && matches!(at.env.column, Some(ColumnSweep::Column(..)));
|
||||
// A held container across its column measures at the column's width.
|
||||
if let Some(ColumnSweep::Column(width)) = at.env.column.filter(|_| self.across && at.width.is_none()) {
|
||||
if let Some(ColumnSweep::Column(_, width)) = at.env.column.filter(|_| self.across && at.width.is_none()) {
|
||||
self.room.x = width;
|
||||
}
|
||||
self.in_column = label::in_column(at.ui);
|
||||
|
||||
@@ -78,11 +78,11 @@ impl<C: Component> MeasureCx<'_, C> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The width a picture sizes at (a plot, a wheel, a well): it takes the room it is offered, down to `least` and up
|
||||
/// to `most`. At its least, where the width is unbounded, and in a measuring run of a column that sizes its width
|
||||
/// from its content (which offers no room), it is `least`: a picture needs no width of its own, so it never sets
|
||||
/// that column's width, and the real run shows it across the width the column settles on. A band picture keeps a
|
||||
/// height of its own; a square one is as tall as this.
|
||||
/// The width a band picture sizes at (a plot, a strip), one whose height is its own whatever its width: it takes
|
||||
/// the room it is offered, down to `least` and up to `most`. At its least, where the width is unbounded, and in a
|
||||
/// measuring run of a column that sizes its width from its content (which offers no room), it is `least`: a
|
||||
/// picture needs no width of its own, so it never sets that column's width, and the real run shows it across the
|
||||
/// width the column settles on.
|
||||
pub fn picture_width(&self, least: f32, most: f32) -> f32 {
|
||||
match self.room.filter(|_| self.proposal != Proposal::Min) {
|
||||
Some(room) => room.clamp(least, most.max(least)),
|
||||
@@ -90,6 +90,23 @@ impl<C: Component> MeasureCx<'_, C> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The size of a picture whose height follows from its width (a square graph, a wheel, an image at its aspect):
|
||||
/// [`picture_width`](Self::picture_width)'s width, and `height` of it. Where a content column's measuring run
|
||||
/// offers it no room, it is a held child of the column (`layout::HeldKind::Picture`): when the column settles
|
||||
/// wider than the picture, the column sweeps again and offers it that width, so the picture is measured as tall
|
||||
/// as it shows.
|
||||
pub fn picture_size(&self, least: f32, most: f32, height: impl FnOnce(f32) -> f32) -> Vec2 {
|
||||
// The width it reports is its placed width, which the place step gives (`run::place_root`).
|
||||
if self.room.is_none()
|
||||
&& self.proposal != Proposal::Min
|
||||
&& let Some(column) = self.env.column_first_sweep()
|
||||
{
|
||||
crate::layout::report_held(self.ui.ctx(), column, self.id, crate::layout::HeldKind::Picture, f32::INFINITY);
|
||||
}
|
||||
let width = self.picture_width(least, most);
|
||||
Vec2::new(width, height(width))
|
||||
}
|
||||
|
||||
/// The label as given.
|
||||
pub fn label(&self) -> Label {
|
||||
self.resolved.label_value.clone()
|
||||
@@ -131,7 +148,7 @@ impl<C: Component> MeasureCx<'_, C> {
|
||||
/// editor draws past its last letter, so the caret stays inside the control and the text never scrolls.
|
||||
pub fn field_text(&self, run: &TextRun<'_>) -> Vec2 {
|
||||
let text = self.layout(run).size();
|
||||
Vec2::new(text.x + self.ui.visuals().text_cursor.stroke.width, text.y)
|
||||
Vec2::new(text.x + crate::runtime::egui::style::caret_width(self.ui.ctx()), text.y)
|
||||
}
|
||||
|
||||
/// Lays document `text` out `text.wrap` wide, as `ContentPainterCx::layout` will paint it: the galley a content
|
||||
|
||||
@@ -10,19 +10,19 @@ const NO_LABEL: Label = Label::Empty;
|
||||
|
||||
/// A row of entries: an item that reports its value when picked, a heading over a group of items, or a separator
|
||||
/// between groups of items.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)]
|
||||
pub struct Entry<T> {
|
||||
row: Row<T>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)]
|
||||
enum Row<T> {
|
||||
Item(Item<T>),
|
||||
Heading(Label),
|
||||
Separator,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)]
|
||||
struct Item<T> {
|
||||
value: T,
|
||||
label: Label,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Requests to a collection's item step from outside it, taken at the collection's next pass.
|
||||
//! Requests to a collection's item step from outside it, taken at the collection's next pass. Each request moves the
|
||||
//! `Requests` input and each take reads it, so a pending request runs the memoized view that takes it.
|
||||
|
||||
use crate::runtime::egui::memory as store;
|
||||
use crate::runtime::inputs::{self, Input};
|
||||
use egui::{Context, Id};
|
||||
|
||||
/// The rename requests not yet taken: the collection and the key to rename.
|
||||
@@ -24,11 +26,13 @@ pub fn request_rename<K: Clone + Send + Sync + 'static>(ctx: &Context, collectio
|
||||
requests.0.retain(|(id, _)| *id != collection);
|
||||
requests.0.push((collection, key.clone()));
|
||||
});
|
||||
inputs::bump(ctx, Input::Requests);
|
||||
crate::runtime::egui::repaint::request_of(ctx, crate::runtime::egui::pass::current_viewport(ctx));
|
||||
}
|
||||
|
||||
/// The rename request addressed to `collection`, once.
|
||||
pub(super) fn take_rename<K: Send + Sync + 'static>(ctx: &Context, collection: Id) -> Option<K> {
|
||||
crate::runtime::replay::note_input(ctx, Input::Requests);
|
||||
store::Service::<RenameRequests<K>>::run(ctx, |requests| {
|
||||
let at = requests.0.iter().position(|(id, _)| *id == collection)?;
|
||||
Some(requests.0.remove(at).1)
|
||||
|
||||
@@ -110,55 +110,124 @@ impl LeafPlaced {
|
||||
}
|
||||
}
|
||||
|
||||
/// The label step for one leaf child: measures the child's narrowest width, runs the step in `row` with the
|
||||
/// `trailing` content inside the label and returns the rect left for the child. The caller shows the child there and
|
||||
/// then calls `LeafPlaced::finish`.
|
||||
pub(crate) fn leaf<C: Show>(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option<Trailing<'_>>) -> LeafPlaced {
|
||||
let scope = sub(at.id, "field");
|
||||
let enabled = at.under.enabled;
|
||||
/// The label step for one leaf child, decided: measures the child's narrowest width and decides where the label, with
|
||||
/// content of `trailing` size inside it, and the child sit in `at.row`. Nothing shows and no room is taken; `show_leaf`
|
||||
/// then shows the label where the row's place in flow puts it, and the caller shows the child at the control's rect
|
||||
/// and calls `LeafPlaced::finish`.
|
||||
pub(crate) fn decide_leaf<C: Show>(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Vec2) -> Decided {
|
||||
// Read before the child measures: nothing it does there may count as a child placed in flow.
|
||||
let in_column = in_column(ui);
|
||||
let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x;
|
||||
let input = LabelIn {
|
||||
scope,
|
||||
let facts = LeafFacts { control_min, in_column, claims: C::LABELLED_AFTER };
|
||||
decide_step(ui, env, &leaf_input(env, at, at.row, facts, trailing))
|
||||
}
|
||||
|
||||
/// Shows the label of a leaf child's step `decided` for `at`, moved down by `down`, with the `trailing` content inside
|
||||
/// it, and returns the rect left for the child.
|
||||
pub(crate) fn show_leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, decided: Decided, down: f32, trailing: Option<Trailing<'_>>) -> LeafPlaced {
|
||||
let size = trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size);
|
||||
let input = leaf_input(env, at, at.row.translate(Vec2::new(0.0, down)), decided.facts, size);
|
||||
let placed = show(ui, env, &input, decided.moved(down), trailing);
|
||||
LeafPlaced { control: placed.control, label: placed.label, scope: input.scope }
|
||||
}
|
||||
|
||||
/// What a label step reads of its control before it decides.
|
||||
#[derive(Clone, Copy)]
|
||||
struct LeafFacts {
|
||||
control_min: f32,
|
||||
in_column: bool,
|
||||
claims: bool,
|
||||
}
|
||||
|
||||
/// The step's input for the leaf child of `at` in `row`, with content of `trailing` size inside the label.
|
||||
fn leaf_input<'a>(env: &Env, at: &LeafLabel<'a>, row: Rect, facts: LeafFacts, trailing: Vec2) -> LabelIn<'a> {
|
||||
LabelIn {
|
||||
scope: sub(at.id, "field"),
|
||||
owner: at.owner,
|
||||
parent: at.parent,
|
||||
row: at.row,
|
||||
room: at.row.width(),
|
||||
row,
|
||||
room: row.width(),
|
||||
content_row: env.content.0,
|
||||
text: at.text,
|
||||
side: at.side,
|
||||
help: None,
|
||||
enabled,
|
||||
enabled: at.under.enabled,
|
||||
size: at.under.size,
|
||||
control_min,
|
||||
control_min: facts.control_min,
|
||||
leaf: true,
|
||||
in_column,
|
||||
claims: C::LABELLED_AFTER,
|
||||
in_column: facts.in_column,
|
||||
claims: facts.claims,
|
||||
status: false,
|
||||
trailing: trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size),
|
||||
};
|
||||
let placed = run(ui, env, &input, trailing);
|
||||
LeafPlaced { control: placed.control, label: placed.label, scope }
|
||||
trailing,
|
||||
}
|
||||
}
|
||||
|
||||
/// The label step for one leaf child in `at.row`, decided and shown where it was decided: returns the rect left for
|
||||
/// the child. The caller shows the child there and then calls `LeafPlaced::finish`.
|
||||
pub(crate) fn leaf<C: Show>(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option<Trailing<'_>>) -> LeafPlaced {
|
||||
let decided = decide_leaf(ui, env, at, child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size));
|
||||
show_leaf(ui, env, at, decided, 0.0, trailing)
|
||||
}
|
||||
|
||||
/// Runs the label step in `ui`: shows the label and the `trailing` content inside it (`input.trailing` is its size),
|
||||
/// opens the label scope and returns where the label and the control sit. The caller closes the scope with
|
||||
/// `scope::finish` after the control ran.
|
||||
pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option<Trailing<'_>>) -> Placed {
|
||||
let decided = decide_step(ui, env, input);
|
||||
show(ui, env, input, decided, trailing)
|
||||
}
|
||||
|
||||
/// The label step decided for a row, before anything shows: where the label and the control sit, and the label leaf
|
||||
/// measured in the child `Ui` it shows in.
|
||||
pub(crate) struct Decided {
|
||||
placed: Placed,
|
||||
/// `None` for a label that shows no leaf.
|
||||
leaf: Option<DecidedLeaf>,
|
||||
/// What the step read of its control.
|
||||
facts: LeafFacts,
|
||||
}
|
||||
|
||||
struct DecidedLeaf {
|
||||
leaf: LabelLeaf,
|
||||
kids: Ui,
|
||||
installed: crate::runtime::env::Installed,
|
||||
reset: Option<scope::ResetFact>,
|
||||
}
|
||||
|
||||
impl Decided {
|
||||
/// The rect left for the control.
|
||||
pub(crate) fn control(&self) -> Rect {
|
||||
self.placed.control
|
||||
}
|
||||
|
||||
/// The label's rect; `Rect::NOTHING` for a hidden label.
|
||||
pub(crate) fn label(&self) -> Rect {
|
||||
self.placed.label
|
||||
}
|
||||
|
||||
/// The step moved down by `down`, as the row's place in flow moves it.
|
||||
fn moved(mut self, down: f32) -> Self {
|
||||
let by = Vec2::new(0.0, down);
|
||||
self.placed.label = self.placed.label.translate(by);
|
||||
self.placed.control = self.placed.control.translate(by);
|
||||
self.placed.trailing = self.placed.trailing.translate(by);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Decides the label step for `input`: measures the label in the child `Ui` it shows in and places it and the control
|
||||
/// in `input.row`. Nothing shows.
|
||||
fn decide_step(ui: &mut Ui, env: &Env, input: &LabelIn<'_>) -> Decided {
|
||||
let ctx = ui.ctx().clone();
|
||||
let rtl = env.direction.is_rtl();
|
||||
let tokens = &env.tokens;
|
||||
let (gap, slot_side) = (label_gap(env), tokens.size.handle.sm);
|
||||
let (gap, slot_side) = (label_gap(env), env.tokens.size.handle.sm);
|
||||
let reset = scope::last_reset(&ctx, input.scope);
|
||||
let flow = Flow::new(input.row, rtl);
|
||||
let label_id = sub(input.scope, "label");
|
||||
let content = input.trailing.x > 0.0;
|
||||
let facts = LeafFacts { control_min: input.control_min, in_column: input.in_column, claims: input.claims };
|
||||
if input.side.shows_no_leaf(content) {
|
||||
scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING)));
|
||||
let control = hidden_control(&ctx, input, flow, gap);
|
||||
scope::place_controls(&ctx, input.scope, control.top());
|
||||
return Placed { label: Rect::NOTHING, control, trailing: Rect::NOTHING, caption: 0.0 };
|
||||
return Decided { placed: Placed { label: Rect::NOTHING, control, trailing: Rect::NOTHING, caption: 0.0 }, leaf: None, facts };
|
||||
}
|
||||
let slot = if reset.is_some() && input.side.reset_dot { slot_side } else { 0.0 };
|
||||
let mut leaf = LabelLeaf::new(input.side.kind.shown(input.text).clone(), slot);
|
||||
@@ -192,24 +261,41 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option<
|
||||
Some(parent) => access::with_parent(builder, parent),
|
||||
None => builder,
|
||||
};
|
||||
let mut kids = alloc::child(ui, builder);
|
||||
let kids = alloc::child(ui, builder);
|
||||
let kid_env = crate::contract::cx::child_env(env, &Under::new(input.enabled, input.size));
|
||||
let installed = Env::install_for(&kids, kid_env);
|
||||
let glyph = leaf.glyph.is_some();
|
||||
let mut placed = decide(&ctx, env, input, &kids, &mut leaf, glyph, flow);
|
||||
// The label without its reset dot, which keeps its own press; the content sits at its end, on the first line.
|
||||
let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot);
|
||||
if input.trailing.x > 0.0 {
|
||||
// The label without its reset dot, which keeps its own press; the content sits at its end, on the first line.
|
||||
let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot);
|
||||
let cell = unslotted.take_end(input.trailing.x).0;
|
||||
let middle = cell.top() + leaf.first_line.get() / 2.0;
|
||||
placed.trailing = Rect::from_min_size(egui::pos2(cell.min.x, middle - input.trailing.y / 2.0), input.trailing);
|
||||
}
|
||||
let label_id_for_scope = sub(input.scope, "label");
|
||||
Decided { placed, leaf: Some(DecidedLeaf { leaf, kids, installed, reset }), facts }
|
||||
}
|
||||
|
||||
/// Shows the label step `decided` for `input`: the label and the `trailing` content inside it, and opens the label
|
||||
/// scope. Returns where the label and the control sit.
|
||||
fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: Option<Trailing<'_>>) -> Placed {
|
||||
let ctx = ui.ctx().clone();
|
||||
let rtl = env.direction.is_rtl();
|
||||
let label_id = sub(input.scope, "label");
|
||||
let Decided { placed, leaf, .. } = decided;
|
||||
let Some(DecidedLeaf { leaf, mut kids, installed, reset }) = leaf else {
|
||||
scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING)));
|
||||
scope::place_controls(&ctx, input.scope, placed.control.top());
|
||||
return placed;
|
||||
};
|
||||
let slot = if reset.is_some() && input.side.reset_dot { env.tokens.size.handle.sm } else { 0.0 };
|
||||
// The label without its reset dot, which keeps its own press.
|
||||
let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot);
|
||||
// A label shows with the control it names: where a bar's view shows the two only in part, neither shows.
|
||||
if crate::contract::run::cut_by_bar_view(env, placed.label.union(placed.control)) {
|
||||
kids.set_clip_rect(Rect::NOTHING);
|
||||
}
|
||||
let shown = Props::id(leaf, label_id_for_scope).show_at(&mut kids, placed.label);
|
||||
let shown = Props::id(leaf, label_id).show_at(&mut kids, placed.label);
|
||||
Env::restore(&ctx, installed);
|
||||
if let Some(fact) = reset.filter(|_| shown.double_click || shown.dot_click) {
|
||||
keys::route_whole_reset(&ctx, fact.control);
|
||||
@@ -219,8 +305,7 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option<
|
||||
if let Some(trailing) = trailing {
|
||||
(trailing.show)(ui, placed.trailing);
|
||||
}
|
||||
let label =
|
||||
field_label(env, input, label_id_for_scope, placed.label).with_press(shown.press).with_hover(shown.hovered).activated(shown.activated);
|
||||
let label = field_label(env, input, label_id, placed.label).with_press(shown.press).with_hover(shown.hovered).activated(shown.activated);
|
||||
scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(label));
|
||||
scope::place_controls(&ctx, input.scope, placed.control.top());
|
||||
if input.claims {
|
||||
@@ -302,28 +387,36 @@ fn flow_leaf_row<C: Show>(
|
||||
region if in_cell => Rect::from_min_size(region.min, Vec2::new(flow.width(), region.height())),
|
||||
_ => flow,
|
||||
};
|
||||
// The child's own height: a stacked label pushes the control down, and the allocation below follows the placement.
|
||||
// The row spans the room's own edges: a room that scrolls along x is unbounded at its start edge, the left one
|
||||
// under RTL.
|
||||
// The label step decides where the label and the control sit at the flow's top, and the row then takes its place
|
||||
// in flow as any other child does: its control's line is the row's line, on a row's or bracket's line, centred in a
|
||||
// grid's cell or a horizontal layout. The row spans the room's own edges: a room that scrolls along x is unbounded
|
||||
// at its start edge, the left one under RTL.
|
||||
let row = Rect::from_min_max(avail.min, egui::pos2(avail.max.x, avail.min.y + ideal.y));
|
||||
let at = LeafLabel { id, owner, parent: None, row, text: &label, side: &side, under: &under };
|
||||
let placed = leaf(ui, &env, &at, &mut child, trailing);
|
||||
let decided = decide_leaf(ui, &env, &at, &mut child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size));
|
||||
// In a column that sizes from its content the row is the label plus the control, never the room around them.
|
||||
// A row of a horizontal flow is as wide as its label and control: the room it has there is unbounded.
|
||||
// So is a grid's cell: the room before it is the whole grid's, and a row spanning it measures its column as wide
|
||||
// as the grid, so the grid could never set two such cells beside each other (two columns of check boxes).
|
||||
let content = env.content.0 || ui.layout().is_horizontal() || in_cell;
|
||||
let control_width = if content { placed.control.width().min(ideal.x) } else { placed.control.width() };
|
||||
let control_width = if content { decided.control().width().min(ideal.x) } else { decided.control().width() };
|
||||
let rtl = env.direction.is_rtl();
|
||||
let cell = Rect::from_min_max(placed.control.min, egui::pos2(placed.control.max.x, placed.control.min.y + ideal.y));
|
||||
let control = Flow::new(cell, rtl).span(0.0, control_width);
|
||||
let span = |cell: Rect| Flow::new(Rect::from_min_size(cell.min, Vec2::new(cell.width(), ideal.y)), rtl).span(0.0, control_width);
|
||||
let (decided_control, decided_label) = (span(decided.control()), decided.label());
|
||||
let extent = if !content {
|
||||
avail.width()
|
||||
} else if rtl {
|
||||
avail.max.x - control.min.x.min(placed.label.min.x)
|
||||
avail.max.x - decided_control.min.x.min(decided_label.min.x)
|
||||
} else {
|
||||
control.max.x.max(placed.label.max.x) - avail.min.x
|
||||
decided_control.max.x.max(decided_label.max.x) - avail.min.x
|
||||
};
|
||||
// The child's own height: a stacked label pushes the control down, and a label taller than the control reaches
|
||||
// below it.
|
||||
let height = (decided_control.bottom().max(decided_label.bottom()) - row.top()).max(ideal.y);
|
||||
let first = decided_control.top() - row.top() + ideal.y / 2.0;
|
||||
let took = crate::layout::place_in_cell(ui, Vec2::new(extent, height), crate::layout::InFlow { fill: false, first: Some(first), line: true });
|
||||
let placed = show_leaf(ui, &env, &at, decided, took.top() - row.top(), trailing);
|
||||
let control = span(placed.control);
|
||||
// A control beside its label in a content-sized column reports how far it reaches past the label column, so
|
||||
// the column's container measures its rows at the widest label.
|
||||
if content && ui.is_sizing_pass() && side.layout == FieldLayout::Beside && placed.label.bottom() > placed.control.top() {
|
||||
@@ -353,10 +446,7 @@ fn flow_leaf_row<C: Show>(
|
||||
if let Some(installed) = installed {
|
||||
Env::restore(ui.ctx(), installed);
|
||||
}
|
||||
let bottom = control.bottom().max(placed.label.bottom());
|
||||
placed.finish(ui.ctx());
|
||||
// The grid's cursor takes the row as its next cell (outside a grid, the next allocation of `ui`'s layout).
|
||||
let _ = crate::layout::take_in_flow(ui, Vec2::new(extent, (bottom - row.top()).max(ideal.y)));
|
||||
output
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user