Merge pull request #2543 from davidmann4/haranishi-combined

Merge haranishi's 20 open UI fixes into next, with the fix-ups they need together
This commit is contained in:
David Mann authored and GitHub committed 2026-11-20 16:28:27 +01:00
commit 62189858af
61 files changed
+2693 -338

No files matched your search

+2 -1
View File
@@ -81,7 +81,8 @@ pub fn jump(span: &ScrollSpan, mv: NavMove) -> Option<Range<f64>> {
})
}
fn shifted(span: &ScrollSpan, shift: f64) -> Range<f64> {
/// Moves the visible range by `shift` content units, keeping it within the scrollable range.
pub fn shifted(span: &ScrollSpan, shift: f64) -> Range<f64> {
let visible = span.visible.end - span.visible.start;
let last = (span.content.end - visible).max(span.content.start);
let start = (span.visible.start + shift).clamp(span.content.start, last);
+6
View File
@@ -3,6 +3,8 @@
//! change as a resolved [`SwatchEdit`] (new, rename, delete, move, group edits, import) that the host runs, with
//! [`SwatchLibrary::apply`] for an in-memory host.
use craft_ui::tile_grid::TileZoom;
mod library;
mod menu;
mod panel;
@@ -13,6 +15,10 @@ pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState,
pub use menu::{SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput};
pub use panel::{SwatchesPanel, SwatchesPanelOutput};
/// Compact colour tiles at the default zoom, with the same upper limit as the preset browser.
const SWATCH_MIN_ZOOM: f64 = 1.0 / 3.0;
const SWATCH_ZOOM: TileZoom = TileZoom::bounded(SWATCH_MIN_ZOOM, 5.0, 1.0 / 12.0, SWATCH_MIN_ZOOM);
/// The most swatches a library holds (PhotoCraft's `MAX_SWATCHES`).
pub const MAX_SWATCHES: usize = 100_000;
+4 -2
View File
@@ -5,7 +5,7 @@ use std::collections::HashSet;
use craft_ui::contract::ReorderMove;
use craft_ui::patterns::presets::{PresetRow, PresetState};
use super::{MAX_GROUPS, MAX_SWATCHES, SwatchesWords};
use super::{MAX_GROUPS, MAX_SWATCHES, SWATCH_ZOOM, SwatchesWords};
use crate::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchReport};
use crate::ui::PickedColor;
@@ -37,7 +37,9 @@ pub struct SwatchesState {
impl Default for SwatchesState {
fn default() -> Self {
SwatchesState { browser: PresetState::new(), selected: None, rename: None, export_notes: None }
let mut browser = PresetState::new();
browser.zoom = SWATCH_ZOOM.default_value();
SwatchesState { browser, selected: None, rename: None, export_notes: None }
}
}
+2 -1
View File
@@ -17,7 +17,7 @@ use egui::{Rect, Response, Ui};
use super::library::{find_swatch, has};
use super::menu::event_edits;
use super::{SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_rows};
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_rows};
use crate::palette::{SwatchColor, SwatchGroup, SwatchNote, SwatchReport};
/// What [`SwatchesPanel::show`] reports.
@@ -103,6 +103,7 @@ impl<'a> SwatchesPanel<'a> {
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)
.thumb_range(SWATCH_ZOOM)
.toolbar(true)
.reorder(PresetReorder::items_and_groups())
.footer(PresetFooterOptions::new().can_delete(st.selected.is_some()))
+46 -6
View File
@@ -8,15 +8,17 @@ use craft_behavior::{EditEvent, Selection};
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
use craft_color_ui::ui::{
ColorPanel, ColorPanelMode, ColorPanelState, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand,
SwatchesMenu, SwatchesPanel, SwatchesState,
SwatchesMenu, SwatchesPanel, SwatchesState, SwatchesWords, swatch_rows,
};
use craft_host::target::Os;
use craft_theme::Srgba;
use craft_ui::choice::SwatchTable;
use craft_ui::contract::Role;
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, Show as _};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::env::{Label, Scale};
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::pointer::moved;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Vec2};
@@ -243,9 +245,9 @@ fn the_palette_arrows_walk_the_wrapped_grid() {
}
/// The Swatches panel over two groups, collecting the edits it reports and never applying them.
fn swatches_rig(groups: Vec<SwatchGroup>) -> (Fixture, Rc<RefCell<Vec<SwatchEdit>>>) {
fn swatches_rig(groups: Vec<SwatchGroup>, state: SwatchesState) -> (Fixture, Rc<RefCell<Vec<SwatchEdit>>>) {
let edits = Rc::new(RefCell::new(Vec::new()));
let state = Rc::new(RefCell::new(SwatchesState::default()));
let state = Rc::new(RefCell::new(state));
let (seen, held) = (Rc::clone(&edits), state);
let mut fixture = Fixture::new(move |ui| {
let mut current = held.borrow().clone();
@@ -257,6 +259,44 @@ fn swatches_rig(groups: Vec<SwatchGroup>) -> (Fixture, Rc<RefCell<Vec<SwatchEdit
(fixture, edits)
}
#[trial]
fn default_swatches_fit_the_ten_grays_in_a_narrow_dock_and_still_zoom() {
let grays = SwatchLibrary::default().groups.into_iter().find(|group| group.name == "Grays").expect("the factory Grays group");
let groups = vec![grays];
let names: Vec<_> = swatch_rows(&groups, &SwatchesWords::default()).into_iter().filter_map(|row| row.accessible_name).collect();
assert_eq!(names.len(), 10);
let (mut fixture, _) = swatches_rig(groups.clone(), SwatchesState::default());
fixture.os(Os::Windows).scale(Scale::new(1.25)).room(Vec2::new(220.0, 150.0)).settle();
let visible_grays =
|fixture: &Fixture| names.iter().filter_map(|name| fixture.by_label(name).and_then(|tile| fixture.visible(&tile))).collect::<Vec<_>>();
let defaults = visible_grays(&fixture);
assert_eq!(defaults.len(), 10, "all ten Grays are visible in the default dock");
let first = defaults[0].rect;
assert!(defaults.iter().all(|tile| tile.rect.top() == first.top()), "all ten Grays fit on one row");
let larger = fixture.by_label("Larger Thumbnails").expect("the larger thumbnail button");
fixture.click(&larger).settle();
let after_click = visible_grays(&fixture)[0].rect.width();
assert!(after_click > first.width(), "the zoom button enlarges the tiles");
let slider = fixture.by_role(Role::SLIDER).into_iter().next().expect("the thumbnail slider");
fixture.access(AccessActionKind::Focus, &slider).settle();
fixture.key(Key::ArrowRight, Modifiers::NONE).settle();
assert!(visible_grays(&fixture)[0].rect.width() > after_click, "the slider enlarges the tiles with the keyboard");
fixture.click(&slider).click(&slider).settle();
assert_eq!(visible_grays(&fixture)[0].rect.width(), first.width(), "double-click resets to the compact default");
let mut larger_state = SwatchesState::default();
larger_state.browser.zoom = 1.75;
let (mut fixture, _) = swatches_rig(groups, larger_state);
fixture.room(Vec2::new(220.0, 310.0)).settle();
let slider = fixture.by_role(Role::SLIDER).into_iter().next().expect("the reopened thumbnail slider");
let shown = fixture.tree().numeric_of(slider.node).expect("the slider's accessible value and range");
assert_eq!(shown.value, Some(1.75), "a previously chosen larger zoom is still displayed");
assert_eq!(*shown.range.end(), 5.0, "the larger end of the zoom range stays available");
}
/// Through the panel, a selected swatch deleted reports one `Delete`, and a swatch dragged onto another group's header
/// reports one `MoveTo` the host can run; New Swatch from the menu reports an `Add` in the selected swatch's group under
/// the next free numbered name. The slots of multi-swatch moves are checked in library.rs.
@@ -269,14 +309,14 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red", red), entry("Color Swatch 1", blue)] },
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Blue", blue)] },
];
let (mut fixture, edits) = swatches_rig(groups.clone());
let (mut fixture, edits) = swatches_rig(groups.clone(), SwatchesState::default());
let row = fixture.by_label("Red, #ff0000").expect("the Red swatch is named with its value");
fixture.click(&row).settle();
assert!(edits.borrow().is_empty(), "a click selects and uses, it edits nothing: {:?}", edits.borrow());
fixture.key(Key::Delete, Modifiers::NONE).settle();
assert_eq!(*edits.borrow(), [SwatchEdit::delete("Red".to_owned())], "one resolved edit, once");
let (mut fixture, edits) = swatches_rig(groups.clone());
let (mut fixture, edits) = swatches_rig(groups.clone(), SwatchesState::default());
let row = fixture.by_label("Red, #ff0000").expect("the Red swatch");
let header = fixture.by_label("Other").expect("the Other group's header").center();
fixture.drag(&row, header - row.center()).settle();
+42 -18
View File
@@ -10,10 +10,13 @@ mod stories;
use craft_behavior::{EditEvent, Mixed};
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Pattern, Props as _, Show as _, ShowContainer as _, clicked};
use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked};
use craft_ui::display::{Shade, Text};
use craft_ui::form::Field;
use craft_ui::layout_components::Stack;
use craft_ui::patterns::presets::{PresetPicker, PresetRow};
use craft_ui::patterns::presets::{PickerField, PresetPicker, PresetRow};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::style::TypeRole;
use egui::{Response, Ui};
use std::sync::Arc;
@@ -25,6 +28,10 @@ use super::{GradientGroup, GradientRef};
const MAX_STOPS: usize = 64;
const MIN_STOPS: usize = 2;
/// An explicit pick wins when two presets have the same colour stops.
#[derive(Clone, Copy, Default)]
struct PickedPreset(Option<GradientRef>);
/// The Gradient Map adjustment's value: the gradient the image's luminance maps through, and its two options.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -56,6 +63,8 @@ craft_ui::words! {
preset: "gradientMap.preset" = "Preset";
/// The picker's placeholder while the stops are no preset.
custom: "gradientMap.custom" = "Custom";
/// How to add another stop on the gradient.
add_stop_hint: "gradientMap.addStopHint" = "Click below the ramp to add a stop.";
/// The command that imports presets.
import_presets: "gradientMap.importPresets" = "Import .GRD";
/// The Reverse option.
@@ -101,22 +110,17 @@ impl<'a> GradientMapEditor<'a> {
GradientMapEditor { label: label.into(), value, presets: &[], sampler: None }
}
/// The stops of preset `key`, as the map takes them: colour stops only, opaque, midpoints centred, at most 64.
fn preset_stops(&self, key: GradientRef) -> Option<GradientStops> {
/// A preset as Gradient Map uses it: opaque colour stops with centred midpoints.
fn preset_colors(&self, key: GradientRef) -> Option<impl Iterator<Item = ColorStop> + '_> {
let GradientRef::Item { group, item } = key else { return None };
let preset = self.presets.get(group)?.items.get(item)?;
let color: Vec<ColorStop> = preset
.stops
.color
.iter()
.take(MAX_STOPS)
.map(|s| {
let colors = &self.presets.get(group)?.items.get(item)?.stops.color;
(colors.len() >= MIN_STOPS).then(|| {
colors.iter().take(MAX_STOPS).map(|s| {
let mut stop = s.with_midpoint(0.5);
stop.color.a = 1.0;
stop
})
.collect();
(color.len() >= MIN_STOPS).then(|| GradientStops::new(color))
})
}
/// Shows the editor across the available width.
@@ -131,7 +135,7 @@ impl<'a> GradientMapEditor<'a> {
let (preset_label, custom, import_label, stops_label) =
(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, _| {
let shown = Stack::new().label(self.label.clone()).show(ui, |ui, cx| {
let rows: Vec<PresetRow<GradientRef>> = self
.presets
.iter()
@@ -143,14 +147,34 @@ impl<'a> GradientMapEditor<'a> {
std::iter::once(header).chain(items)
})
.collect();
let picker =
PresetPicker::new(preset_label.clone(), Bind::given(None::<GradientRef>), &rows, Bind::kept()).placeholder(custom.clone()).show(ui);
if let Some(stops) = picker.picked.and_then(|key| self.preset_stops(key)) {
event = Some(set(GradientMap { stops, ..base.clone() }));
// 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 picked = Field::new(preset_label.clone())
.show(ui, |ui, _| {
PresetPicker::new(preset_label.clone(), Bind::given(current), &rows, Bind::kept())
.field(PickerField::Name)
.placeholder(custom.clone())
.show(ui)
.picked
})
.inner
.flatten();
if let Some(key) = picked
&& let Some(colors) = self.preset_colors(key)
{
cx.keep::<PickedPreset>().0 = Some(key);
event = Some(set(GradientMap { stops: GradientStops::new(colors.collect()), ..base.clone() }));
}
if clicked(&Button::new(import_label.clone()).show(ui)) {
import = true;
}
if base.stops.color.len() < MAX_STOPS {
Text::new(words.add_stop_hint.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
}
let rules = StopRules::new(StopRows::ColorOnly).stops(MIN_STOPS, MAX_STOPS);
let mut editor =
GradientEditor::new(stops_label.clone(), Bind::given(base.stops.clone())).rules(rules).midpoints(false).location_decimals(1);
+55
View File
@@ -0,0 +1,55 @@
//! Gradient Map readout and stop editing.
use std::cell::RefCell;
use std::rc::Rc;
use craft_color_ui::ui::gradient::{ColorStop, GradientStops};
use craft_draw::ui::gradient::{GradientGroup, GradientItem, GradientMap, GradientMapEditor};
use craft_theme::Srgba;
use craft_ui::testing::{Fixture, trial};
#[trial]
fn gradient_map_names_the_current_preset_and_shows_how_to_add_a_stop() {
let black = Srgba::rgb(0.0, 0.0, 0.0);
let white = Srgba::rgb(1.0, 1.0, 1.0);
let blue = Srgba::rgb(0.0, 0.0, 1.0);
let stops = |first| GradientStops::new(vec![ColorStop::new(0.0, first), ColorStop::new(1.0, white)]);
let presets =
[GradientGroup::new("Basics", vec![GradientItem::new("Blue to White Alias", stops(blue)), GradientItem::new("Blue to White", stops(blue))])];
let value = Rc::new(RefCell::new(GradientMap::new(stops(black), false, true)));
let held = Rc::clone(&value);
let mut fixture = Fixture::new(move |ui| {
let out = GradientMapEditor::new("Gradient Map", &held.borrow()).presets(&presets).show(ui);
if let Some(event) = out.event {
event.apply(&mut held.borrow_mut());
}
});
fixture.room(egui::vec2(380.0, 330.0)).settle();
let visible = |fixture: &Fixture, text: &str| {
assert!(
fixture.texts().iter().any(|run| run.text == text && !run.elided && run.clip.contains_rect(run.rect)),
"{text:?} is fully visible; painted {:?}",
fixture.texts().iter().map(|run| run.text.as_str()).collect::<Vec<_>>()
);
};
visible(&fixture, "Preset");
visible(&fixture, "Custom");
let picker = fixture.by_label("Preset").expect("a named preset picker");
fixture.click(&picker).settle();
let blue_to_white = fixture.by_label("Blue to White").expect("the library preset");
fixture.click(&blue_to_white).settle();
visible(&fixture, "Blue to White");
assert_eq!(value.borrow().stops, stops(blue));
visible(&fixture, "Click below the ramp to add a stop.");
let first = fixture.by_label("Color stop 1 of 2").expect("first stop");
let last = fixture.by_label("Color stop 2 of 2").expect("last stop");
fixture.click_at(first.center().lerp(last.center(), 0.5)).settle();
let active = value.borrow();
assert_eq!(active.stops.color.len(), 3);
assert!((active.stops.color[1].location - 0.5).abs() < 0.01);
assert!(active.dither);
visible(&fixture, "Custom");
}
+1
View File
@@ -7,6 +7,7 @@ mod shape_cells;
// draw-gradient-b
mod gradient_fill;
mod gradient_map;
mod gradient_overlay;
// draw-connector
+17 -18
View File
@@ -9,13 +9,13 @@ use craft_ui::sections::{FooterAction, FooterBar};
use egui::{Id, Ui};
use super::labels::ChannelsWords;
use super::model::{ChannelKind, ChannelRow, ChannelsEvent, targeted_row};
use super::model::{ChannelKind, ChannelRow, ChannelsEvent, targeted_for_delete, targeted_row};
/// A button of the Channels footer.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChannelsFooterButton {
/// Delete current channel: disabled while the target is the composite, a colour channel or Quick Mask.
/// Delete the targeted channel when it can be deleted.
Delete,
/// Create new channel; a row dropped on it is duplicated.
New,
@@ -26,22 +26,16 @@ pub enum ChannelsFooterButton {
}
/// What a row drag carries for the footer's buttons: the list it started in, the row the pointer grabbed and that
/// row's kind.
/// row's key.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct ChannelDrag<K> {
pub(super) list: Id,
pub(super) grabbed: K,
pub(super) kind: ChannelKind,
}
/// Whether `button` takes a drop of a row of `kind`: Delete refuses the composite, colour channels and Quick Mask;
/// New and Load take every row; Save takes none.
pub(super) fn accepts_footer_drop(button: ChannelsFooterButton, kind: ChannelKind) -> bool {
match button {
ChannelsFooterButton::Delete => !matches!(kind, ChannelKind::Composite | ChannelKind::Color | ChannelKind::QuickMask(_)),
ChannelsFooterButton::New | ChannelsFooterButton::LoadSelection => true,
ChannelsFooterButton::SaveSelection => false,
}
/// Delete takes saved channels, a layer mask or an opted-in process colour.
fn deletable<K>(row: &ChannelRow<K>) -> bool {
row.can_delete_color() || !matches!(row.kind, ChannelKind::Composite | ChannelKind::Color | ChannelKind::QuickMask(_))
}
// Photoshop's order from the end edge.
@@ -63,7 +57,7 @@ fn button_at(at: usize) -> Option<ChannelsFooterButton> {
/// Shows the footer and returns its events in order.
///
/// - Buttons from the leading end: Load channel as selection, Save selection as channel, New, Delete. Delete is
/// disabled for a click while the targeted row is the composite, a colour channel or Quick Mask, or there is none.
/// disabled for a click unless the target is deletable. A process colour must be the only process target.
/// - A click reports [`ChannelsEvent::Footer`] with `rows` = [`targeted_row`] and the modifiers held.
/// - Delete, New and Load take a dragged row of the panel's list: a drop reports [`ChannelsEvent::FooterDrop`] with
/// the row the pointer grabbed. A button shows the drop outline, and Delete reads enabled, while the grabbed row is
@@ -75,25 +69,30 @@ pub(super) fn show_footer<K: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
list: Id,
) -> Vec<ChannelsEvent<K>> {
let target = targeted_row(rows);
let delete_enabled = target.is_some_and(|row| accepts_footer_drop(ChannelsFooterButton::Delete, row.kind));
let takes = |button: ChannelsFooterButton| move |drag: &ChannelDrag<K>| drag.list == list && accepts_footer_drop(button, drag.kind);
let delete_target = targeted_for_delete(rows);
let delete_enabled = delete_target.is_some_and(deletable);
let deletable_keys: Vec<K> = rows.iter().filter(|row| deletable(row)).map(|row| row.key.clone()).collect();
let from_list = move |drag: &ChannelDrag<K>| drag.list == list;
let icon = |name: &'static str| IconSpec::svg(IconId::new(name));
let actions = [
FooterAction::new(icon("trash"), words.delete.clone())
.enabled(delete_enabled)
.takes_drops_disabled(true)
.accepts_drops(takes(ChannelsFooterButton::Delete)),
FooterAction::new(icon("plus"), words.new.clone()).accepts_drops(takes(ChannelsFooterButton::New)),
.accepts_drops(move |drag: &ChannelDrag<K>| from_list(drag) && deletable_keys.contains(&drag.grabbed)),
FooterAction::new(icon("plus"), words.new.clone()).accepts_drops(from_list),
FooterAction::new(icon("rect_dashed"), words.save_selection.clone()),
FooterAction::new(icon("ellipse_dashed"), words.load_selection.clone()).accepts_drops(takes(ChannelsFooterButton::LoadSelection)),
FooterAction::new(icon("ellipse_dashed"), words.load_selection.clone()).accepts_drops(from_list),
];
let out = FooterBar::actions(actions).show_footer(ui);
let mut events = Vec::new();
if let Some(button) = out.picked.and_then(button_at) {
let target = if button == ChannelsFooterButton::Delete { delete_target } else { target };
events.push(ChannelsEvent::Footer { button, rows: target.map(|row| row.key.clone()).into_iter().collect(), mods: out.mods });
}
if let Some(dropped) = &out.dropped
&& let (Some(button), Some(drag)) = (button_at(dropped.index), dropped.payload::<ChannelDrag<K>>())
&& from_list(drag)
&& (button != ChannelsFooterButton::Delete || rows.iter().any(|row| row.key == drag.grabbed && deletable(row)))
{
events.push(ChannelsEvent::FooterDrop { button, rows: vec![drag.grabbed.clone()] });
}
+21 -9
View File
@@ -12,7 +12,7 @@ use egui::{Response, Ui};
use std::sync::Arc;
use super::labels::ChannelsWords;
use super::model::{ChannelKind, ChannelRow, ChannelsEvent, ColorIndicates, OVERLAY_OPACITIES, OverlayPreset, targeted_row};
use super::model::{ChannelKind, ChannelRow, ChannelsEvent, ColorIndicates, OVERLAY_OPACITIES, OverlayPreset, targeted_for_delete, targeted_row};
/// The commands of the Channels panel: its panel-menu rows, its row menu, and the keys of the list.
///
@@ -217,10 +217,14 @@ impl ChannelsCommands {
}
}
fn applies_to_row<K>(self, row: Option<&ChannelRow<K>>) -> bool {
self.applies_to(row.map(|row| row.kind)) || (self == Self::Delete && row.is_some_and(ChannelRow::can_delete_color))
}
/// The event the command makes over `rows` with the modifiers `mods` held; `None` when it does nothing there.
/// Rename has no event: the panel opens the row's rename field.
pub fn event<K: Clone + PartialEq>(self, rows: &[ChannelRow<K>], mods: Mods) -> Option<ChannelsEvent<K>> {
let target = targeted_row(rows)?;
let target = if self == Self::Delete { targeted_for_delete(rows) } else { targeted_row(rows) }?;
match self {
ChannelsCommands::LoadSelection => {
Some(ChannelsEvent::LoadSelection { key: target.key.clone(), operation: SelectionOperation::from_mods(mods) })
@@ -229,7 +233,7 @@ impl ChannelsCommands {
ChannelsCommands::ChannelOptions => target.kind.has_options().then(|| ChannelsEvent::Options(target.key.clone())),
ChannelsCommands::RenameChannel => None,
command => {
self.applies_to(Some(target.kind)).then(|| ChannelsEvent::Command { command, key: command_key(command).then(|| target.key.clone()) })
self.applies_to_row(Some(target)).then(|| ChannelsEvent::Command { command, key: command_key(command).then(|| target.key.clone()) })
}
}
}
@@ -294,7 +298,7 @@ fn add_commands(lines: &mut Vec<Plan>, commands: &[ChannelsCommands]) {
}
/// The menu lines for a row of `kind`; with no row, the document's.
fn plan(kind: Option<ChannelKind>) -> Vec<Plan> {
fn plan(kind: Option<ChannelKind>, can_delete_color: bool) -> Vec<Plan> {
use ChannelsCommands as C;
let mut lines: Vec<Plan> = Vec::new();
match kind {
@@ -313,6 +317,7 @@ fn plan(kind: Option<ChannelKind>) -> Vec<Plan> {
lines.extend(overlay_plan());
}
Some(ChannelKind::LayerMask(_)) => add_commands(&mut lines, &[C::ToggleLayerMask, C::DeleteLayerMask, C::ChannelOptions]),
Some(ChannelKind::Color) if can_delete_color => add_commands(&mut lines, &[C::Duplicate, C::Delete]),
Some(ChannelKind::Composite | ChannelKind::Color) => add_commands(&mut lines, &[C::Duplicate]),
None => {}
}
@@ -342,10 +347,17 @@ pub fn panel_rows() -> Vec<PanelRow> {
]
}
/// Each command greyed by the targeted row's kind, the one rule the panel's publish loop and the dock's panel menu share.
/// Enabled states shared by the panel and the dock's panel menu.
pub fn states<K>(rows: &[ChannelRow<K>]) -> Vec<(ChannelsCommands, CommandState)> {
let kind = targeted_row(rows).map(|row| row.kind);
ChannelsCommands::ALL.into_iter().map(|command| (command, CommandState::new().enabled(command.applies_to(kind)))).collect()
let target = targeted_row(rows);
let delete_target = targeted_for_delete(rows);
ChannelsCommands::ALL
.into_iter()
.map(|command| {
let row = if command == ChannelsCommands::Delete { delete_target } else { target };
(command, CommandState::new().enabled(command.applies_to_row(row)))
})
.collect()
}
fn label_of(command: ChannelsCommands, kind: Option<ChannelKind>, words: &ChannelsWords) -> Label {
@@ -403,7 +415,7 @@ fn checked(command: ChannelsCommands, kind: Option<ChannelKind>) -> Option<bool>
pub(super) fn show_row_menu<K>(ui: &mut Ui, opener: &Response, row: &ChannelRow<K>, words: &ChannelsWords) -> Option<ChannelsCommands> {
let kind = Some(row.kind);
let units = Env::of(ui).units();
let lines = plan(kind);
let lines = plan(kind, row.can_delete_color());
let shown = Menu::context(words.row_menu.clone(), opener).show(ui, |ui, _| {
use craft_ui::contract::Show as _;
let mut ran = None;
@@ -413,7 +425,7 @@ pub(super) fn show_row_menu<K>(ui: &mut Ui, opener: &Response, row: &ChannelRow<
craft_ui::display::Divider::horizontal().show(ui);
}
Plan::Command(command) => {
let mut item = MenuItem::new(label_of(command, kind, words)).enabled(command.applies_to(kind));
let mut item = MenuItem::new(label_of(command, kind, words)).enabled(command.applies_to_row(Some(row)));
if let Some(on) = checked(command, kind) {
item = item.radio_mark(on);
}
+15 -4
View File
@@ -115,18 +115,23 @@ pub struct ChannelRow<K> {
/// The app's highlight: the targeted channel, or every colour row while the composite is
/// targeted (PhotoCraft).
pub targeted: bool,
/// The host supports deleting this individual process colour row. Off by default.
pub allow_color_deletion: bool,
}
impl<K> ChannelRow<K> {
/// A visible, untargeted row.
pub fn new(key: K, kind: ChannelKind, name: impl Into<String>) -> Self {
Self { key, kind, name: name.into(), visible: true, targeted: false }
Self { key, kind, name: name.into(), visible: true, targeted: false, allow_color_deletion: false }
}
pub(super) fn can_delete_color(&self) -> bool {
self.kind == ChannelKind::Color && self.allow_color_deletion
}
}
/// The row the footer's Delete and Load act on: the targeted layer-mask, alpha, spot or Quick
/// Mask row; else the composite when it is targeted; else the one targeted colour row; `None`
/// with no rows or no target.
/// Target-based commands prefer a targeted layer mask, alpha, spot or Quick Mask row.
/// Otherwise they use the targeted composite or the first targeted process colour.
pub fn targeted_row<K>(rows: &[ChannelRow<K>]) -> Option<&ChannelRow<K>> {
let targeted = |kinds: fn(ChannelKind) -> bool| rows.iter().find(|row| row.targeted && kinds(row.kind));
targeted(|kind| !matches!(kind, ChannelKind::Composite | ChannelKind::Color))
@@ -134,6 +139,12 @@ pub fn targeted_row<K>(rows: &[ChannelRow<K>]) -> Option<&ChannelRow<K>> {
.or_else(|| targeted(|kind| matches!(kind, ChannelKind::Color)))
}
/// Target-based deletion needs one component; an explicit row menu or drag already identifies it.
pub(super) fn targeted_for_delete<K>(rows: &[ChannelRow<K>]) -> Option<&ChannelRow<K>> {
let row = targeted_row(rows)?;
(row.kind != ChannelKind::Color || rows.iter().filter(|row| row.targeted && row.kind == ChannelKind::Color).take(2).count() == 1).then_some(row)
}
/// What the Channels panel reports, in the order it happened.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
+9 -6
View File
@@ -22,7 +22,7 @@ use egui::Ui;
use super::footer::{ChannelDrag, show_footer};
use super::labels::{ChannelsWords, shortcut_numbers};
use super::menu::{ChannelsCommands, lands, show_row_menu};
use super::model::{ChannelKind, ChannelRow, ChannelsEvent, ChannelsOutput, targeted_row};
use super::model::{ChannelKind, ChannelRow, ChannelsEvent, ChannelsOutput, targeted_for_delete, targeted_row};
use super::rows::{EYE, NAME, RowContext, ThumbHost, channel_row};
/// What the panel keeps between passes, in its root slot: the row the last context request opened the menu on.
@@ -93,7 +93,7 @@ impl<K: Clone> ItemSource<K> for Order<'_, K> {
/// [`Rename`](ChannelsEvent::Rename).
/// - **Drag**: alpha and spot rows reorder, before or after another one or before Quick Mask
/// ([`Reorder`](ChannelsEvent::Reorder); Cmd/Ctrl+] and [ too). Any row drops on the footer's New and Load buttons,
/// and an alpha or spot row on Delete; a drop acts on the row grabbed.
/// and a deletable row on Delete. A drop acts on the row grabbed.
/// - **Menus**: a right-click or the Menu key opens the row's context menu; [`panel_rows`](super::panel_rows) is the
/// panel menu's fixed list, each command greyed by [`states`](super::states).
/// - **Right to left**: the list and the footer mirror; the chord sits at the trailing end.
@@ -172,7 +172,7 @@ impl<'a, K: Clone + Eq + Hash + Debug + Send + Sync + 'static> ChannelsPanel<'a,
let lead = targeted_row(rows).map(|row| row.key.clone());
let mut selection = Selection::new(rows.iter().filter(|row| row.targeted).map(|row| row.key.clone()).collect(), lead.clone(), lead);
let kinds: Vec<(K, ChannelKind)> = rows.iter().map(|row| (row.key.clone(), row.kind)).collect();
let payload_kinds = kinds.clone();
let payload_rows: Vec<K> = rows.iter().map(|row| row.key.clone()).collect();
let kind_of = |key: &K| kinds.iter().find(|(k, _)| k == key).map(|(_, kind)| *kind);
let columns = vec![
ColumnSpec::toggle(EYE, Label::Empty, ToggleColumn::sweepable()).icon(IconId::new("eye")),
@@ -198,8 +198,7 @@ impl<'a, K: Clone + Eq + Hash + Debug + Send + Sync + 'static> ChannelsPanel<'a,
lands(&remaining, insert.saturating_sub(moved_before))
})
.drag_payload(move |drag: &ListDrag<K>| {
let kind = payload_kinds.iter().find(|(key, _)| *key == drag.grabbed).map(|(_, kind)| *kind)?;
Some(ChannelDrag { list: drag.list, grabbed: drag.grabbed.clone(), kind })
payload_rows.contains(&drag.grabbed).then(|| ChannelDrag { list: drag.list, grabbed: drag.grabbed.clone() })
})
.show_items(ui, &order, &mut |_key, item| {
let at = item.at;
@@ -264,7 +263,11 @@ fn map_events<K: Clone + PartialEq>(
}
CollectionEvent::Reorder(edit) => events.push(ChannelsEvent::Reorder(edit)),
CollectionEvent::Delete(keys) => {
for key in keys.into_iter().filter(|key| kind_of(key).is_some_and(ChannelKind::moves)) {
let delete_color = matches!(
keys.as_slice(),
[key] if targeted_for_delete(rows).is_some_and(|row| &row.key == key && row.can_delete_color())
);
for key in keys.into_iter().filter(|key| delete_color || kind_of(key).is_some_and(ChannelKind::moves)) {
events.push(ChannelsEvent::Command { command: ChannelsCommands::Delete, key: Some(key) });
}
}
+4 -4
View File
@@ -8,7 +8,7 @@ use craft_ui::buttons::Button;
use craft_ui::canvas::{PixelRect, RasterSource};
use craft_ui::choice::{Checkbox, Radio, RadioGroup, Segmented};
use craft_ui::contract::{
Bind, CanvasGesture, EditResponse, Entry, NoValue, Outcome, Pattern, Props, Sampler as _, Show as _, ShowContainer as _, clicked,
Bind, CanvasGesture, EditResponse, Entry, FieldLayout, NoValue, Outcome, Pattern, Props, Sampler as _, Show as _, ShowContainer as _, clicked,
};
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, FieldGroup, SliderField};
@@ -293,7 +293,7 @@ impl<'a> ColorRangeDialog<'a> {
next.samples.pick(at, document, tool, mods);
pass.set(&words.eyedropper, next);
}
Stack::new().show(ui, |ui, _| {
Stack::new().fill_width().show(ui, |ui, _| {
Stack::new().enabled(c.sampling).show(ui, |ui, _| {
let tools = [
Entry::new(SampleTool::Sample, words.eyedropper.clone()).icon(IconSpec::svg(IconId::new("eyedropper"))),
@@ -323,7 +323,7 @@ impl<'a> ColorRangeDialog<'a> {
});
let events = Checkbox::new(Bind::given(now.invert)).label(words.invert.clone()).show(ui).events;
pass.lift(events, |value, on| value.invert = on);
Field::new(words.selection.clone()).id_salt("view").show(ui, |ui, _| {
Field::new(words.selection.clone()).layout(FieldLayout::Above).id_salt("view").show(ui, |ui, _| {
let group = RadioGroup::new(words.selection.clone(), Bind::given(show_image)).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Radio::new(false).label(words.selection.clone()).show(ui);
@@ -332,7 +332,7 @@ impl<'a> ColorRangeDialog<'a> {
});
picked_view = group.output.value().copied();
});
Field::new(words.selection_preview.clone()).show(ui, |ui, _| {
Field::new(words.selection_preview.clone()).layout(FieldLayout::Above).show(ui, |ui, _| {
let modes = [
Entry::new(PreviewMode::None, words.none.clone()),
Entry::new(PreviewMode::Grayscale, preview_words.grayscale.clone()),
+123
View File
@@ -0,0 +1,123 @@
//! Deleting one process row uses its own key, from the context menu, keyboard and trash button.
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Event, Key, Modifiers, PointerButton, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::ui::channels::{ChannelKind, ChannelRow, ChannelsCommands, ChannelsEvent, ChannelsFooterButton, ChannelsPanel};
const RGB: u8 = 0;
const GREEN: u8 = 1;
const BLUE: u8 = 2;
type Events = Rc<RefCell<Vec<ChannelsEvent<u8>>>>;
fn panel(targets: &[u8], allow_color_deletion: bool) -> (Fixture, Events) {
panel_with_permission(targets, Rc::new(Cell::new(allow_color_deletion)))
}
fn panel_with_permission(targets: &[u8], allow_color_deletion: Rc<Cell<bool>>) -> (Fixture, Events) {
let mut rows =
[(RGB, ChannelKind::Composite, "RGB"), (GREEN, ChannelKind::Color, "Green"), (BLUE, ChannelKind::Color, "Blue")].map(|(key, kind, name)| {
let mut row = ChannelRow::new(key, kind, name);
row.targeted = targets.contains(&key);
row
});
let events = Events::default();
let reported = Rc::clone(&events);
let mut fixture = Fixture::new(move |ui| {
for row in &mut rows {
row.allow_color_deletion = allow_color_deletion.get();
}
reported.borrow_mut().extend(ChannelsPanel::new(&rows).show(ui).events);
});
fixture.room(Vec2::new(900.0, 700.0)).idle(6);
(fixture, events)
}
fn context(fixture: &mut Fixture, name: &str) {
let pos = fixture.by_label(name).expect("a named channel row").center();
fixture.frame(vec![pointer::moved(pos)]);
for pressed in [true, false] {
fixture.frame(vec![Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }]);
}
fixture.idle(2);
}
fn deleted(events: &Events) -> Vec<u8> {
events
.borrow()
.iter()
.filter_map(|event| match event {
ChannelsEvent::Command { command: ChannelsCommands::Delete, key: Some(key), .. } => Some(std::slice::from_ref(key)),
ChannelsEvent::Footer { button: ChannelsFooterButton::Delete, rows, .. }
| ChannelsEvent::FooterDrop { button: ChannelsFooterButton::Delete, rows, .. } => Some(rows.as_slice()),
_ => None,
})
.flatten()
.copied()
.collect()
}
#[trial]
fn process_channel_delete_uses_the_clicked_or_dragged_row() {
let (mut menu, events) = panel(&[RGB, GREEN, BLUE], true);
context(&mut menu, "Green");
assert!(menu.by_label("Duplicate Channel").is_some(), "the process row opens its regular context menu");
let delete = menu.by_label("Delete Channel").expect("the process row's Delete Channel menu item");
menu.click(&delete).idle(2);
assert_eq!(deleted(&events), [GREEN], "the menu deletes the right-clicked row, even with the composite targeted");
let (mut drag, events) = panel(&[RGB, GREEN, BLUE], true);
let row = drag.by_label("Green").expect("the Green row");
let trash = drag.by_label("Delete current channel").expect("the trash button");
drag.drag(&row, trash.center() - row.center()).idle(3);
assert_eq!(deleted(&events), [GREEN], "the drop deletes the grabbed row, even with the composite targeted");
}
#[trial]
fn process_channel_delete_from_the_keyboard_and_footer_requires_one_target() {
let (mut single, events) = panel(&[GREEN], true);
let row = single.by_label("Green").unwrap();
single.click(&row);
assert!(single.focused_role().is_some(), "clicking the process row gives the list focus");
single.key(Key::Delete, Modifiers::NONE).idle(3);
assert_eq!(deleted(&events), [GREEN], "Delete on one focused process row");
events.borrow_mut().clear();
let trash = single.by_label("Delete current channel").unwrap();
single.click(&trash).idle(2);
assert_eq!(deleted(&events), [GREEN], "the trash button deletes a single targeted process row");
for (targets, opted_in) in [(&[GREEN, BLUE][..], true), (&[GREEN][..], false), (&[RGB, GREEN, BLUE][..], true)] {
let (mut blocked, events) = panel(targets, opted_in);
let name = if targets.contains(&RGB) { "RGB" } else { "Green" };
let row = blocked.by_label(name).unwrap();
blocked.click(&row).key(Key::Delete, Modifiers::NONE).idle(2);
let trash = blocked.by_label("Delete current channel").unwrap();
blocked.click(&trash).idle(2);
assert!(deleted(&events).is_empty(), "ambiguous, composite and unconfigured targets have no process delete");
if !opted_in || targets.contains(&RGB) {
blocked.drag(&row, trash.center() - row.center()).idle(3);
assert!(deleted(&events).is_empty(), "this row also refuses a trash drop");
context(&mut blocked, name);
assert!(blocked.by_label("Delete Channel").is_none(), "this row's context menu keeps the default");
}
}
}
#[trial]
fn revoking_process_channel_delete_during_a_drag_blocks_the_drop() {
let allow = Rc::new(Cell::new(true));
let (mut fixture, events) = panel_with_permission(&[GREEN], Rc::clone(&allow));
let row = fixture.by_label("Green").expect("the Green row").center();
let trash = fixture.by_label("Delete current channel").expect("the trash button").center();
fixture.frame(vec![pointer::moved(row)]);
fixture.frame(vec![Event::PointerButton { pos: row, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]);
fixture.frame(vec![pointer::moved(row + Vec2::new(16.0, 0.0))]);
fixture.frame(vec![pointer::moved(trash)]);
allow.set(false);
fixture.frame(Vec::new());
fixture.frame(vec![Event::PointerButton { pos: trash, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]);
fixture.idle(3);
assert!(deleted(&events).is_empty(), "the current row revokes delete before the drop");
}
+83 -3
View File
@@ -2,14 +2,20 @@
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use craft_behavior::PixelSize;
use craft_imaging::ui::color_range::{ColorRangeDialog, ColorRangeSelect, ColorRangeValue, SampleSign, SampleTool};
use craft_host::target::Os;
use craft_imaging::selection::PreviewMode;
use craft_imaging::ui::color_range::{ColorRangeDialog, ColorRangeSelect, ColorRangeValue, HostedColorRange, SampleSign, SampleTool};
use craft_ui::canvas::{PixelRect, RasterSource};
use craft_ui::contract::Bind;
use craft_ui::contract::{Bind, Role};
use craft_ui::dialog::DialogHost;
use craft_ui::fonts::{I18nScripts, UiFonts};
use craft_ui::primitives::Revision;
use craft_ui::runtime::env::Scale;
use craft_ui::testing::{Fixture, trial};
use egui::{Color32, ColorImage, Modifiers, Pos2, Rect, vec2};
use egui::{Color32, ColorImage, Modifiers, Pos2, Rect, Vec2, vec2};
/// The proxy: 40 × 20 pixels shown in a square well, so the picture is letterboxed and the well has room off it. It is
/// large enough that the fitted zoom stays inside the pane's zoom range, so the picture spans the well's width.
@@ -159,3 +165,77 @@ fn preview_presses_and_drags_sample_add_and_subtract_in_order() {
fixture.settle();
assert_eq!(samples().order.len(), count);
}
/// Open the same form used by Select > Color Range with a ready image and mask.
fn hosted_fixture(room: Vec2) -> (Rc<RefCell<DialogHost>>, Fixture) {
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
UiFonts::new(&I18nScripts).install(fixture.ctx());
fixture.os(Os::Windows).scale(Scale::new(1.25)).room(room);
let mut dialog = HostedColorRange::new("Color Range", ColorRangeValue::default(), DOCUMENT);
dialog.set_preview(Some(Arc::new(Flat)), Some(Arc::new(Flat)), SCALE, None);
host.borrow_mut().open(dialog);
fixture.settle().idle(10);
(host, fixture)
}
#[trial]
fn color_range_15558_hosted_controls_fit_at_125_percent() {
for room in [vec2(1600.0, 1000.0), vec2(1280.0, 800.0)] {
let (_, fixture) = hosted_fixture(room);
let dialog = fixture.by_role(Role::DIALOG)[0].rect;
for (label, role) in [
("Eyedropper", Role::RADIO_BUTTON),
("Add to Sample", Role::RADIO_BUTTON),
("Subtract from Sample", Role::RADIO_BUTTON),
("Invert", Role::CHECK_BOX),
("Selection", Role::RADIO_BUTTON),
("Image", Role::RADIO_BUTTON),
("Selection Preview", Role::COMBO_BOX),
] {
let target = fixture
.by_role(role)
.into_iter()
.find(|target| fixture.tree().name_of(target.node) == Some(label))
.unwrap_or_else(|| panic!("missing {label} at {room:?}"));
assert!(target.rect.width() > 0.0 && dialog.contains_rect(target.rect), "{label}: {:?} outside {dialog:?} at {room:?}", target.rect);
}
let hint = fixture.texts().iter().find(|text| text.text == "Sample: foreground color").expect("sample source hint");
assert!(hint.clip.contains_rect(hint.rect), "sample source hint is clipped");
}
}
#[trial]
fn color_range_15558_hosted_controls_respond_to_pointer() {
let (host, mut fixture) = hosted_fixture(vec2(1280.0, 800.0));
let well = fixture.by_label("Color Range preview").expect("preview pane").rect;
let click = |fixture: &mut Fixture, label: &str| {
let target = fixture.by_label(label).expect(label);
fixture.click_at(target.center()).settle();
};
let tool = || host.borrow_mut().get_mut::<HostedColorRange>().expect("open").tool();
let samples = || host.borrow_mut().get_mut::<HostedColorRange>().expect("open").value().samples.clone();
fixture.click_at(cell(well, 2.0, 3.0)).settle();
click(&mut fixture, "Add to Sample");
assert_eq!(tool(), SampleTool::Add);
fixture.click_at(cell(well, 5.0, 3.0)).settle();
assert_eq!(samples().add, [[12.0, 17.0], [27.0, 17.0]]);
click(&mut fixture, "Subtract from Sample");
assert_eq!(tool(), SampleTool::Subtract);
fixture.click_at(cell(well, 7.0, 3.0)).settle();
assert_eq!(samples().subtract, [[37.0, 17.0]]);
click(&mut fixture, "Eyedropper");
assert_eq!(tool(), SampleTool::Sample);
click(&mut fixture, "Invert");
click(&mut fixture, "Image");
click(&mut fixture, "Selection Preview");
click(&mut fixture, "Black Matte");
let mut host = host.borrow_mut();
let dialog = host.get_mut::<HostedColorRange>().expect("open after pointer input");
assert!(dialog.value().invert);
assert!(dialog.shows_image());
assert_eq!(dialog.preview_mode(), PreviewMode::BlackMatte);
}
+1
View File
@@ -3,6 +3,7 @@
mod adjust_editors;
mod adjust_tone;
mod blur_pins;
mod channels_delete;
mod color_range;
mod contour_field;
mod curve;
+6 -4
View File
@@ -118,9 +118,11 @@ pub(super) fn tab_strip(ui: &mut Ui, name: &'static str, titles: &[String], show
.kind(TabKind::Text)
.shown(shown)
.show_items(ui, &Titles(titles), &mut |key, _| Tab::new(titles[*key].clone()).id_salt(("tab", *key)));
strip.response.events.into_iter().find_map(|event| match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => keys.last().copied(),
_ => None,
strip.picked.or_else(|| {
strip.response.events.into_iter().find_map(|event| match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => keys.last().copied(),
_ => None,
})
})
}
@@ -137,7 +139,7 @@ fn app_tabs(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> Option<u
state.set_tab(None);
}
let shown = current.map_or(0, |i| i + 1);
let picked = Stack::new().enabled(!state.modal()).show(ui, |ui, _| tab_strip(ui, "shortcuts.tab", &titles, shown)).inner.flatten();
let picked = Stack::new().fill_width().enabled(!state.modal()).show(ui, |ui, _| tab_strip(ui, "shortcuts.tab", &titles, shown)).inner.flatten();
let shown = match picked {
Some(i) => {
state.set_tab(i.checked_sub(1).and_then(|k| ids.get(k).copied()));
+1
View File
@@ -5,3 +5,4 @@ mod lists;
mod recorder;
mod rows;
mod sets;
mod tabs;
+92
View File
@@ -0,0 +1,92 @@
//! The app's pages share the Keyboard Shortcuts dialog's width and navigation.
use craft_host::target::Os;
use craft_keymap::{Platform, Profiles};
use craft_menu::shortcuts::{Area, DialogState, DialogTab, ShortcutsDialog};
use craft_theme::ThemeId;
use craft_ui::contract::Role;
use craft_ui::runtime::egui::access::AccessTree;
use craft_ui::runtime::env::RootEnv;
use craft_ui::testing::{Fixture, Frames, pointer, trial};
use super::fixture;
fn dialog_at_125_percent(toolbar_label: &str) -> (Frames, impl FnMut(&mut egui::Ui) + '_) {
// Use the Windows test context and a 1600 × 1000 physical-pixel window at 125%.
let mut os = Fixture::new(|_| {});
os.os(Os::Windows);
let mut frames = Frames::over(os.ctx().clone());
frames.screen(egui::vec2(1280.0, 800.0));
frames.pixels_per_point(1.25);
let mut root = RootEnv::default();
root.set_theme(ThemeId::parse("craft.artcraft").unwrap());
frames.root(root);
let mut keys = fixture::keymap(Platform::Windows);
let mut state = DialogState::new();
let mut profiles = Profiles::default();
let builtins = fixture::builtins();
let options = fixture::options().with(|o| {
o.title = Some("Keyboard Shortcuts and Menus".into());
o.areas = Area::photoshop();
});
let show = move |ui: &mut egui::Ui| {
let mut tabs = [
DialogTab::new("menus", "Menus", |ui| {
ui.label("Menu item visibility");
false
}),
DialogTab::new("toolbar", toolbar_label, |ui| {
ui.label("Toolbar tool visibility");
false
}),
];
ShortcutsDialog::new(&mut keys).sets(&mut profiles, &builtins).options(&options).tabs(&mut tabs).show(ui, &mut state);
};
(frames, show)
}
fn tab_bounds(tree: &AccessTree, label: &str) -> egui::Rect {
let tab = tree.keys().into_iter().find(|&key| tree.role_of(key) == Some(Role::TAB) && tree.name_of(key) == Some(label));
tab.and_then(|key| tree.bounds_of(key)).unwrap_or_else(|| panic!("no tab labelled {label}"))
}
#[trial]
fn app_tabs_show_full_labels_at_125_percent_and_switch_pages() {
let (mut frames, mut show) = dialog_at_125_percent("Toolbar");
frames.idle(12, &mut show);
assert_eq!(frames.ctx.pixels_per_point(), 1.25);
let tree = frames.tree();
let tabs = ["Keyboard Shortcuts", "Menus", "Toolbar"].map(|label| {
let rect = tab_bounds(&tree, label);
let text = frames.texts().iter().find(|text| text.text == label).unwrap_or_else(|| panic!("no painted label {label}"));
assert!(!text.elided && text.clip.contains_rect(text.rect), "{label} is clipped: {text:?}");
rect
});
assert!(tabs.windows(2).all(|pair| pair[0].right() <= pair[1].left()));
for (label, page) in [("Menus", "Menu item visibility"), ("Toolbar", "Toolbar tool visibility")] {
// A page can change the dialog's bounds, so target the tab in the current frame.
frames.idle(2, &mut show);
let tab = tab_bounds(&frames.tree(), label);
pointer::click(&mut frames, tab.center(), &mut show);
assert!(frames.texts().iter().any(|text| text.text == page), "click should show {page}");
}
}
#[trial]
fn app_tabs_keep_overflow_when_the_labels_do_not_fit() {
let long_label = "Toolbar ".repeat(200);
let (mut frames, mut show) = dialog_at_125_percent(&long_label);
frames.idle(12, &mut show);
let tree = frames.tree();
let overflow = tree.keys().into_iter().find(|&key| tree.role_of(key) == Some(Role::BUTTON) && tree.name_of(key) == Some("More tabs"));
let overflow = overflow.and_then(|key| tree.bounds_of(key)).expect("oversized titles still have an overflow menu");
pointer::click(&mut frames, overflow.center(), &mut show);
let popup = frames.tree();
let hidden = popup.keys().into_iter().find(|&key| popup.name_of(key) == Some(long_label.as_str()));
let hidden = hidden.and_then(|key| popup.bounds_of(key)).expect("the hidden toolbar remains available");
pointer::click(&mut frames, hidden.center(), &mut show);
frames.idle(2, &mut show);
assert!(frames.texts().iter().any(|text| text.text == "Toolbar tool visibility"), "the overflow choice opens the Toolbar page");
}
+10 -5
View File
@@ -456,7 +456,7 @@ impl Outcome for CharacterControlsOutput {
/// for edit in out.edits { gestures.handle(&mut doc, edit, apply_to_selection) }
/// ```
///
/// - Fields fill two columns of the available width with a mark for a label (PhotoCraft's marks: "tT", "A↕", "VA",
/// - Fields fill two columns where they fit and stack in narrower panels. A mark serves as a label (PhotoCraft's marks: "tT", "A↕", "VA",
/// "↕T", "↔T", "Aª"); a drag on the mark scrubs the value. Size, leading, kerning and tracking have a preset menu in
/// the field (presets are shortcuts, not limits: any value in range can be typed). Ranges in points: size
/// 0.1–1296, leading 0.1–5000, baseline shift −1296–1296; tracking and kerning −1000–10000; scales 0–1000 %. The
@@ -553,6 +553,11 @@ impl<'a> CharacterControls<'a> {
let mut rested_family = None;
let mut requests = HostRequests::new();
// A short field needs room for its value, plus space for the mark and preset button.
let tokens = &env.tokens;
let field_width = tokens.size.length.short + 2.0 * tokens.size.icon.md;
let pair_width = 2.0 * field_width + tokens.space.gap.row;
let columns = if ui.available_width() < pair_width { &TWO_COLUMNS[..1] } else { &TWO_COLUMNS };
let shown = Stack::new().label(self.label).show(ui, |ui, _| {
#[cfg(feature = "font-picker")]
let family = family_field(ui, &words, values, families, picker.as_mut());
@@ -572,7 +577,7 @@ impl<'a> CharacterControls<'a> {
edits.extend(sliders.show(ui).edit.into_iter().map(|event| event.map(CharacterChange::Axes)));
}
Grid::new(&TWO_COLUMNS).fill_width().show(ui, |ui, _| {
Grid::new(columns).fill_width().show(ui, |ui, _| {
let size = LengthRow {
label: words.size.clone(),
side: mark(GlyphLabel::text("tT"), None, FieldLayout::Inside),
@@ -585,7 +590,7 @@ impl<'a> CharacterControls<'a> {
let side = mark(GlyphLabel::text("A↕"), Some(words.leading_hint.clone()), FieldLayout::Inside);
edits.extend(leading_row(&lengths, ui, &words, side, values.leading, values.size, &leading_presets));
});
Grid::new(&TWO_COLUMNS).fill_width().show(ui, |ui, _| {
Grid::new(columns).fill_width().show(ui, |ui, _| {
let event = lengths.kerning(
ui,
words.kerning.clone(),
@@ -606,7 +611,7 @@ impl<'a> CharacterControls<'a> {
let (event, _) = lengths.plain(ui, tracking);
edits.extend(number_change(event, CharacterChange::Tracking));
});
Grid::new(&TWO_COLUMNS).fill_width().show(ui, |ui, _| {
Grid::new(columns).fill_width().show(ui, |ui, _| {
let vertical = PlainRow {
label: words.vertical_scale.clone(),
side: mark(GlyphLabel::text("↕T"), None, FieldLayout::Inside),
@@ -628,7 +633,7 @@ impl<'a> CharacterControls<'a> {
let (event, _) = lengths.plain(ui, horizontal);
edits.extend(number_change(event, CharacterChange::HorizontalScale));
});
Grid::new(&TWO_COLUMNS).fill_width().show(ui, |ui, _| {
Grid::new(columns).fill_width().show(ui, |ui, _| {
let shift = LengthRow {
label: words.baseline_shift.clone(),
side: mark(GlyphLabel::text("Aª"), None, FieldLayout::Inside),
+31
View File
@@ -0,0 +1,31 @@
use craft_text::ui::character::{CharacterControls, CharacterValues, Kerning, Leading};
use craft_ui::testing::{Fixture, trial};
use egui::vec2;
#[trial]
fn character_fields_are_readable_when_the_panel_is_narrowed() {
let mut fixture = Fixture::new(|ui| {
let values =
CharacterValues { size: Some(144.0), leading: Some(Leading::Auto), kerning: Some(Kerning::Metrics), ..CharacterValues::default() };
CharacterControls::new("Character", &values, &[], &[]).show(ui);
});
for (step, width) in [402.0, 222.0, 402.0].into_iter().enumerate() {
fixture.room(vec2(width, 500.0)).settle();
let size = fixture.by_label("Font size").expect("the font-size field is shown").rect;
let leading = fixture.by_label("Leading").expect("the leading field is shown").rect;
for value in ["144", "172.8", "Metrics"] {
let text = fixture
.texts()
.iter()
.find(|run| run.text == value)
.unwrap_or_else(|| panic!("{value} is painted at {width} pt (resize step {step})"));
assert!(!text.elided && text.clip.expand(0.5).contains_rect(text.rect), "{value} fits inside its field at {width} pt: {text:?}");
}
if width == 222.0 {
assert!(size.bottom() <= leading.top(), "the two fields stack at {width} pt");
} else {
assert!(size.right() <= leading.left(), "the two fields sit side by side at {width} pt");
}
}
}
+2
View File
@@ -14,3 +14,5 @@ mod ruler;
mod style_options;
mod style_panel;
mod tabs;
mod character;
+192 -26
View File
@@ -1,6 +1,7 @@
//! `CanvasScrollbars`: the scroll bars of a canvas (20.6): a horizontal bar along the bottom of the view and a vertical
//! one along the right, always shown, in the docked look (`ScrollBarKind::Docked`): the thumb has the track's whole
//! thickness at rest and under the pointer. The thumb is the visible fraction of
//! thickness at rest and under the pointer. Document chrome uses inset thumbs, step buttons and a corner.
//! The thumb is the visible fraction of
//! the scrollable extent (the document, plus wherever the view has been scrolled past it); drag it to scroll, or press
//! the track to page by one screenful. With overscroll on, a document smaller than the window can also be scrolled from
//! one edge of the window to the other. With overscroll off the app clamps the view before it draws
@@ -16,22 +17,32 @@ use super::words::CanvasWords;
use crate::contract::overlay::{Anchor, Place};
use crate::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Name, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi,
PartsCx, Pointer as _, Props as _, Role, Show as _, THUMB, WordSetCx as _,
PartsCx, Pointer as _, Props as _, Remember as _, Role, Show as _, THUMB, WordSetCx as _,
};
use crate::display::Text;
use crate::primitives::{Draw, PaintShape, ScrollBar, StrokeWidth};
use crate::runtime::access::Numeric;
use crate::runtime::commands::FireSource;
use crate::runtime::env::Label;
use crate::runtime::focus::KeyUse;
use crate::style::{ComponentStyle, ScrollBarKind, ScrollBarLook, StyleCx};
use crate::runtime::frame;
use crate::style::{ComponentStyle, ScrollBarKind, ScrollBarLook, Stateful, StyleColor, StyleCx};
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_behavior::overlay::{Align, Side};
use craft_behavior::scroll::ScrollSpan;
use craft_behavior::{Axis, CanvasView, Metrics, PartKey, PartRef, PressPhase};
use egui::{Pos2, Rect, Response, Vec2};
use craft_behavior::{Axis, CanvasView, Metrics, PartKey, PartRef, PressPhase, Sense};
use egui::{CornerRadius, Rect, Response, Vec2, pos2, vec2};
use std::ops::{Deref, Range};
const HORIZONTAL: PartKey = PartKey::new("horizontal");
const CORNER: PartKey = PartKey::new("corner");
const VERTICAL: PartKey = PartKey::new("vertical");
const START_ARROW: u64 = 1;
const END_ARROW: u64 = 2;
/// Distance of a line step in device pixels, like the canvas's scroll wheel.
const ARROW_STEP_PIXELS: f64 = 16.0;
const ARROW_HOLD_DELAY: f64 = 0.4;
const ARROW_HOLD_INTERVAL: f64 = 0.06;
/// The popup of the tip beside a dragged vertical thumb.
const TIP: &str = "tip";
@@ -48,6 +59,13 @@ pub struct ScrollbarsStyle {
#[style(metrics)]
metrics: Metrics,
look: ScrollBarLook,
document: Option<DocumentLook>,
}
#[derive(Clone, Debug, PartialEq)]
struct DocumentLook {
corner: StyleColor,
arrow: Stateful<StyleColor>,
}
/// One axis of the view, in document units counted from the document's start on that axis.
@@ -88,13 +106,96 @@ impl Span {
/// One bar: where it lies and what it scrolls.
struct Bar {
rect: Rect,
track: Rect,
span: ScrollSpan,
}
impl Bar {
fn new(rect: Rect, axis: Axis, span: ScrollSpan, document_chrome: bool) -> Self {
let mut track = rect;
if document_chrome {
let cap = if axis == Axis::X { rect.height() } else { rect.width() };
let length = if axis == Axis::X { rect.width() } else { rect.height() };
if length > 2.0 * cap && cap > 0.0 {
let inset = if axis == Axis::X { vec2(cap, 0.0) } else { vec2(0.0, cap) };
track = rect.shrink2(inset);
}
}
Self { rect, track, span }
}
fn arrows(&self, key: PartKey, axis: Axis) -> impl Iterator<Item = (PartRef, Rect, bool)> {
(self.track != self.rect)
.then(|| {
let (before, after) = if axis == Axis::X {
(pos2(self.track.left(), self.rect.bottom()), pos2(self.track.right(), self.rect.top()))
} else {
(pos2(self.rect.right(), self.track.top()), pos2(self.rect.left(), self.track.bottom()))
};
[
(key.at(START_ARROW), Rect::from_min_max(self.rect.min, before), false),
(key.at(END_ARROW), Rect::from_min_max(after, self.rect.max), true),
]
})
.into_iter()
.flatten()
}
}
/// The bars of a view over a document, in the order horizontal, vertical.
struct Bars {
horizontal: Option<Bar>,
vertical: Option<Bar>,
corner: Option<Rect>,
}
#[derive(Clone, Default)]
struct ArrowRepeat {
part: Option<PartRef>,
next: f64,
}
fn arrow_pressed(cx: &mut Cx<'_, CanvasScrollbars<'_>>, part: PartRef, rect: Rect) -> bool {
if matches!(cx.part_activated(part), Some(FireSource::Access | FireSource::Key)) {
return true;
}
let phase = cx.part(part).press.phase;
if !matches!(phase, PressPhase::Down { .. } | PressPhase::Held { .. }) {
return false;
}
let ctx = cx.response.ctx.clone();
let now = frame::clock(&ctx);
match phase {
PressPhase::Down { .. } => {
*cx.memory::<ArrowRepeat>() = ArrowRepeat { part: Some(part), next: now + ARROW_HOLD_DELAY };
frame::request_repaint_after(&ctx, ARROW_HOLD_DELAY);
true
}
PressPhase::Held { pos, .. } if rect.contains(pos) => {
let repeat = cx.memory::<ArrowRepeat>();
if repeat.part != Some(part) {
return false;
}
let due = now >= repeat.next;
if due {
repeat.next = now + ARROW_HOLD_INTERVAL;
}
frame::request_repaint_after(&ctx, repeat.next - now);
due
}
_ => false,
}
}
fn paint_arrow(draw: &Draw<'_>, rect: Rect, axis: Axis, after: bool, color: StyleColor) {
let size = rect.width().min(rect.height()) / 4.0;
let sign = if after { 1.0 } else { -1.0 };
let point = |along, across| {
let along = along * sign;
rect.center() + if axis == Axis::X { vec2(along, across) } else { vec2(across, along) }
};
let path = PaintShape::Path(vec![point(-size * 0.5, -size), point(size * 0.5, 0.0), point(-size * 0.5, size)]);
draw.stroke(&path, StrokeWidth::Thin, color);
}
/// How the document's x axis runs on screen: with the view flipped, backwards.
@@ -108,16 +209,23 @@ fn aspect(view: &CanvasView) -> f64 {
impl Bars {
/// The bars inside `rect` (bottom and right edges), `width` thick, for `view` over the document `doc`.
fn of(view: &CanvasView, doc: DocRect, overscroll: bool, horizontal: bool, rect: Rect, width: f32) -> Bars {
fn of(view: &CanvasView, doc: DocRect, overscroll: bool, horizontal: bool, rect: Rect, style: &ScrollbarsStyle) -> Bars {
let document_chrome = style.document.is_some();
let mut width = style.look.thickness;
if document_chrome {
width = width.min(rect.width().max(0.0)).min(rect.height().max(0.0));
}
let x = Span::of(doc.width(), along_x(view, doc.width(), view.center.x - doc.x0), f64::from(view.rect.width()) / aspect(view), view.zoom)
.filter(|_| horizontal);
let y = Span::of(doc.height(), view.center.y - doc.y0, f64::from(view.rect.height()), view.zoom);
let right = if y.is_some() { rect.right() - width } else { rect.right() };
let bottom = if x.is_some() { rect.bottom() - width } else { rect.bottom() };
let bar = |span: Option<Span>, rect: Rect| span.map(|span| Bar { rect, span: span.scroll(overscroll) });
let corner = (document_chrome && x.is_some() && y.is_some()).then(|| Rect::from_min_max(pos2(right, bottom), rect.max));
let bar = |span: Option<Span>, axis, rect| span.map(|span| Bar::new(rect, axis, span.scroll(overscroll), document_chrome));
Bars {
horizontal: bar(x, Rect::from_min_max(Pos2::new(rect.left(), bottom), Pos2::new(right, rect.bottom()))),
vertical: bar(y, Rect::from_min_max(Pos2::new(right, rect.top()), Pos2::new(rect.right(), bottom))),
horizontal: bar(x, Axis::X, Rect::from_min_max(pos2(rect.left(), bottom), pos2(right, rect.bottom()))),
vertical: bar(y, Axis::Y, Rect::from_min_max(pos2(right, rect.top()), pos2(rect.right(), bottom))),
corner,
}
}
@@ -182,6 +290,10 @@ pub struct CanvasScrollbars<'a> {
/// horizontal bar or corner is shown.
#[prop(flag)]
vertical_only: bool,
/// Wider bars with inset thumbs, step arrows and a corner for a document window.
#[prop(flag)]
#[style_key]
document_chrome: bool,
/// While the vertical thumb drags, the bars show the tip this builds from the view as the drag moved it, beside the
/// thumb on the reading-start side.
#[prop]
@@ -191,7 +303,8 @@ pub struct CanvasScrollbars<'a> {
impl<'a> CanvasScrollbars<'a> {
/// Scroll bars named `label` that edit `view`, a view over the document `document` (document units).
pub fn new(label: impl Into<Label>, view: Bind<'a, CanvasView>, document: DocRect) -> Self {
CanvasScrollbars { common: Common::new(), view, document, overscroll: false, vertical_only: false, tip: None }.label(label)
CanvasScrollbars { common: Common::new(), view, document, overscroll: false, vertical_only: false, document_chrome: false, tip: None }
.label(label)
}
/// Applies overscroll off to `view` over the document `doc`: the view can't leave the document's edges, and a
@@ -240,8 +353,8 @@ impl<'a> CanvasScrollbars<'a> {
changed
}
fn bars(&self, view: &CanvasView, rect: Rect, width: f32) -> Bars {
Bars::of(view, self.document, self.overscroll, !self.vertical_only, rect, width)
fn bars(&self, view: &CanvasView, rect: Rect, style: &ScrollbarsStyle) -> Bars {
Bars::of(view, self.document, self.overscroll, !self.vertical_only, rect, style)
}
}
@@ -251,8 +364,15 @@ impl Component for CanvasScrollbars<'_> {
type Style = ScrollbarsStyle;
type Output = CanvasScrollbarsOutput;
fn style(cx: &StyleCx<'_>, _: CanvasScrollbarsStyleKey) -> ScrollbarsStyle {
ScrollbarsStyle { metrics: Metrics::new(), look: cx.scroll_bar_of(ScrollBarKind::Docked) }
fn style(cx: &StyleCx<'_>, key: CanvasScrollbarsStyleKey) -> ScrollbarsStyle {
let mut look = cx.scroll_bar_of(ScrollBarKind::Docked);
let document = key.document_chrome.then(|| {
let color = &cx.tokens.color;
look.thickness = cx.tokens.size.icon.md;
look.track = Stateful::new(cx.color(color.surface.sunken));
DocumentLook { corner: cx.color(color.surface.panel), arrow: cx.quiet_ink() }
});
ScrollbarsStyle { metrics: Metrics::new(), look, document }
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
@@ -266,9 +386,15 @@ impl Component for CanvasScrollbars<'_> {
/// The bars: `PartsCx::scroll` runs the thumb drag and the page press in the pipeline.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let Some(view) = cx.value().copied() else { return };
let bars = self.bars(&view, rect, cx.style.look.thickness);
let bars = self.bars(&view, rect, cx.style);
for (key, axis, bar) in bars.each() {
cx.scroll(key, bar.rect, axis, bar.span.clone());
cx.scroll(key, bar.track, axis, bar.span.clone());
for (part, rect, _) in bar.arrows(key, axis) {
cx.part(part, rect).sense(Sense::CLICK | Sense::FOCUS).focusable();
}
}
if let Some(corner) = bars.corner {
cx.part(CORNER, corner).sense(Sense::CLICK).pointer_only("the corner only reserves space between the two scroll bars");
}
}
@@ -281,8 +407,21 @@ impl Component for CanvasScrollbars<'_> {
tip.close(cx);
}
let Some(view) = cx.value().copied() else { return };
let bars = self.bars(&view, cx.rect, cx.style.look.thickness);
for (key, axis, _) in bars.each() {
let bars = self.bars(&view, cx.rect, cx.style);
for (key, axis, bar) in bars.each() {
for (part, rect, after) in bar.arrows(key, axis) {
if arrow_pressed(cx, part, rect) {
let scale = if axis == Axis::X { aspect(&view) } else { 1.0 };
let pixel_zoom = view.zoom * scale * f64::from(cx.response.ctx.pixels_per_point());
let toward_end = after != (axis == Axis::X && cx.flow.is_rtl());
let sign = if toward_end { 1.0 } else { -1.0 };
let range = craft_behavior::scroll::shifted(&bar.span, sign * ARROW_STEP_PIXELS / pixel_zoom);
let next = moved(&view, self.document, axis, &range);
if next != view {
cx.set(next);
}
}
}
let phase = cx.part(thumb_of(key)).press.phase;
match phase {
PressPhase::DragStart { .. } => cx.begin(),
@@ -315,17 +454,34 @@ impl Component for CanvasScrollbars<'_> {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let Some(view) = cx.value().copied() else { return };
let style = cx.style;
let bars = self.bars(&view, cx.rect, style.look.thickness);
let bars = self.bars(&view, cx.rect, style);
let draw = ui.draw();
let rtl = cx.flow.is_rtl();
let fill = |rect, color| draw.fill(&PaintShape::Rect(rect, CornerRadius::ZERO), color);
for (key, axis, bar) in bars.each() {
draw.scroll_bar(&style.look, bar.rect, axis, cx.flow.is_rtl(), &bar.span, &cx.scroll_bar_state(key));
let state = cx.scroll_bar_state(key);
if let Some(look) = &style.document {
fill(bar.rect, state.resolve(&style.look.track));
let inset = if axis == Axis::X { vec2(0.0, bar.rect.height() / 8.0) } else { vec2(bar.rect.width() / 8.0, 0.0) };
let thumb = ScrollBar::thumb(style.look.min_thumb, bar.track, axis, rtl, &bar.span).shrink2(inset);
fill(thumb, state.resolve(&style.look.thumb));
for (part, rect, after) in bar.arrows(key, axis) {
let color = cx.part_state(part).resolve(&look.arrow);
paint_arrow(&draw, rect, axis, after, color);
}
} else {
draw.scroll_bar(&style.look, bar.track, axis, rtl, &bar.span, &state);
}
}
if let (Some(corner), Some(look)) = (bars.corner, &style.document) {
fill(corner, look.corner);
}
}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let Some(view) = cx.value().copied() else { return };
let words = cx.words::<CanvasWords>();
let bars = self.bars(&view, cx.rect, cx.style.look.thickness);
let bars = self.bars(&view, cx.rect, cx.style);
for (key, axis, bar) in bars.each() {
let name = if axis == Axis::X { &words.scroll_horizontal } else { &words.scroll_vertical };
let room = (bar.span.content.end - bar.span.content.start - (bar.span.visible.end - bar.span.visible.start)).max(0.0);
@@ -333,15 +489,25 @@ impl Component for CanvasScrollbars<'_> {
let node = access.node(key, Role::SCROLL_BAR);
node.name = Name::Text(name.as_str().to_owned());
node.numeric = Some(Numeric::new(position, 0.0..=room));
for (part, _, after) in bar.arrows(key, axis) {
let name = match (axis, after) {
(Axis::X, false) => &words.scroll_left,
(Axis::X, true) => &words.scroll_right,
(_, false) => &words.scroll_up,
(_, true) => &words.scroll_down,
};
access.node(part, Role::BUTTON).name = Name::Text(name.as_str().to_owned());
}
}
}
fn finish(self, cx: Cx<'_, Self>) -> CanvasScrollbarsOutput {
let over = [HORIZONTAL, VERTICAL].into_iter().any(|key| {
[PartRef::from(key), thumb_of(key)]
.into_iter()
.any(|part| cx.part_if_declared(part).is_some_and(|result| result.hovered || result.press.phase.is_press()))
});
let is_over = |part| cx.part_if_declared(part).is_some_and(|result| result.hovered || result.press.phase.is_press());
let over = is_over(PartRef::from(CORNER))
|| [HORIZONTAL, VERTICAL].into_iter().any(|key| {
let arrows = self.document_chrome.then_some([key.at(START_ARROW), key.at(END_ARROW)]);
[PartRef::from(key), thumb_of(key)].into_iter().chain(arrows.into_iter().flatten()).any(is_over)
});
let dragging = thumb_dragging(&cx);
CanvasScrollbarsOutput { view: cx.edit_response(), over, dragging }
}
+4
View File
@@ -27,6 +27,10 @@ craft_ui::words! {
scroll_horizontal: "canvasScrollbars.horizontal" = "Horizontal scroll bar";
scroll_vertical: "canvasScrollbars.vertical" = "Vertical scroll bar";
scroll_left: "canvasScrollbars.left" = "Scroll left";
scroll_right: "canvasScrollbars.right" = "Scroll right";
scroll_up: "canvasScrollbars.up" = "Scroll up";
scroll_down: "canvasScrollbars.down" = "Scroll down";
navigate_zoom: "navigateBar.zoom" = "Zoom";
navigate_direction: "navigateBar.direction" = "Zoom direction";
+110 -5
View File
@@ -1,16 +1,17 @@
//! `CanvasScrollbars`: the clamp of the view and the bars' drag and page press.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_behavior::kurbo::{Point, Rect as DocRect, Size};
use craft_behavior::{Axis, CanvasView};
use craft_ui::canvas::{Canvas, CanvasScrollbars};
use craft_ui::canvas::{Canvas, CanvasScrollbars, NavigationOptions, Rulers, canvas_space};
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::runtime::access::Role;
use craft_ui::runtime::env::Label;
use craft_ui::testing::input::slop;
use craft_ui::testing::{Fixture, trial};
use egui::{Pos2, Rect, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Pos2, Rect, Shape, Vec2, pos2, vec2};
/// The view's rect in the fixture, in points.
const VIEW: Rect = Rect::from_min_max(Pos2::new(0.0, 0.0), Pos2::new(400.0, 300.0));
@@ -55,6 +56,110 @@ fn overscroll_off_below_fit_keeps_the_image_centred() {
assert!((image.center().y - VIEW.center().y).abs() < TOLERANCE, "the short axis is centred: {image:?}");
}
const FITTING_DOCUMENT: Size = Size::new(400.0, 300.0);
const DOCUMENT_WINDOW: Rect = Rect::from_min_max(Pos2::new(12.0, 12.0), Pos2::new(732.0, 512.0));
fn document_scrollbars() -> (Fixture, Rc<Cell<CanvasView>>, Rc<Cell<bool>>) {
let over = Rc::new(Cell::new(false));
let observed_over = Rc::clone(&over);
let view = Rc::new(Cell::new(CanvasView::new(DOCUMENT_WINDOW, Point::new(200.0, 150.0), 1.0)));
let observed = Rc::clone(&view);
let mut fixture = Fixture::new(move |ui| {
let mut navigation = NavigationOptions::default();
navigation.overscroll = true;
let mut zero = Point::ZERO;
let rulers = Rulers::new("Rulers", Bind::bound(&mut zero));
let mut next = observed.get();
Canvas::new("Document").document(FITTING_DOCUMENT).view(next).navigation(navigation).with_rulers(Some(rulers)).show_at(
ui,
DOCUMENT_WINDOW,
|_, body| {
if let Some(space) = canvas_space(&body.env) {
next = space.view;
}
},
);
let doc = DocRect::from_origin_size(Point::ZERO, FITTING_DOCUMENT);
let bars = CanvasScrollbars::new("Scroll bars", Bind::bound(&mut next), doc).overscroll(true).document_chrome().show_at(ui, DOCUMENT_WINDOW);
observed_over.set(bars.over);
observed.set(next);
});
fixture.room(vec2(760.0, 560.0)).settle();
(fixture, view, over)
}
/// #15529: the document bars leave room for arrows and a corner, and put a thinner thumb inside each track.
#[trial]
fn document_bars_show_arrows_and_an_inset_thumb_for_a_fitting_image() {
let (mut fixture, view, _) = document_scrollbars();
let horizontal = fixture.by_label("Horizontal scroll bar").expect("the horizontal bar").rect;
let vertical = fixture.by_label("Vertical scroll bar").expect("the vertical bar").rect;
assert!((horizontal.height() - 16.0).abs() < TOLERANCE, "horizontal track: {horizontal:?}");
assert!((vertical.width() - 16.0).abs() < TOLERANCE, "vertical track: {vertical:?}");
let left = fixture.by_label("Scroll left").expect("the left arrow").rect;
let right = fixture.by_label("Scroll right").expect("the right arrow").rect;
let up = fixture.by_label("Scroll up").expect("the up arrow").rect;
let down = fixture.by_label("Scroll down").expect("the down arrow").rect;
assert!((left.right() - horizontal.left()).abs() < TOLERANCE && (right.left() - horizontal.right()).abs() < TOLERANCE);
assert!((up.bottom() - vertical.top()).abs() < TOLERANCE && (down.top() - vertical.bottom()).abs() < TOLERANCE);
assert!((up.top() - DOCUMENT_WINDOW.top()).abs() < TOLERANCE, "the bar starts beside the ruler row");
assert!(up.top() < view.get().rect.top(), "the visible document starts below the ruler row");
let corner = Rect::from_min_size(pos2(right.right(), down.bottom()), Vec2::splat(16.0));
let shapes = fixture.frame_shapes();
assert!(shapes.iter().any(|shape| matches!(shape, Shape::Rect(paint) if paint.rect == corner && paint.fill.a() > 0)), "the corner is painted");
assert!(
shapes.iter().any(|shape| matches!(shape, Shape::Rect(paint)
if horizontal.contains_rect(paint.rect)
&& (paint.rect.top() - horizontal.top() - 2.0).abs() < TOLERANCE
&& (paint.rect.height() - 12.0).abs() < TOLERANCE
&& paint.rect.width() < horizontal.width()
&& paint.fill.a() > 0)),
"the fitting document's thumb is shorter than the track and inset on both sides",
);
}
/// #15529: a press is one small step, a held press repeats, and the rest of the track still pages.
#[trial]
fn a_document_scroll_arrow_steps_and_repeats_while_its_track_pages() {
let (mut fixture, view, _) = document_scrollbars();
let start = view.get().center;
let arrow = fixture.by_label("Scroll right").expect("the right arrow").center();
fixture.frame(vec![pointer::moved(arrow)]).frame(vec![pointer::press(arrow)]);
let stepped = view.get().center;
assert!((stepped.x - start.x - 16.0).abs() < f64::from(TOLERANCE), "the arrow moves 16 screen pixels at 100%: {start:?} -> {stepped:?}");
assert_eq!(stepped.y, start.y);
fixture.advance(0.05).frame(vec![]);
assert_eq!(view.get().center, stepped, "the first step precedes the hold delay");
fixture.advance(0.5).frame(vec![]);
let repeated = view.get().center;
assert!(repeated.x > stepped.x && repeated.y == start.y, "the held arrow repeats on its own axis");
fixture.frame(vec![pointer::release(arrow)]).advance(1.0).frame(vec![]);
assert_eq!(view.get().center, repeated, "releasing the arrow stops the repeat");
let track = fixture.by_label("Horizontal scroll bar").expect("the horizontal track").rect;
fixture.click_at(pos2(track.right() - 8.0, track.center().y));
fixture.settle();
assert!(view.get().center.x > repeated.x + 16.0, "the track still pages instead of stepping");
}
#[trial]
fn the_scrollbar_corner_keeps_pointer_presses_off_the_canvas() {
let (mut fixture, view, over) = document_scrollbars();
let right = fixture.by_label("Scroll right").expect("the right arrow").rect;
let down = fixture.by_label("Scroll down").expect("the down arrow").rect;
let corner = pos2(right.right() + 4.0, down.bottom() + 4.0);
fixture.frame(vec![pointer::moved(corner)]);
assert!(over.get(), "the corner belongs to the scrollbars");
let center = view.get().center;
fixture.frame(vec![pointer::press(corner)]);
assert!(over.get(), "a press on the corner must not reach the document");
assert_eq!(view.get().center, center, "the corner never scrolls");
fixture.frame(vec![pointer::release(corner)]).frame(vec![pointer::moved(DOCUMENT_WINDOW.center())]);
assert!(!over.get(), "the document area still receives pointer input");
}
/// The document the bar trials scroll: ten times the view's height, so a page is a third of a thumb's travel or less.
const DOCUMENT: DocRect = DocRect::new(0.0, 0.0, 1000.0, 1000.0);
@@ -14,6 +14,8 @@ use crate::runtime::requests::{ColorRequest, HostAnswer};
use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field};
use crate::contract::Show as _;
use crate::display::Divider;
use crate::layout_components::{Grid, Stack};
use crate::patterns::presets::{GroupPath, NamedPresetEvent, PresetLibrary, PresetWords as LibraryWords};
@@ -376,8 +378,8 @@ impl Outcome for NewDocumentOutput {
}
}
/// The columns of the body: the cards take the room the details column leaves.
const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::Content];
/// Leave most of the dialog to the presets and keep the details column at a consistent share of the width.
const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(2.0), ColumnWidth::fill(1.0)];
/// The body of the dialog: the columns, then what they asked for.
fn body(ui: &mut Ui, form: &mut FormCx<'_, '_>, values: &mut DocumentOptions, shared: &Shared<'_>) -> bool {
@@ -421,6 +423,8 @@ fn body(ui: &mut Ui, form: &mut FormCx<'_, '_>, values: &mut DocumentOptions, sh
let read = Read { setup, recents: &recents, library: &library, words, preset_words, library_words, units };
let mut left = Left::default();
let mut right = Right::default();
cards::tabs(ui, &session, &read, &mut left);
Divider::horizontal().show(ui);
Grid::new(&COLUMNS).fill().show(ui, |ui, _| {
Stack::new().fill().show(ui, |ui, _| {
cards::show(ui, &session, values, &read, &mut left);
@@ -7,13 +7,13 @@ use crate::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _,
use crate::display::{Shade, Text};
use crate::list::{List, ListRow, ThumbAspect};
use crate::patterns::presets::PresetId;
use crate::primitives::{ContentPainterCx, PaintShape};
use crate::runtime::env::{Label, UnitKind};
use crate::primitives::{ContentPainterCx, StrokeWidth};
use crate::runtime::env::{Env, Label, UnitKind};
use crate::style::TypeRole;
use crate::tabs::{Tab, TabKind, TabStrip};
use crate::tile_grid::{Tile, TileGrid};
use craft_behavior::{DisplayOrder, ItemSource, Selection, SelectionChange, keyed};
use egui::{CornerRadius, Rect, Ui, vec2};
use egui::{CornerRadius, Rect, Stroke, StrokeKind, Ui, vec2};
use std::borrow::Cow;
use std::cell::Cell;
@@ -115,8 +115,8 @@ impl ItemSource<usize> for CardList<'_> {}
/// The columns of preset cards the grid holds: the dialog's left side is as wide as they are.
const CARD_COLUMNS: usize = 3;
/// Shows the tabs and what the open tab lists, and reports the tab and the card the user picked.
pub(super) fn show(ui: &mut Ui, session: &Session, values: &DocumentOptions, read: &Read<'_>, left: &mut Left) {
/// Shows the full-width category strip above the two columns.
pub(super) fn tabs(ui: &mut Ui, session: &Session, read: &Read<'_>, left: &mut Left) {
let (setup, words) = (read.setup, read.words);
let tabs: Vec<TabId> =
std::iter::once(TabId::Recent).chain((0..setup.categories.len()).map(TabId::Category)).chain(std::iter::once(TabId::Saved)).collect();
@@ -132,7 +132,11 @@ pub(super) fn show(ui: &mut Ui, session: &Session, values: &DocumentOptions, rea
left.tab = Some(*tab);
}
}
}
/// Shows the cards or saved presets in the category picked in this pass.
pub(super) fn show(ui: &mut Ui, session: &Session, values: &DocumentOptions, read: &Read<'_>, left: &mut Left) {
let words = read.words;
let tab = left.tab.unwrap_or(session.tab);
let cards = cards_of(tab, session, values, read);
let selected = if tab == session.tab { selected_of(tab, session, values, &cards) } else { None };
@@ -166,9 +170,12 @@ pub(super) fn show(ui: &mut Ui, session: &Session, values: &DocumentOptions, rea
}
} else {
let count = read.units.number(cards.len() as f64, 0..=0);
Text::new(words.presets_heading.fill(&[("n", &count)])).role(TypeRole::Label).shade(Shade::Muted).show(ui);
let heading = Label::from(words.presets_heading.fill(&[("n", &count)]));
Text::new(Env::of(ui).view().resolve(&heading).as_str().to_uppercase()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
let shown = TileGrid::<usize>::new(words.cards.clone())
.card_columns(CARD_COLUMNS)
.card()
.aspect(2.0)
.select(SelectMode::Single)
.detail_line()
.rows_stamp(stamp)
@@ -354,22 +361,25 @@ fn tile_of(card: &Card) -> Tile<'static> {
let aspect = card.aspect;
let tile = Tile::new(card.title.clone())
.detail(card.line.clone())
.thumb(ThumbAspect::SQUARE, move |painter: &ContentPainterCx<'_>, rect: Rect| paint_page(painter, rect, aspect));
.flat_thumbnail()
.thumb(ThumbAspect::new(2, 1), move |painter: &ContentPainterCx<'_>, rect: Rect| paint_page(painter, rect, aspect));
match &card.detail {
Some(detail) => tile.tooltip(detail.clone()),
None => tile,
}
}
/// The page outline in the picture: a well, and the page's outline at its aspect inside it.
/// A page icon inside the tile's picture, in content ink so the tile alone draws the selection ring.
fn paint_page(painter: &ContentPainterCx<'_>, picture: Rect, (width, height): (u32, u32)) {
let well = painter.plot_frame(picture);
painter.outline(&PaintShape::Rect(page_rect(well, width, height), CornerRadius::ZERO));
let page = page_rect(picture, width, height);
let stroke = Stroke::new(painter.stroke_width(StrokeWidth::Thin), painter.ink());
painter.painter.rect_stroke(page, CornerRadius::ZERO, stroke, StrokeKind::Inside);
}
/// The largest rect of the page's aspect that fits `room`, centred in it.
/// The page's aspect inside `room`, capped at the 30-point size of the original outline.
fn page_rect(room: Rect, width: u32, height: u32) -> Rect {
const PAGE_SIDE: f32 = 30.0;
let (width, height) = (width.max(1) as f32, height.max(1) as f32);
let scale = (room.width() / width).min(room.height() / height);
let scale = (room.width().min(PAGE_SIDE) / width).min(room.height().min(PAGE_SIDE) / height);
Rect::from_center_size(room.center(), vec2(width * scale, height * scale))
}
@@ -5,12 +5,12 @@ use super::presets::{
BackgroundContents, ColorMode, DocumentOptions, MAX_NAME, MAX_SAVED, Orientation, PIXEL_ASPECTS, RESOLUTION_UNITS, SIZE_UNITS, SQUARE_PIXELS,
};
use super::{NewDocumentWords, Read, Session, background_rgb, depth_label, mode_label};
use crate::buttons::{Button, IconButton};
use crate::buttons::Button;
use crate::choice::{Checkbox, Segmented, Swatch};
use crate::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Validity, clicked};
use crate::contract::{Bind, Entry, FieldLayout, Gap, Props as _, Show as _, ShowContainer as _, Sizing, Validity, clicked};
use crate::display::{Shade, Text};
use crate::form::{Field, FieldGroup};
use crate::layout_components::Row;
use crate::layout_components::{Grid, Row};
use crate::patterns::form_dialogs::LinkedSize;
use crate::patterns::presets::{PresetError, PresetLibrary};
use crate::pickers::{Select, UnitSelect};
@@ -18,8 +18,8 @@ use crate::runtime::env::{Env, Label, Message, UnitKind};
use crate::runtime::focus::{self, FocusTarget};
use crate::runtime::words::CommonWords;
use crate::style::TypeRole;
use crate::text::TextField;
use craft_behavior::{EditEvent, EditEvents, IconId, PixelSize};
use crate::text::{NumberField, TextField};
use craft_behavior::{ColumnWidth, EditEvent, EditEvents, IconId, NumberCodec, PixelSize};
use craft_theme::Srgba;
use egui::Ui;
@@ -97,7 +97,10 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti
let size_units = unit_entries(read, &SIZE_UNITS);
let resolution_units = unit_entries(read, &RESOLUTION_UNITS);
let orientations = [Entry::new(Orientation::Portrait, words.portrait.clone()), Entry::new(Orientation::Landscape, words.landscape.clone())];
let orientations = [
Entry::new(Orientation::Portrait, words.portrait.clone()).icon(IconId::new("orientation_portrait")),
Entry::new(Orientation::Landscape, words.landscape.clone()).icon(IconId::new("orientation_landscape")),
];
let modes = ColorMode::ALL.map(|mode| Entry::new(mode, mode_label(words, mode).clone()));
let depths: Vec<_> = values.color_mode.depths().iter().map(|&depth| Entry::new(depth, depth_label(words, depth).clone())).collect();
let working = setup.profiles.iter().find(|profiles| profiles.mode == values.color_mode);
@@ -120,63 +123,69 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti
PIXEL_ASPECTS.iter().map(|(id, _)| Entry::new((*id).to_owned(), pixel_aspect_label(words, id).clone())).collect();
pixel_aspects.extend(setup.custom_pixel_aspects.iter().map(|(id, name)| Entry::new(id.clone(), name.clone())));
Text::new(words.preset_details.clone()).role(TypeRole::Label).shade(Shade::Muted).show(ui);
FieldGroup::new(words.preset_details.clone()).show(ui, |ui, _| {
Field::new(words.name.clone()).id_salt("name").show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
let shown = TextField::new(words.name.clone(), Bind::given(values.name.clone())).limit(MAX_NAME).select_on_focus().show(ui);
if let Some(name) = shown.value().cloned() {
values.name = name;
}
if std::mem::take(&mut session.focus_name) {
focus::request(ui.ctx(), FocusTarget::Id(shown.response.id));
}
let save = IconButton::new(IconId::new("save"))
.label(words.save_preset_title.clone())
.tooltip(words.save_preset_title.clone())
.id_salt("save-preset")
.show(ui);
if clicked(&save) {
session.naming = Some(proposed_name(read));
session.name_tried = false;
session.focus_preset_name = true;
}
});
Text::new(Env::of(ui).view().resolve(&words.preset_details).as_str().to_uppercase()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
FieldGroup::new(words.preset_details.clone()).gap(Gap::Tight).show(ui, |ui, _| {
Field::new(words.name.clone()).layout(FieldLayout::Above).id_salt("name").show(ui, |ui, _| {
let shown = TextField::new(words.name.clone(), Bind::given(values.name.clone())).limit(MAX_NAME).select_on_focus().show(ui);
if let Some(name) = shown.value().cloned() {
values.name = name;
}
if std::mem::take(&mut session.focus_name) {
focus::request(ui.ctx(), FocusTarget::Id(shown.response.id));
}
});
for side in [Side::Width, Side::Height] {
Field::new(side.name(words).clone()).id_salt(side.key()).show(ui, |ui, _| {
let dimension = |ui: &mut Ui, session: &mut Session, side: Side| {
Field::new(side.name(words).clone()).layout(FieldLayout::Above).id_salt(side.key()).show(ui, |ui, _| {
let (value, range) = match side {
Side::Width => (session.size.width(), session.size.width_range()),
Side::Height => (session.size.height(), session.size.height_range()),
};
if matches!(side, Side::Height) {
// One unit serves both sides, so its select sits on the Width row only and Height leaves that
// room to Orientation beside it. The field reads and steps in the shared unit.
let kind = session.size.unit();
let units = Env::of(ui).units();
let shown = NumberField::new(side.name(words).clone(), Bind::given(Some(value)))
.range(range)
.codec(NumberCodec::new(units.reader(Some(kind)), *kind.decimals().end()))
.step(kind.step())
.sizing(Sizing::FillWidth)
.show(ui);
apply_number(session, &shown.edit.events, |size, value| size.set_height(value));
return;
}
let shown = UnitSelect::new(side.name(words).clone(), Bind::given(Some(value)), Bind::given(session.size.unit()), &size_units)
.range(range)
.unit_label(side.unit_name(words).clone())
.sizing(Sizing::FillWidth)
.show(ui);
apply_number(session, &shown.edit.events, |size, value| match side {
Side::Width => size.set_width(value),
Side::Height => size.set_height(value),
});
apply_number(session, &shown.edit.events, |size, value| size.set_width(value));
if let Some(kind) = shown.unit.value().copied() {
session.size.set_unit(kind);
}
});
}
Field::new(words.orientation.clone()).id_salt("orientation").show(ui, |ui, _| {
let current = Orientation::of(session.size.pixels());
let shown = Segmented::new(words.orientation.clone(), Bind::given(current), &orientations).show(ui);
if let Some(turned) = shown.value().cloned() {
session.orientation = Some(turned);
if current != turned {
values.take_linked(&session.size);
let PixelSize { width, height, .. } = values.size;
values.size = PixelSize::new(height, width);
session.size = values.linked(read.units.points_per_inch());
};
dimension(ui, session, Side::Width);
// Two shares, as Color Mode and Depth: a content-sized column here was measured empty, which clipped Orientation
// out of reach.
const HEIGHT_AND_ORIENTATION: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)];
Grid::new(&HEIGHT_AND_ORIENTATION).fill().show(ui, |ui, _| {
dimension(ui, session, Side::Height);
Field::new(words.orientation.clone()).layout(FieldLayout::Above).id_salt("orientation").show(ui, |ui, _| {
let current = Orientation::of(session.size.pixels());
let shown = Segmented::new(words.orientation.clone(), Bind::given(current), &orientations).show(ui);
if let Some(turned) = shown.value().cloned() {
session.orientation = Some(turned);
if current != turned {
values.take_linked(&session.size);
let PixelSize { width, height, .. } = values.size;
values.size = PixelSize::new(height, width);
session.size = values.linked(read.units.points_per_inch());
}
keep_selection = true;
}
keep_selection = true;
}
});
});
let shown = Checkbox::new(Bind::given(values.artboard)).label(words.artboards.clone()).show(ui);
@@ -185,7 +194,7 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti
session.preset_artboard = false;
}
Field::new(words.resolution.clone()).id_salt("resolution").show(ui, |ui, _| {
Field::new(words.resolution.clone()).layout(FieldLayout::Above).id_salt("resolution").show(ui, |ui, _| {
let shown = UnitSelect::new(
words.resolution.clone(),
Bind::given(Some(session.size.resolution())),
@@ -194,6 +203,7 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti
)
.range(session.size.resolution_range())
.unit_label(words.resolution_unit.clone())
.sizing(Sizing::FillWidth)
.show(ui);
apply_number(session, &shown.edit.events, LinkedSize::set_resolution);
if let Some(kind) = shown.unit.value().copied() {
@@ -202,40 +212,43 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti
});
values.take_linked(&session.size);
Field::new(words.color_mode.clone()).id_salt("mode").show(ui, |ui, _| {
let shown = Select::new(words.color_mode.clone(), Bind::given(values.color_mode), &modes).show(ui);
if let Some(mode) = shown.value().cloned() {
values.color_mode = mode;
// A profile of the old mode's colour space does not suit the new one.
values.profile = None;
}
const MODE_AND_DEPTH: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)];
Grid::new(&MODE_AND_DEPTH).fill().show(ui, |ui, _| {
Field::new(words.color_mode.clone()).layout(FieldLayout::Above).id_salt("mode").show(ui, |ui, _| {
let shown = Select::new(words.color_mode.clone(), Bind::given(values.color_mode), &modes).sizing(Sizing::FillWidth).show(ui);
if let Some(mode) = shown.value().cloned() {
values.color_mode = mode;
// A profile of the old mode's colour space does not suit the new one.
values.profile = None;
}
});
Field::new(words.depth.clone()).layout(FieldLayout::Above).id_salt("depth").show(ui, |ui, _| {
let shown = Select::new(words.depth.clone(), Bind::given(values.depth), &depths).sizing(Sizing::FillWidth).show(ui);
if let Some(depth) = shown.value().cloned() {
values.depth = depth;
}
});
});
Field::new(words.depth.clone()).id_salt("depth").show(ui, |ui, _| {
let shown = Select::new(words.depth.clone(), Bind::given(values.depth), &depths).show(ui);
if let Some(depth) = shown.value().cloned() {
values.depth = depth;
}
});
Field::new(words.profile.clone()).id_salt("profile").show(ui, |ui, _| {
Field::new(words.profile.clone()).layout(FieldLayout::Above).id_salt("profile").show(ui, |ui, _| {
let current = values.profile.clone().filter(|profile| others.contains(&profile));
let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).show(ui);
let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).sizing(Sizing::FillWidth).show(ui);
if let Some(profile) = shown.value().cloned() {
values.profile = profile;
}
});
Field::new(words.pixel_aspect.clone()).id_salt("pixel-aspect").show(ui, |ui, _| {
Field::new(words.pixel_aspect.clone()).layout(FieldLayout::Above).id_salt("pixel-aspect").show(ui, |ui, _| {
let listed = pixel_aspects.iter().any(|entry| entry.value() == Some(&values.pixel_aspect));
let current = if listed { values.pixel_aspect.clone() } else { SQUARE_PIXELS.to_owned() };
let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).show(ui);
let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).sizing(Sizing::FillWidth).show(ui);
if let Some(id) = shown.value().cloned() {
values.pixel_aspect = id;
}
});
Field::new(words.background.clone()).id_salt("background").show(ui, |ui, _| {
Field::new(words.background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
let kind = BackgroundKind::of(values.background);
let shown = Select::new(words.background.clone(), Bind::given(kind), &backgrounds).show(ui);
let shown = Select::new(words.background.clone(), Bind::given(kind), &backgrounds).sizing(Sizing::FillWidth).show(ui);
match shown.value().cloned() {
Some(BackgroundKind::White) => values.background = BackgroundContents::White,
Some(BackgroundKind::Black) => values.background = BackgroundContents::Black,
@@ -254,6 +267,13 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti
});
});
let save = Button::new(words.save_preset_title.clone()).painted(words.save_preset.clone()).id_salt("save-preset").show(ui);
if clicked(&save) {
session.naming = Some(proposed_name(read));
session.name_tried = false;
session.focus_preset_name = true;
}
let fitted = values.clone().fitted();
if fitted != *values {
*values = fitted;
@@ -463,10 +463,12 @@ impl NumberUnit {
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct RowOptions {
range_decimals: Option<u32>,
pub(crate) popup_slider: bool,
randomize: bool,
eyedropper: bool,
eyedropper_armed: bool,
full_width: bool,
beside_next: bool,
/// A radio row's options stand in one row with no caption ([`Param::options_in_row`]).
options_in_row: bool,
not_remembered: bool,
@@ -814,6 +816,13 @@ impl Param {
self
}
/// Shows a Range row's slider in a linear popup opened from the number field.
#[must_use]
pub fn popup_slider(mut self) -> Self {
self.options.get_or_insert_default().popup_slider = true;
self
}
/// A Random button after the field of a [`ParamKind::Int`] row (a seed): it sets a random value within the row's
/// bounds (an open side is `0` or `i32::MAX`); other kinds are unchanged.
#[must_use]
@@ -873,6 +882,18 @@ impl Param {
self
}
/// Pairs this field with the next one in its section, wrapping when they cannot fit together.
/// If only one is visible, it keeps the content width it takes in a pair.
#[must_use]
pub fn beside_next(mut self) -> Self {
self.options.get_or_insert_default().beside_next = true;
self
}
pub(super) fn pairs_with_next(&self) -> bool {
self.option().beside_next
}
/// Sets the unit shown after the number.
#[must_use]
pub fn unit(mut self, unit: UnitKind) -> Self {
@@ -13,8 +13,9 @@ use super::words::ParamWords;
use crate::buttons::{Button, ToggleButton};
use crate::choice::{Checkbox, Radio, RadioGroup, Swatch};
use crate::contract::{
Bind, BodyCx, CanvasGesture, Entry, NoValue, Outcome, Props as _, Remember as _, Sampler as _, Show as _, ShowContainer as _, clicked,
Bind, BodyCx, CanvasGesture, Entry, NoValue, Outcome, Props as _, Remember as _, Sampler as _, Show as _, ShowContainer as _, Sizing, clicked,
};
use crate::display::Text;
use crate::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
use crate::layout_components::{Row, Stack};
@@ -24,11 +25,11 @@ use crate::pickers::{Select, UnitSelect};
use crate::runtime::env::{Env, Label, UnitKind, Units, with_env};
use crate::sections::{HeaderStrength, Section};
use crate::text::{NumberField, RangeAlert, SelectableText, TextField};
use crate::text::{NumberField, RangeAlert, SelectableText, TextField, UnitPlacement};
use crate::value_drag::{AngleDial, PointPicker, SliderScale};
use craft_behavior::{EditEvent, IconId, Mixed, NumberCodec};
use craft_behavior::{EditEvent, IconId, Mixed, NumberCodec, decimals_for_step};
use craft_host::PickRequest;
use craft_theme::Srgba;
@@ -271,18 +272,29 @@ struct Line<'r> {
key: &'r str,
name: Label,
enabled: bool,
compact: bool,
}
impl Line<'_> {
/// Shows `body` in a field named by the row: its label beside the control, its tooltip over both.
fn show(&self, ui: &mut Ui, mut body: impl FnMut(&mut Ui)) {
let mut field = Field::new(self.name.clone()).id_salt(self.key).enabled(self.enabled);
if self.compact {
field = field.sizing(Sizing::Content);
}
if let Some(tip) = self.param.tooltip_text() {
field = field.tooltip(tip.clone());
}
field.show(ui, |ui, _| body(ui));
}
/// A scalar field with the parameter's declared unit drawn beside the existing editable text.
fn scalar_field(&self, units: &Units, value: f64, decimals: u32) -> NumberField<'static> {
let unit = self.param.unit;
let field = number_field(units, self.name.clone(), Some(value), decimals, unit);
if let Some(unit) = unit { field.unit_kind(unit) } else { field }
}
/// Shows `body` across the form for a full-width row, without a label, or else beside the row's label.
fn show_body(&self, ui: &mut Ui, mut body: impl FnMut(&mut Ui)) {
if self.param.option().full_width() {
@@ -368,29 +380,45 @@ impl<'p> Pass<'p> {
fn rows(&mut self, ui: &mut Ui, params: &[Param]) {
let is_section = |param: &Param| matches!(param.kind, ParamKind::Section);
let first = params.iter().position(is_section).unwrap_or(params.len());
for param in &params[..first] {
self.row(ui, param);
}
self.section_rows(ui, &params[..first]);
let mut rest = &params[first..];
while let Some((head, tail)) = rest.split_first() {
let end = tail.iter().position(is_section).unwrap_or(tail.len());
let (body, after) = tail.split_at(end);
if head.visible(&self.work) {
Section::fixed(plain(&head.label)).id_salt(head.key.as_str()).show(ui, |ui, _| {
for param in body {
self.row(ui, param);
}
self.section_rows(ui, body);
});
}
rest = after;
}
}
fn row(&mut self, ui: &mut Ui, param: &Param) {
fn section_rows(&mut self, ui: &mut Ui, params: &[Param]) {
let mut params = params.iter();
while let Some(param) = params.next() {
if param.pairs_with_next()
&& let Some(next) = params.next()
{
// A row with no visible fields must not add a gap to the form.
if !param.visible(&self.work) && !next.visible(&self.work) {
continue;
}
Row::new().id_salt(param.key.as_str()).wrap(true).fill_width().show(ui, |ui, _| {
self.row(ui, param, true);
self.row(ui, next, true);
});
} else {
self.row(ui, param, false);
}
}
}
fn row(&mut self, ui: &mut Ui, param: &Param, compact: bool) {
if !param.visible(&self.work) {
return;
}
let line = Line { param, key: param.key.as_str(), name: plain(&param.label), enabled: param.enabled(&self.work) };
let line = Line { param, key: param.key.as_str(), name: plain(&param.label), enabled: param.enabled(&self.work), compact };
let held = self.work.get(line.key).cloned();
self.show_row(ui, &line);
param.drop_dependents(held.as_ref(), &mut self.work);
@@ -433,7 +461,12 @@ impl<'p> Pass<'p> {
/// A range row: inline beside its label in the row's field, or stacked under its own caption across the form.
fn range(&mut self, ui: &mut Ui, line: &Line<'_>, range: RangeInclusive<f64>, scale: SliderScale) {
let value = self.work.number(line.key).unwrap_or(*range.start());
let places = line.param.option().range_places();
let options = line.param.option();
let places = options.range_places();
if options.popup_slider {
self.popup_range(ui, line, range, value, places);
return;
}
let layout = self.sliders;
let mut show = |ui: &mut Ui| {
let mut slider = SliderField::new(line.name.clone(), Bind::given(value), range.clone()).scale(scale).layout(layout);
@@ -462,10 +495,41 @@ impl<'p> Pass<'p> {
}
}
fn popup_range(&mut self, ui: &mut Ui, line: &Line<'_>, range: RangeInclusive<f64>, value: f64, places: Option<u32>) {
// Match the ordinary range row's number field precision when the caller sets no step.
let default_step = if range.end() - range.start() <= 10.0 { 0.01 } else { 1.0 };
let step = places.map_or(default_step, |places| 10f64.powi(-(places as i32)));
let unit = line.param.unit.map(|kind| (kind, self.units.symbol(kind)));
line.show(ui, |ui| {
Row::new().show(ui, |ui, _| {
let mut field = NumberField::new(line.name.clone(), Bind::given(Some(value)))
.range(range.clone())
.popup_slider(range.clone())
.snap_popup_slider(places.is_some())
.commit_decimals(decimals_for_step(step))
.scrub_by_label();
if places.is_some() || default_step != 1.0 {
field = field.step(step).snap_typed(places.is_some());
}
if let Some((kind, _)) = &unit {
field = field.unit_kind(*kind).unit_placement(UnitPlacement::After);
}
let shown = field.show(ui);
if let Some((_, symbol)) = &unit {
Text::new(symbol.clone()).show(ui);
}
self.alert(shown.out_of_range);
if let Some(value) = shown.edit.value().copied().flatten() {
self.work.set(line.key, rounded(value, places));
}
});
});
}
fn number(&mut self, ui: &mut Ui, line: &Line<'_>, range: Option<RangeInclusive<f64>>, step: f64, decimals: u32) {
let value = self.work.number(line.key).unwrap_or(0.0);
line.show(ui, |ui| {
let mut field = number_field(self.units, line.name.clone(), Some(value), decimals, line.param.unit).step(step);
let mut field = line.scalar_field(self.units, value, decimals).step(step);
if let Some(range) = range.clone() {
field = field.range(range);
}
@@ -530,7 +594,7 @@ impl<'p> Pass<'p> {
let random = line.param.option().randomize();
line.show(ui, |ui| {
beside(ui, |ui| {
let mut field = number_field(self.units, line.name.clone(), Some(value as f64), WHOLE, line.param.unit).id_salt("field");
let mut field = line.scalar_field(self.units, value as f64, WHOLE).id_salt("field");
if let Some(range) = range.clone() {
field = field.range(range);
}
@@ -609,7 +673,8 @@ impl<'p> Pass<'p> {
.or_else(|| rows.iter().find(is_pattern))
.map(|row| row.key.clone());
// With no pattern to offer the row is disabled and writes nothing.
let line = Line { param: line.param, key: line.key, name: line.name.clone(), enabled: line.enabled && current.is_some() };
let line =
Line { param: line.param, key: line.key, name: line.name.clone(), enabled: line.enabled && current.is_some(), compact: line.compact };
line.show(ui, |ui| {
let picked = PresetPicker::pattern(line.name.clone(), Bind::given(current.clone()), rows, Bind::kept()).show(ui).picked;
if let Some(id) = picked.filter(|id| rows.iter().filter(is_pattern).any(|row| row.key == *id)) {
@@ -901,7 +966,7 @@ impl<'p> Pass<'p> {
}
None => {}
}
let field = number_field(self.units, line.name.clone(), Some(last), decimals, line.param.unit).range(range.clone());
let field = line.scalar_field(self.units, last, decimals).range(range.clone());
let field = field.id_salt("field").enabled(self.work.number(line.key).is_some());
let shown = field.show(ui);
self.alert(shown.out_of_range);
@@ -9,9 +9,11 @@ use super::size_model::LinkedSize;
use super::sizing::{Resample, SizingWords};
use crate::runtime::requests::{HostAnswer, PathFilter, PathRequest};
use crate::contract::{Bind, Held, NoValue, Outcome, Props as _, ShowContainer as _};
use crate::contract::{Bind, Held, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
use crate::display::Text;
use crate::layout_components::{Row, Stack};
use crate::style::TypeRole;
use crate::runtime::env::{Env, Label};
@@ -22,7 +24,7 @@ use crate::runtime::overlay::CloseReason;
use craft_behavior::{PixelSize, Selection};
use craft_keymap::{Chord, Key, Mods};
use craft_theme::Rgba;
use craft_theme::{Rgba, variant::Tone};
use egui::load::SizedTexture;
use egui::{Response, Ui};
@@ -123,6 +125,7 @@ craft_ui::words! {
image_size: "saveForWeb.imageSize" = "Image Size";
width: "saveForWeb.width" = "Width";
height: "saveForWeb.height" = "Height";
constrain: "saveForWeb.constrainProportions" = "Constrain proportions";
size_unit: "saveForWeb.sizeUnit" = "Unit";
percent: "saveForWeb.percent" = "Percent";
fit: "saveForWeb.fit" = "Fit";
@@ -348,6 +351,9 @@ pub struct SaveForWebDialog<'a> {
/// The document's slices, for the Slices choice.
#[prop]
slices: &'a [WebSlice],
/// A notice from the host about slices omitted from the preview and export.
#[prop]
slice_warning: Option<Label>,
/// Binds the view tab to `view`: the dialog shows the bound view and writes the tab the user picks, so the host
/// and the dialog share one value.
#[prop]
@@ -373,6 +379,7 @@ impl<'a> SaveForWebDialog<'a> {
saving: false,
answers: Vec::new(),
slices: &[],
slice_warning: None,
view: None,
frame: None,
}
@@ -380,7 +387,22 @@ impl<'a> SaveForWebDialog<'a> {
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> SaveForWebOutput {
let SaveForWebDialog { name, size, pictures, options, open, presets, animation, remember, saving, answers, slices, view, frame } = self;
let SaveForWebDialog {
name,
size,
pictures,
options,
open,
presets,
animation,
remember,
saving,
answers,
slices,
slice_warning,
view,
frame,
} = self;
let mut view_held = view.map(Held::new);
let mut frame_held = frame.map(Held::new);
let env = Env::of(ui);
@@ -411,8 +433,7 @@ impl<'a> SaveForWebDialog<'a> {
let saved = remember.as_ref().and_then(|key| cx.saved::<Option<Last>>(key).clone());
live = Live::open(size, saved.as_ref());
if let Some(last) = &saved {
// The slices and palette edits belong to one document, so a remembered set leaves them at their defaults.
*options = SaveForWebOptions { percent: 100.0, ..last.options.without_document_fields() };
*options = last.options.without_document_fields();
restored = true;
}
}
@@ -449,6 +470,7 @@ impl<'a> SaveForWebDialog<'a> {
}
}
let before = (options.clone(), live.link.pixels(), live.view, live.frame);
options.apply_size(&mut live.link);
// A frame the host set is a change from the one the last pass showed: the panes are encoded again.
if let Some(bound) = frame_held.as_mut().and_then(|held| held.read(&mut **cx)) {
live.frame = bound;
@@ -474,7 +496,10 @@ impl<'a> SaveForWebDialog<'a> {
slices,
chosen: options.slices.selected(),
};
panes::show(ui, &reads, &mut live, &mut slice_click)
panes::show(ui, &reads, &mut live, &mut slice_click);
if let Some(warning) = &slice_warning {
Text::new(warning.clone()).role(TypeRole::Caption).tone(Tone::Warn).show(ui);
}
});
Stack::new().id_salt("settings").show(ui, |ui, _| {
let kit =
@@ -486,9 +511,6 @@ impl<'a> SaveForWebDialog<'a> {
options.slices.select(number, add);
}
if live.link.pixels() != before.1 {
options.percent = percent_of(live.link.pixels(), live.link.original());
}
if (options.clone(), live.link.pixels(), live.view, live.frame) != before {
live.revision += 1;
}
@@ -6,7 +6,9 @@ use super::model::{Animation, SaveForWebOptions, SaveForWebResult, WantedVariant
use super::{SaveForWebDialog, WebPictures, WebSlice, WebView, result_of, save_request};
use crate::contract::Bind;
use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field};
use crate::patterns::form_dialogs::LinkedSize;
use crate::patterns::form_dialogs::host_requests::HostRequests;
use crate::runtime::env::Label;
use crate::runtime::memory::SaveKey;
use crate::runtime::requests::{ColorRequest, PathRequest};
use craft_behavior::PixelSize;
@@ -42,12 +44,11 @@ pub struct HostedSaveForWeb {
open: bool,
/// The document's slices.
slices: Vec<WebSlice>,
slice_warning: Option<Label>,
/// The view tab: bound to the dialog's `view` prop, so automation reads and writes it here.
view: WebView,
/// The path the app answered the save request with.
path: Option<PathBuf>,
/// The output size after the last pass.
pixels: PixelSize,
}
impl HostedSaveForWeb {
@@ -58,6 +59,13 @@ impl HostedSaveForWeb {
self
}
/// A notice placed below the preview captions when the host omits slices.
#[must_use]
pub fn slice_warning(mut self, warning: Option<Label>) -> Self {
self.slice_warning = warning;
self
}
/// The options as the user left them.
pub fn current(&self) -> &SaveForWebOptions {
&self.options
@@ -81,9 +89,9 @@ impl HostedSaveForWeb {
saving: false,
open: true,
slices: Vec::new(),
slice_warning: None,
view: WebView::default(),
path: None,
pixels: size,
}
}
@@ -91,6 +99,7 @@ impl HostedSaveForWeb {
#[must_use]
pub fn options(mut self, options: SaveForWebOptions) -> Self {
self.options = options;
self.options.clamp_exact_size(self.size);
self
}
@@ -176,7 +185,7 @@ impl StackDialog for HostedSaveForWeb {
}
return None;
};
Some(result_of(self.options.clone(), path, self.pixels, self.view, self.remember.clone()))
Some(result_of(self.options.clone(), path, self.options.output_size(self.size), self.view, self.remember.clone()))
}
/// Waiting while the file dialog Save… asked for is open.
@@ -187,6 +196,10 @@ impl StackDialog for HostedSaveForWeb {
fn json_fields(&self) -> Option<serde_json::Value> {
let mut fields = serde_fields(&self.options)?;
let map = fields.as_object_mut()?;
let size = self.options.output_size(self.size);
map.insert("width".into(), size.width.into());
map.insert("height".into(), size.height.into());
map.insert("__constrain".into(), self.options.constrain_proportions.into());
map.insert("view".to_owned(), serde_json::to_value(self.view).ok()?);
map.insert("frame".to_owned(), serde_json::Value::from(self.frame));
let path = self.path.as_ref().map_or(serde_json::Value::Null, |path| serde_json::Value::String(path.to_string_lossy().into_owned()));
@@ -212,7 +225,35 @@ impl StackDialog for HostedSaveForWeb {
self.frame = u32::try_from(frame).unwrap_or(u32::MAX).min(last);
Ok(())
}
_ => set_serde_field(&mut self.options, field, value),
"width" | "height" => {
let pixels = value.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
let mut link = LinkedSize::new(self.size);
self.options.apply_size(&mut link);
if field == "width" {
link.set_width(pixels);
} else {
link.set_height(pixels);
}
self.options.set_exact_size(&link);
Ok(())
}
"__constrain" => {
let constrain = value.as_bool().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
let mut link = LinkedSize::new(self.size);
self.options.apply_size(&mut link);
self.options.constrain(&mut link, constrain);
Ok(())
}
"percent" => {
set_serde_field(&mut self.options, field, value)?;
self.options.size = None;
Ok(())
}
_ => {
set_serde_field(&mut self.options, field, value)?;
self.options.clamp_exact_size(self.size);
Ok(())
}
}
}
@@ -229,13 +270,13 @@ impl StackDialog for HostedSaveForWeb {
animation: self.animation,
remember: self.remember.clone(),
slices: &self.slices,
slice_warning: self.slice_warning.clone(),
view: Some(Bind::bound(&mut self.view)),
frame: Some(Bind::bound(&mut self.frame)),
open: Some(Bind::bound(&mut self.open)),
..dialog
};
let mut shown = dialog.show(ui);
self.pixels = shown.size;
if let Some(last) = shown.wanted_variants.first() {
self.taken = last.request.revision;
self.wanted = shown.wanted_variants;
@@ -1,20 +1,33 @@
//! Save for Web's values: formats, palettes, dither, metadata, views, options, presets, variants, the result and animations.
use super::Last;
use super::panes::WebPane;
use super::{Last, percent_of};
#[cfg(doc)]
use super::{SaveForWebDialog, four_up_variants};
use crate::patterns::form_dialogs::host_requests::PreviewRequest;
use crate::patterns::form_dialogs::sizing::Resample;
use crate::patterns::form_dialogs::{LinkedSize, MAX_DOCUMENT_SIDE, Resample, resize_from_scale};
use crate::runtime::env::Label;
use crate::runtime::env::UnitKind;
use crate::runtime::memory::SaveKey;
use craft_behavior::{Selection, SelectionChange, SelectionModel};
use craft_behavior::{PixelSize, Selection, SelectionChange, SelectionModel};
use egui::Context;
use egui::load::SizedTexture;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;
/// Loads both sides in pixels without changing the unit shown in the fields.
pub(super) fn set_pixels(link: &mut LinkedSize, size: PixelSize) {
let unit = link.unit();
let linked = link.is_linked();
link.set_unit(UnitKind::Pixels);
link.lock(false);
link.set_width(f64::from(size.width));
link.set_height(f64::from(size.height));
link.lock(linked);
link.set_unit(unit);
}
/// The formats of Save for Web.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
@@ -179,6 +192,12 @@ pub struct SaveForWebOptions {
pub metadata: WebMetadata,
/// The output size in percent of the document, 1 to 1000 with two decimals.
pub percent: f64,
/// Exact output dimensions after editing either side, when those take precedence over percent.
#[serde(default)]
pub size: Option<PixelSize>,
/// Makes the other side follow the document's proportions when one side is edited.
#[serde(default = "constrain_default")]
pub constrain_proportions: bool,
/// How the pixels are made when the size differs from the document's.
pub resample: Resample,
/// The palette colours the user edited, by index, as red, green and blue.
@@ -192,6 +211,10 @@ pub struct SaveForWebOptions {
pub html: bool,
}
fn constrain_default() -> bool {
true
}
/// The serde default of [`SaveForWebOptions::html`]: on.
fn html_default() -> bool {
true
@@ -269,6 +292,8 @@ impl Default for SaveForWebOptions {
convert_srgb: true,
metadata: WebMetadata::Copyright,
percent: 100.0,
size: None,
constrain_proportions: true,
resample: Resample::Bicubic,
palette_edits: BTreeMap::new(),
slices: WebSlices::All,
@@ -278,10 +303,59 @@ impl Default for SaveForWebOptions {
}
impl SaveForWebOptions {
/// The options as the next open remembers them: the slices and palette edits belong to one document, so they
/// are left at their defaults.
/// The output size of the current document, including percent-only settings from existing callers.
pub(super) fn output_size(&self, original: PixelSize) -> PixelSize {
self.size.or_else(|| resize_from_scale(original, self.percent).ok()).unwrap_or(original)
}
/// Keeps supplied exact dimensions within the same bounds as the width and height fields.
pub(super) fn clamp_exact_size(&mut self, original: PixelSize) {
let Some(size) = self.size else { return };
let clamp = |side: u32| side.clamp(1, MAX_DOCUMENT_SIDE as u32);
let clamped = PixelSize::new(clamp(size.width), clamp(size.height));
if clamped != size {
self.size = Some(clamped);
self.percent = percent_of(clamped, original);
}
}
pub(super) fn apply_size(&mut self, link: &mut LinkedSize) {
self.clamp_exact_size(link.original());
let size = self.output_size(link.original());
if size != link.pixels() {
set_pixels(link, size);
}
link.lock(self.constrain_proportions);
}
pub(super) fn set_exact_size(&mut self, link: &LinkedSize) {
self.size = Some(link.pixels());
self.percent = percent_of(link.pixels(), link.original());
}
pub(super) fn constrain(&mut self, link: &mut LinkedSize, constrain: bool) {
self.constrain_proportions = constrain;
link.lock(constrain);
if constrain {
let unit = link.unit();
link.set_unit(UnitKind::Pixels);
let width = f64::from(link.pixels().width);
link.set_width(width);
link.set_unit(unit);
self.set_exact_size(link);
}
}
/// Starts on the next document's full size with proportions linked.
pub(super) fn without_document_fields(&self) -> Self {
SaveForWebOptions { slices: WebSlices::default(), palette_edits: BTreeMap::new(), ..self.clone() }
SaveForWebOptions {
percent: 100.0,
size: None,
constrain_proportions: true,
slices: WebSlices::default(),
palette_edits: BTreeMap::new(),
..self.clone()
}
}
/// Whether the matte row shows: the matte fills the transparency of formats that cannot keep it.
@@ -318,7 +392,14 @@ impl WebPreset {
/// Whether the preset is what `current` shows apart from the size, the slices and the palette edits.
pub fn is_set_in(&self, current: &SaveForWebOptions) -> bool {
let own = &self.options;
own == &SaveForWebOptions { percent: own.percent, slices: own.slices.clone(), palette_edits: own.palette_edits.clone(), ..current.clone() }
own == &SaveForWebOptions {
percent: own.percent,
size: own.size,
constrain_proportions: own.constrain_proportions,
slices: own.slices.clone(),
palette_edits: own.palette_edits.clone(),
..current.clone()
}
}
}
@@ -12,6 +12,7 @@ use crate::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use crate::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
use super::model::set_pixels;
use crate::layout_components::Row;
use crate::patterns::form_dialogs::{LinkedSize, Resample, resize_from_scale};
use crate::pickers::{Select, UnitSelect};
@@ -114,7 +115,7 @@ pub(super) fn show(
if has_slices {
slices_rows(ui, words, options);
}
size_section(ui, words, sizing, units, link, &mut options.resample);
size_section(ui, words, sizing, units, link, options);
});
}
@@ -124,8 +125,15 @@ fn preset_row(ui: &mut Ui, words: &SaveForWebWords, presets: &[WebPreset], optio
entries.extend(presets.iter().enumerate().map(|(at, preset)| Entry::new(Some(at), Label::from(preset.name.clone()))));
row(ui, &words.preset, "preset", |ui| {
if let Some(Some(at)) = Select::new(words.preset.clone(), Bind::given(current), &entries).show(ui).value().cloned() {
let (percent, resample, slices) = (options.percent, options.resample, options.slices.clone());
*options = SaveForWebOptions { percent, resample, slices, palette_edits: BTreeMap::new(), ..presets[at].options.clone() };
*options = SaveForWebOptions {
percent: options.percent,
size: options.size,
constrain_proportions: options.constrain_proportions,
resample: options.resample,
slices: options.slices.clone(),
palette_edits: BTreeMap::new(),
..presets[at].options.clone()
};
}
});
}
@@ -331,7 +339,7 @@ fn metadata_row(ui: &mut Ui, words: &SaveForWebWords, options: &mut SaveForWebOp
}
/// Image Size: Width and Height in pixels or percent, the Percent row and the Resample method.
fn size_section(ui: &mut Ui, words: &SaveForWebWords, sizing: &SizingWords, units: &Units, link: &mut LinkedSize, resample: &mut Resample) {
fn size_section(ui: &mut Ui, words: &SaveForWebWords, sizing: &SizingWords, units: &Units, link: &mut LinkedSize, options: &mut SaveForWebOptions) {
let kinds = [Entry::new(UnitKind::Pixels, units.name(UnitKind::Pixels)), Entry::new(UnitKind::Percent, units.name(UnitKind::Percent))];
Section::fixed(words.image_size.clone()).id_salt("size").show(ui, |ui, _| {
row(ui, &words.width, "width", |ui| {
@@ -342,6 +350,7 @@ fn size_section(ui: &mut Ui, words: &SaveForWebWords, sizing: &SizingWords, unit
.show(ui);
if let Some(v) = field.edit.value().cloned().flatten() {
link.set_width(v);
options.set_exact_size(link);
}
if let Some(unit) = field.unit.value().copied() {
link.set_unit(unit);
@@ -355,6 +364,7 @@ fn size_section(ui: &mut Ui, words: &SaveForWebWords, sizing: &SizingWords, unit
.show(ui);
if let Some(v) = field.edit.value().cloned().flatten() {
link.set_height(v);
options.set_exact_size(link);
}
if let Some(unit) = field.unit.value().copied() {
link.set_unit(unit);
@@ -365,25 +375,22 @@ fn size_section(ui: &mut Ui, words: &SaveForWebWords, sizing: &SizingWords, unit
let field = NumberField::new(words.percent.clone(), Bind::given(Some(percent)))
.codec(NumberCodec::new(units.reader(Some(UnitKind::Percent)), 2))
.range(LEAST_PERCENT..=MAX_PERCENT);
if let Some(v) = field.show(ui).edit.value().cloned().flatten() {
set_percent(link, v);
if let Some(v) = field.show(ui).edit.value().cloned().flatten()
&& let Ok(size) = resize_from_scale(link.original(), v)
{
set_pixels(link, size);
options.percent = v;
options.size = None;
}
});
if let Some(on) = check(ui, &words.constrain, "constrain", link.is_linked()) {
options.constrain(link, on);
}
let methods = Resample::entries(sizing, &RESAMPLE_METHODS);
row(ui, &sizing.resample_method, "resample", |ui| {
if let Some(method) = Select::new(sizing.resample_method.clone(), Bind::given(*resample), &methods).show(ui).value().copied() {
*resample = method;
if let Some(method) = Select::new(sizing.resample_method.clone(), Bind::given(options.resample), &methods).show(ui).value().copied() {
options.resample = method;
}
});
});
}
/// Sets the output size to `percent` of the document, whatever unit the fields show.
fn set_percent(link: &mut LinkedSize, percent: f64) {
if let Ok(size) = resize_from_scale(link.original(), percent) {
let unit = link.unit();
link.set_unit(UnitKind::Pixels);
link.set_width(f64::from(size.width));
link.set_unit(unit);
}
}
@@ -319,10 +319,14 @@ pub(super) struct Kit {
resolutions: Vec<Entry<UnitKind>>,
}
/// The units the width and height are shown in.
/// The length units in Canvas Size order.
const LENGTH_UNITS: [UnitKind; 7] =
[UnitKind::Pixels, UnitKind::Percent, UnitKind::Inches, UnitKind::Centimetres, UnitKind::Millimetres, UnitKind::Points, UnitKind::Picas];
/// Image Size lists Percent first in both dimension menus.
const IMAGE_LENGTH_UNITS: [UnitKind; 7] =
[UnitKind::Percent, UnitKind::Pixels, UnitKind::Inches, UnitKind::Centimetres, UnitKind::Millimetres, UnitKind::Points, UnitKind::Picas];
/// The units the resolution is shown in.
const RESOLUTION_UNITS: [UnitKind; 2] = [UnitKind::PixelsPerInch, UnitKind::PixelsPerCentimetre];
@@ -335,11 +339,21 @@ enum Dimension {
}
impl Kit {
/// The rows of Image Size.
pub(super) fn new(ui: &Ui) -> Self {
Self::with_length_order(ui, &IMAGE_LENGTH_UNITS)
}
/// The rows of Canvas Size.
pub(super) fn for_canvas(ui: &Ui) -> Self {
Self::with_length_order(ui, &LENGTH_UNITS)
}
fn with_length_order(ui: &Ui, length_order: &[UnitKind]) -> Self {
let env = Env::of(ui);
let units = env.units();
let entries = |kinds: &[UnitKind]| -> Vec<Entry<UnitKind>> { kinds.iter().map(|kind| Entry::new(*kind, units.name(*kind))).collect() };
let lengths = entries(&LENGTH_UNITS);
let lengths = entries(length_order);
let mut widths = lengths.clone();
widths.extend(entries(&[UnitKind::Columns]));
Kit {
@@ -177,7 +177,7 @@ impl<'a> CanvasSize<'a> {
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> CanvasSizeOutput {
let CanvasSize { values, open, bytes_per_pixel, held } = self;
let kit = Kit::new(ui);
let kit = Kit::for_canvas(ui);
let words = kit.words();
let title = words.canvas_size_title.clone();
@@ -0,0 +1,67 @@
//! Image Size makes Percent easy to find in both dimension menus.
use craft_behavior::PixelSize;
use craft_ui::contract::Role;
use craft_ui::dialog::{DialogHost, DialogResult};
use craft_ui::patterns::form_dialogs::{CanvasSize, CanvasSizeValues, HostedCanvasSize, HostedImageSize, ImageSize, ImageSizeValues};
use craft_ui::runtime::env::{ColumnSize, UnitKind};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, vec2};
use std::cell::RefCell;
use std::rc::Rc;
const SIZE: PixelSize = PixelSize::new(1200, 900);
const COLUMNS: ColumnSize = ColumnSize::new(180.0, 12.0);
const IMAGE_UNITS: [&str; 8] = ["Percent", "Pixels", "Inches", "Centimetres", "Millimetres", "Points", "Picas", "Columns"];
const CANVAS_UNITS: [&str; 8] = ["Pixels", "Percent", "Inches", "Centimetres", "Millimetres", "Points", "Picas", "Columns"];
fn fixture(host: &Rc<RefCell<DialogHost>>) -> Fixture {
let host = Rc::clone(host);
let mut fixture = Fixture::new(move |ui| host.borrow_mut().run(ui));
fixture.room(vec2(1400.0, 1000.0)).idle(10);
fixture
}
fn unit_order(fixture: &mut Fixture, axis: &str) -> Vec<String> {
let field = fixture.by_label(axis).expect("the dimension's unit combobox");
fixture.access(AccessActionKind::Focus, &field).idle(2);
fixture.key(Key::Space, Modifiers::NONE).idle(3);
let mut options = fixture.by_role(Role::LIST_BOX_OPTION);
options.sort_by(|a, b| a.center().y.total_cmp(&b.center().y));
options.iter().map(|option| fixture.tree().name_of(option.node).expect("the visible option has a name").to_owned()).collect()
}
fn image_host() -> Rc<RefCell<DialogHost>> {
let mut host = DialogHost::new();
#[allow(clippy::redundant_closure, reason = "the builder must be generic over the bind's lifetime")]
let dialog = HostedImageSize::new(ImageSizeValues::new(SIZE).column_size(COLUMNS), |values| ImageSize::new(values));
host.open(dialog);
Rc::new(RefCell::new(host))
}
#[trial]
fn image_size_dimension_menus_put_percent_before_pixels() {
let mut canvas = DialogHost::new();
#[allow(clippy::redundant_closure, reason = "the builder must be generic over the bind's lifetime")]
let dialog = HostedCanvasSize::new(CanvasSizeValues::new(SIZE).column_size(COLUMNS), |values| CanvasSize::new(values));
canvas.open(dialog);
let mut comparison = fixture(&Rc::new(RefCell::new(canvas)));
assert_eq!(unit_order(&mut comparison, "Width unit"), CANVAS_UNITS);
let host = image_host();
let mut width = fixture(&host);
let mut height = fixture(&image_host());
let width_order = unit_order(&mut width, "Width unit");
let height_order = unit_order(&mut height, "Height unit");
assert_eq!(width_order, IMAGE_UNITS, "Image Size Width puts Percent first and Columns last");
assert_eq!(height_order, &IMAGE_UNITS[..7], "Image Size Height puts Percent first and offers no Columns");
let percent = width.by_label("Percent").expect("Percent is a selectable unit");
width.click(&percent).idle(4);
let confirm = width.by_label("OK").expect("the Image Size confirmation");
width.access(AccessActionKind::Click, &confirm).idle(4);
let accepted = host.borrow_mut().take::<HostedImageSize>().and_then(DialogResult::ok).expect("Image Size answers after choosing Percent");
assert_eq!(accepted.unit, UnitKind::Percent);
assert_eq!(accepted.size, SIZE, "switching units preserves the image size");
}
@@ -6,8 +6,10 @@ mod dialog;
mod export;
mod files;
mod hosted;
mod image_unit_order;
mod list_manager;
mod new_document;
mod new_document_orientation;
mod params;
mod password;
mod picker;
@@ -10,9 +10,9 @@ use egui::{Key, Modifiers, Vec2};
use std::cell::RefCell;
use std::rc::Rc;
/// Opens the Save Document Preset pane with the icon beside Name, types `name` over the proposed one and saves.
/// Opens the Save Document Preset pane with the button below the fields, types `name` over the proposed one and saves.
fn save_preset(fixture: &mut Fixture, name: &str) {
let save = fixture.by_label("Save Document Preset").expect("the icon beside Name");
let save = fixture.by_label("Save Document Preset").expect("the Save Document Preset button");
fixture.click(&save).idle(10);
assert!(fixture.by_label("Preset Name").is_some(), "the pane asks for a name");
fixture.type_text(name).idle(4);
@@ -92,7 +92,7 @@ fn the_save_icon_proposes_a_free_name_and_enter_saves_without_creating() {
*held.borrow_mut() = bound;
});
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
let save = fixture.by_label("Save Document Preset").expect("the icon beside Name");
let save = fixture.by_label("Save Document Preset").expect("the Save Document Preset button");
fixture.click(&save).idle(10);
assert!(shows(&fixture, "Saved 2"), "the first free name is proposed");
fixture.type_text("Poster").idle(4);
@@ -129,6 +129,80 @@ fn bitmap_is_one_bit_without_a_transparent_background() {
assert!(shows(&fixture, "1 bit"));
}
#[trial]
fn recent_preset_cards_paint_one_small_page_at_its_aspect() {
use craft_behavior::PixelSize;
use craft_host::target::Os;
use craft_ui::runtime::access::Role;
use craft_ui::testing::{Frames, install_spec, pointer};
use std::cell::Cell;
let wide = PixelSize::new(1200, 900);
let tall = PixelSize::new(600, 1200);
for scale in [1.0, 1.25] {
let mut frames = Frames::uninstalled();
let mut install = install_spec();
install.shell_info = install.shell_info.os(Os::Windows);
craft_ui::install(&frames.ctx, install).expect("a fresh Windows-style desktop fixture");
frames.screen(Vec2::new(1440.0, 900.0));
frames.pixels_per_point(scale);
let mut options = DocumentOptions::default();
let mut recent = DocumentOptions::default();
recent.size = tall;
let mut recents = vec![recent];
let selected_size = Cell::new(options.size);
let mut show = |ui: &mut egui::Ui| {
let _ = NewDocumentDialog::new(Bind::bound(&mut options)).clipboard(wide).recent(Bind::bound(&mut recents)).show(ui);
selected_size.set(options.size);
};
for _ in 0..30 {
frames.frame(Vec::new(), &mut show);
}
assert_eq!(frames.ctx.pixels_per_point(), scale);
assert_eq!(selected_size.get(), wide, "Recent starts with the Clipboard preset");
let tree = frames.tree();
let card = |name: &str| {
tree.with_role(Role::LIST_ITEM)
.into_iter()
.find(|key| tree.name_of(*key).is_some_and(|label| label.starts_with(name)))
.expect("the preset card")
};
let clipboard = card("Clipboard");
let custom = card("Custom");
assert_eq!(tree.selected_of(clipboard), Some(true));
let shapes = frames.frame_shapes(&mut show);
for (name, key, size) in [("Clipboard", clipboard, wide), ("Custom", custom, tall)] {
let card = tree.bounds_of(key).expect("visible tile bounds");
let caption = frames.texts().iter().find(|line| line.text == name).expect("the preset title is painted");
let outlines: Vec<_> = shapes
.iter()
.filter_map(|shape| match shape {
egui::Shape::Rect(rect)
if rect.stroke.width > 0.0
&& (rect.rect.center().x - card.center().x).abs() <= 1.0
&& card.contains_rect(rect.rect)
&& rect.rect.bottom() <= caption.rect.top() =>
{
Some(rect.rect)
}
_ => None,
})
.collect();
assert_eq!(outlines.len(), 1, "one page outline and no extra frame in {name} at {scale}: {outlines:?}");
let page = outlines[0];
assert!((page.width().max(page.height()) - 30.0).abs() <= 1.0, "the compact page outline in {name}: {page:?}");
assert!((page.width() / page.height() - size.width as f32 / size.height as f32).abs() < 0.05, "the page has the preset's aspect");
}
let at = tree.bounds_of(custom).expect("the custom recent is visible").center();
pointer::click(&mut frames, at, &mut show);
assert_eq!(selected_size.get(), tall, "clicking the tall recent still loads its actual dimensions");
let tree = frames.tree();
assert_eq!(tree.selected_of(custom), Some(true));
assert_eq!(tree.selected_of(clipboard), Some(false));
}
}
/// A Web card turns Artboards on and a Photo card turns it off again; Artboards the user ticked stays on.
#[trial]
fn web_cards_turn_artboards_on_and_only_take_back_their_own() {
@@ -174,3 +248,23 @@ fn pixel_aspect_lists_the_custom_entries_and_shows_an_unknown_id_as_square() {
fixture.click(&row).idle(10);
assert!(shows(&fixture, "DVCPRO HD 1080 (1.5)") && shows(&fixture, "Mine"), "the built-in ratios, then the app's");
}
#[trial]
fn the_new_document_layout_places_presets_and_details_below_the_tabs() {
let mut options = DocumentOptions::default();
let mut fixture = Fixture::new(move |ui| {
let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui);
});
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
let recent = fixture.by_label("Recent").expect("the Recent tab").rect;
let mode = fixture.by_label("Color Mode").expect("the Color Mode field").rect;
let depth = fixture.by_label("Depth").expect("the Depth field").rect;
let save = fixture.by_label("Save Document Preset").expect("the save action").rect;
let create = fixture.by_label("Create").expect("the create action").rect;
assert!(shows(&fixture, "PRESET DETAILS"), "the details header is a caption");
assert!(fixture.texts().iter().any(|t| t.text.starts_with("BLANK DOCUMENT PRESETS")), "the presets header is a caption");
assert!(recent.bottom() <= mode.top(), "tabs go above the details");
assert!((mode.top() - depth.top()).abs() < 1.0, "color mode and depth share a row");
assert!(mode.right() <= depth.left(), "depth follows color mode");
assert!(mode.bottom() <= save.top() && save.bottom() <= create.top(), "Save Preset is between the fields and the footer");
}
@@ -0,0 +1,45 @@
//! The orientation segments are page glyphs with accessible names and still turn the document.
use craft_ui::contract::Bind;
use craft_ui::patterns::form_dialogs::{DocumentOptions, NewDocumentDialog};
use craft_ui::testing::{Fixture, trial};
use egui::Vec2;
use std::cell::RefCell;
use std::rc::Rc;
#[trial]
fn orientation_uses_icons_and_swaps_the_document_dimensions() {
let options = Rc::new(RefCell::new(DocumentOptions::default()));
let bound = Rc::clone(&options);
let mut fixture = Fixture::new(move |ui| {
let _ = NewDocumentDialog::new(Bind::bound(&mut *bound.borrow_mut())).show(ui);
});
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
let portrait = fixture.by_label("Portrait").expect("an accessible Portrait choice");
assert!(fixture.by_label("Landscape").is_some(), "an accessible Landscape choice");
assert!(
fixture.texts().iter().all(|text| text.text != "Portrait" && text.text != "Landscape"),
"the orientation controls show page icons without painting their accessible names"
);
let shapes = fixture.frame_clipped_shapes();
for name in ["Portrait", "Landscape"] {
let choice = fixture.by_label(name).expect("an orientation choice").rect;
let painted = shapes.iter().any(|(clip, shape)| {
let bounds = shape.visual_bounding_rect();
choice.contains_rect(bounds) && bounds.area() < choice.area() && clip.contains_rect(bounds)
});
assert!(painted, "the {name} glyph is painted where it can be seen");
}
assert!(fixture.by_label("Height Unit").is_none(), "Width's unit select serves Height too");
let original = options.borrow().size;
assert!(original.width > original.height);
fixture.click_at(portrait.center()).idle(10);
let rotated = options.borrow().size;
assert_eq!((rotated.width, rotated.height), (original.height, original.width));
let landscape = fixture.by_label("Landscape").expect("the Landscape choice after turning the page");
fixture.click_at(landscape.center()).idle(10);
assert_eq!(options.borrow().size, original);
}
@@ -5,7 +5,7 @@ use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, NumberUnit, Param, ParamDialog, ParamKind, ParamRows, set_param_field};
use craft_ui::patterns::presets::PresetRow;
use craft_ui::runtime::env::{Label, UnitKind};
use craft_ui::runtime::env::{Label, Scale, UnitKind};
use craft_ui::testing::{Fixture, trial};
use craft_ui::value_drag::SliderScale;
use egui::{Key, Modifiers, Vec2};
@@ -69,6 +69,47 @@ fn rows(params: Vec<Param>, values: &Rc<RefCell<DialogFields>>) -> Fixture {
fixture
}
/// The opt-in range keeps its numeric value and only opens its slider from the field's arrow.
#[trial]
fn a_popup_slider_opens_from_a_typed_range_row() {
let params = Param::parse_list(r#"{"scale":1..1000=100}"#);
let popup = vec![params[0].clone().popup_slider().unit(UnitKind::Percent)];
let values = Rc::new(RefCell::new(DialogFields::new()));
let mut fixture = rows(popup.clone(), &values);
assert!(fixture.by_role(Role::SLIDER).is_empty(), "no permanent slider");
let chevron = fixture.by_label("Slider").expect("the slider arrow");
let unit = fixture.texts().iter().find(|run| run.text == "%").expect("the percent unit");
assert!(unit.rect.left() >= chevron.rect.right(), "the unit follows the arrow");
fixture.click(&chevron).settle();
let slider = fixture.by_role(Role::SLIDER).into_iter().next().expect("the popup slider");
fixture.click_at(slider.center()).settle();
let value = values.borrow().number("scale").unwrap();
assert!((value - 500.5).abs() <= 4.0, "linear midpoint: {value}");
assert!(set_param_field(&popup, &mut values.borrow_mut(), "scale", json!("125")).is_err());
assert!(set_param_field(&popup, &mut values.borrow_mut(), "scale", json!(1001)).is_err());
set_param_field(&popup, &mut values.borrow_mut(), "scale", json!(125.5)).unwrap();
assert_eq!(ParamDialog::remembered(&popup, &values.borrow()).number("scale"), Some(125.5));
let standard = rows(params, &Rc::new(RefCell::new(DialogFields::new())));
assert_eq!(standard.by_role(Role::SLIDER).len(), 1, "standard range uses its visible slider");
}
#[trial]
fn a_short_popup_slider_can_select_its_midpoint_without_explicit_precision() {
let param = Param::new("scale", "Scale", ParamKind::range(0.0, 0.001, 0.0, SliderScale::Linear)).popup_slider();
let values = Rc::new(RefCell::new(DialogFields::new()));
let mut fixture = rows(vec![param], &values);
let chevron = fixture.by_label("Slider").expect("the slider arrow");
fixture.click(&chevron).settle();
let slider = fixture.by_role(Role::SLIDER).into_iter().next().expect("the popup slider");
fixture.click_at(slider.center()).settle();
let value = values.borrow().number("scale").expect("the selected value");
assert!((value - 0.0005).abs() <= 0.00002, "linear midpoint: {value}");
}
// A row with `visible_when` is there only while its condition holds, and one with `enabled_when` takes input only
// while its condition holds; a tooltip is the description of its row.
#[trial]
@@ -242,6 +283,69 @@ fn a_blend_row_steps_and_picks_by_its_keys_inside_the_dialog() {
assert_eq!(held().as_deref(), Some("multiply"), "Down on the closed list skips the greyed mode");
}
#[trial]
fn paired_parameter_fields_15539_keep_their_controls_and_values() {
let values = Rc::new(RefCell::new(DialogFields::new()));
let shown = values.clone();
let mut fixture = Fixture::new(move |ui| {
let modes = vec![
(BlendKeyEntry::new("normal".to_owned(), BlendShortcut::Normal), "Normal".into()),
(BlendKeyEntry::new("multiply".to_owned(), BlendShortcut::Multiply), "Multiply".into()),
];
let params = vec![
Param::new("name", "Name", ParamKind::text("Layer 1")),
Param::new("mode", "Mode", ParamKind::blend(modes, Some("normal".into()))).beside_next(),
Param::new("opacity", "Opacity", ParamKind::number(Some(0.0), Some(100.0), 100.0, 1.0, 0)).enabled_when("mode", "multiply"),
Param::new("neutral", "Fill with neutral color", ParamKind::bool(false)).enabled_when_in("mode", ["multiply".to_owned()]),
];
let _ = ParamDialog::new("newLayer", "New Layer", params).values(Bind::bound(&mut *shown.borrow_mut())).show(ui);
});
fixture.scale(Scale::new(1.25)).room(Vec2::new(1280.0, 800.0)).settle();
let mode = fixture.by_role(Role::COMBO_BOX).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Mode")).expect("mode");
let opacity =
fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Opacity")).expect("opacity");
assert!((mode.center().y - opacity.center().y).abs() < 1.0, "Mode and Opacity share a row");
assert!(mode.rect.right() <= opacity.rect.left(), "Mode and Opacity have separate hit areas");
assert!(fixture.tree().is_disabled_key(opacity.node), "Normal has a disabled paired Opacity field");
fixture.click_at(opacity.center()).settle();
fixture.type_text("42").settle();
assert_eq!(values.borrow().number("opacity"), Some(100.0), "a disabled neighbor ignores input");
fixture.click(&mode).settle();
let multiply = fixture.by_label("Multiply").expect("the mode option");
fixture.click(&multiply).settle();
let opacity = fixture.by_label("Opacity").expect("the paired field remains present");
assert!(!fixture.tree().is_disabled_key(opacity.node), "the original predicate enables Opacity");
assert_eq!(values.borrow().text("mode"), Some("multiply"));
fixture.click(&opacity).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text("42").key(Key::Tab, Modifiers::NONE).settle();
assert_eq!(values.borrow().number("opacity"), Some(42.0));
assert_eq!(values.borrow().text("mode"), Some("multiply"));
}
#[trial]
fn paired_parameter_fields_15539_leave_no_gap_when_both_are_hidden() {
let before = Param::new("before", "Before", ParamKind::text("one"));
let after = Param::new("after", "After", ParamKind::text("two"));
let values = Rc::new(RefCell::new(DialogFields::new()));
let hidden = rows(
vec![
before.clone(),
Param::new("mode", "Mode", ParamKind::text("Normal")).visible_when("show", true).beside_next(),
Param::new("opacity", "Opacity", ParamKind::int(Some(0), Some(100), 100)).visible_when("show", true),
after.clone(),
],
&values,
);
let center_y = |fixture: &Fixture, name: &str| fixture.by_label(name).expect(name).center().y;
let gap = |fixture: &Fixture| center_y(fixture, "After") - center_y(fixture, "Before");
assert!(hidden.by_label("Mode").is_none() && hidden.by_label("Opacity").is_none());
let absent = rows(vec![before, after], &Rc::new(RefCell::new(DialogFields::new())));
assert_eq!(gap(&hidden), gap(&absent), "a hidden pair uses no space");
}
/// A pattern row shows the first pattern for a stored id the rows lack without writing it, a pick writes the pattern's
/// id, and a group header takes no pick.
#[trial]
@@ -389,3 +493,49 @@ fn typing_in_a_freshly_opened_parameter_dialog_replaces_its_first_field() {
fixture.type_text("7").key(Key::Tab, Modifiers::NONE).settle();
assert_eq!(values.borrow().number("radius"), Some(7.0), "typing replaced the radius");
}
#[trial]
fn parameter_dialogs_15539_show_declared_units_and_keep_parsing() {
let opacity = || Param::new("opacity", "Opacity", ParamKind::number(Some(0.0), Some(100.0), 100.0, 1.0, 0)).unit(UnitKind::Percent);
let new_layer = vec![Param::new("name", "Name", ParamKind::text("Layer 1")), opacity()];
let stroke = vec![
Param::new("copies", "Copies", ParamKind::int(Some(1), Some(5), 1)),
Param::new("width", "Width", ParamKind::number(Some(1.0), Some(250.0), 1.0, 1.0, 0)).unit(UnitKind::Pixels),
opacity(),
Param::new("angle", "Angle", ParamKind::int(Some(0), Some(90), 4)).unit(UnitKind::Degrees),
Param::new("offset", "Offset", ParamKind::optional_number(0.0, 10.0, Some(2.5), 2.5, 2)).unit(UnitKind::Points),
];
for (title, params, units) in [
("New Layer", new_layer, vec![("Opacity", "%", "42%")]),
("Stroke", stroke, vec![("Width", "px", "12 px"), ("Opacity", "%", "42%"), ("Angle", "°", "15°"), ("Offset", "pt", "3.25 pt")]),
] {
let values = Rc::new(RefCell::new(DialogFields::new()));
let shown = values.clone();
let mut fixture = Fixture::new(move |ui| {
let _ = ParamDialog::new(title, title, params.clone()).values(Bind::bound(&mut *shown.borrow_mut())).show(ui);
});
fixture.room(Vec2::new(1280.0, 800.0)).settle();
for (label, suffix, _) in &units {
let field = fixture.by_label(label).expect("the number field");
let painted = fixture
.texts()
.iter()
.filter(|text| text.text == *suffix && !text.elided && text.clip.contains_rect(text.rect) && field.rect.contains_rect(text.rect))
.count();
assert_eq!(painted, 1, "{title}: one visible {suffix} on {label}");
}
for (label, _, text) in units {
let field = fixture.by_label(label).expect("the number field");
fixture.click(&field).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text(text).key(Key::Tab, Modifiers::NONE).settle();
}
let held = values.borrow();
assert_eq!(held.number("opacity"), Some(42.0));
if title == "Stroke" {
assert_eq!(held.number("width"), Some(12.0));
assert_eq!(held.int("angle"), Some(15));
assert_eq!(held.number("offset"), Some(3.25));
assert_eq!(held.int("copies"), Some(1));
}
}
}
@@ -2,9 +2,11 @@
use craft_behavior::PixelSize;
use craft_theme::Srgba;
use craft_ui::dialog::{DialogHost, DialogResult};
use craft_ui::contract::Bind;
use craft_ui::dialog::{DialogHost, DialogResult, StackDialog};
use craft_ui::patterns::form_dialogs::{
Animation, HostedSaveForWeb, PALETTE_COLOR_KEY, SaveForWebOptions, WebFormat, WebPreset, WebSlice, WebSlices, WebVariant,
Animation, HostedSaveForWeb, PALETTE_COLOR_KEY, SAVE_PATH_KEY, SaveForWebDialog, SaveForWebOptions, WebFormat, WebPictures, WebPreset, WebSlice,
WebSlices, WebVariant,
};
use craft_ui::testing::{Fixture, trial};
use egui::load::SizedTexture;
@@ -49,6 +51,96 @@ fn current(host: &Rc<RefCell<DialogHost>>) -> SaveForWebOptions {
host.borrow_mut().get_mut::<HostedSaveForWeb>().map(|web| web.current().clone()).expect("the dialog is open")
}
#[trial]
fn image_size_can_unlink_and_preserves_exact_pixels() {
let document = PixelSize::new(50_001, 100);
let mut preset_options = SaveForWebOptions::default();
preset_options.format = WebFormat::Png24;
let preset = WebPreset::new("PNG exact", preset_options);
let (host, mut fixture) = open(HostedSaveForWeb::new("wide.psd", document, texture()).presets(vec![preset.clone()]));
assert!(current(&host).constrain_proportions);
let field = |fixture: &mut Fixture, label, value| {
let field = fixture.by_label(label).expect("the size field");
fixture.click(&field).idle(2);
fixture.key(Key::A, Modifiers::COMMAND).type_text(value).key(Key::Tab, Modifiers::NONE).idle(4);
};
field(&mut fixture, "Width", "22501");
assert_eq!(current(&host).percent, 45.0);
let link = fixture.by_label("Constrain proportions").expect("the proportions check box");
fixture.click(&link).idle(2);
field(&mut fixture, "Height", "37");
assert_eq!(current(&host).size, Some(PixelSize::new(22_501, 37)));
let select = fixture.by_label("Preset").expect("the Preset list");
fixture.click(&select).idle(2);
let entry = fixture.by_label("PNG exact").expect("the preset entry");
fixture.click(&entry).idle(4);
let current = current(&host);
assert!(preset.is_set_in(&current), "the preset remains selected after editing the size");
assert!(!current.constrain_proportions);
assert_eq!(current.size, Some(PixelSize::new(22_501, 37)));
let mut host = host.borrow_mut();
let web = host.get_mut::<HostedSaveForWeb>().expect("the dialog is open");
let wanted = web.wanted_variants();
assert_eq!(wanted[0].request.options.size, Some(PixelSize::new(22_501, 37)));
web.answer_path(SAVE_PATH_KEY, PathBuf::from("wide.png"));
let result = web.confirm(fixture.ctx()).expect("Save returns the exact unlinked size");
assert_eq!((result.width, result.height), (22_501, 37));
}
#[trial]
fn initial_exact_size_respects_the_document_side_limits() {
let mut options = SaveForWebOptions::default();
options.size = Some(PixelSize::new(300_001, 0));
let (host, fixture) = open(HostedSaveForWeb::new("poster.psd", IMAGE, texture()).options(options));
let normalized = Some(PixelSize::new(300_000, 1));
let mut host = host.borrow_mut();
let web = host.get_mut::<HostedSaveForWeb>().expect("the dialog is open");
let wanted = web.wanted_variants();
assert_eq!(wanted[0].request.options.size, normalized);
assert_eq!(web.current().size, normalized);
let fields = web.json_fields().expect("the dialog fields");
assert_eq!(fields["width"], 300_000);
assert_eq!(fields["height"], 1);
web.answer_path(SAVE_PATH_KEY, PathBuf::from("poster.jpg"));
let result = web.confirm(fixture.ctx()).expect("Save returns the preview size");
assert_eq!((result.width, result.height), (300_000, 1));
assert_eq!(result.options.size, normalized);
let input = serde_json::json!({ "width": 0, "height": 300_001 });
web.set_json_field(fixture.ctx(), "size", input).expect("the automation accepts supplied dimensions");
let result = web.confirm(fixture.ctx()).expect("Save uses the new dimensions before the next frame");
assert_eq!((result.width, result.height), (1, 300_000));
assert_eq!(result.options.size, Some(PixelSize::new(1, 300_000)));
}
#[trial]
fn bound_exact_size_matches_preview_size() {
let mut options = SaveForWebOptions::default();
options.size = Some(PixelSize::new(300_001, 0));
let options = Rc::new(RefCell::new(options));
let bound = Rc::clone(&options);
let size = Rc::new(RefCell::new(None));
let shown = Rc::clone(&size);
let mut fixture = Fixture::new(move |ui| {
let mut options = bound.borrow_mut();
let output = SaveForWebDialog::new("poster.psd", IMAGE, WebPictures::new().original(texture()), Bind::bound(&mut *options)).show(ui);
if let Some(variant) = output.wanted_variants.first() {
*shown.borrow_mut() = Some((output.size, variant.request.options.size));
}
});
fixture.room(Vec2::new(1400.0, 1000.0)).idle(10);
let expected = PixelSize::new(300_000, 1);
assert_eq!(*size.borrow(), Some((expected, Some(expected))));
assert_eq!(options.borrow().size, Some(expected));
}
/// Shows the pictures at 100% and clicks the point `at` of the Original pane's picture.
fn click_picture(fixture: &mut Fixture, at: Pos2) {
let pane = fixture.by_label(ORIGINAL_PANE).expect("the Original pane");
@@ -77,6 +169,23 @@ fn gif(colors: u16) -> SaveForWebOptions {
options
}
#[trial]
fn a_slice_warning_appears_once_below_the_preview_captions() {
let warning = "5 stored slices past the first 10000 were ignored";
let web = || HostedSaveForWeb::new("poster.psd", IMAGE, texture()).slices(slices());
let (_, normal) = open(web());
assert!(!normal.texts().iter().any(|run| run.text == warning));
let (_, mut overflow) = open(web().slice_warning(Some(warning.into())));
let four_up = overflow.by_label("4-Up").expect("the 4-Up view");
overflow.click(&four_up).idle(4);
let notices = overflow.texts().iter().filter(|run| run.text == warning).collect::<Vec<_>>();
assert_eq!(notices.len(), 1, "the dialog shows one warning before Save is pressed");
let captions = overflow.texts().iter().filter(|run| run.text == "Encoding").collect::<Vec<_>>();
assert_eq!(captions.len(), 3, "the three encoded preview captions");
assert!(captions.iter().all(|caption| notices[0].rect.top() >= caption.rect.bottom()), "the warning follows both rows");
}
#[trial]
fn slices_and_palette_edits_follow_the_settings() {
let start = gif(8);
+16 -4
View File
@@ -3,7 +3,8 @@
use super::recent::{RecentFile, RecentView, ThumbKey};
use super::start::{
Leads, PICTURE_HIGH, PICTURE_WIDE, Page, REMOVE, StartAction, StartOutput, StartRecentCommands, ThumbHost, folder_of, paint_thumb, read_events,
HOME_RECENT_PICTURE_ASPECT, Leads, PICTURE_HIGH, PICTURE_WIDE, Page, REMOVE, StartAction, StartOutput, StartRecentCommands, ThumbHost, folder_of,
paint_thumb, read_events,
};
use super::words::ShellWords;
use crate::buttons::Button;
@@ -84,7 +85,7 @@ impl<'a> RecentList<'a> {
if files.is_empty() {
let _ = Text::new(empty.clone()).shade(Shade::Muted).show(ui);
} else {
recent_body(&page, ui, cx, &files, RecentView::List, &empty);
recent_body(&page, ui, cx, &files, RecentView::List, &empty, false);
}
});
StartOutput { response: shown.output.response, actions: actions.into_inner() }
@@ -93,7 +94,16 @@ impl<'a> RecentList<'a> {
/// The body of a recent section: the commands of the recent files, the rows as a grid or a list, the events as
/// actions and the context menu. `empty` is the text of the no-files state when the page has no drop card.
pub(super) fn recent_body(page: &Page<'_>, ui: &mut Ui, cx: &mut BodyCx<'_>, files: &[RecentFile], current: RecentView, empty: &Label) {
/// `desktop_home` gives the grid's cards the desktop Home page's wider pictures and regular padding.
pub(super) fn recent_body(
page: &Page<'_>,
ui: &mut Ui,
cx: &mut BodyCx<'_>,
files: &[RecentFile],
current: RecentView,
empty: &Label,
desktop_home: bool,
) {
let words = page.words;
let mut lead = cx.keep::<Leads>().recent.clone().filter(|path| files.iter().any(|file| &file.path == path));
// One rule for the menu row, the palette and the keys: where the platform cannot reveal a file, the command is disabled.
@@ -128,7 +138,9 @@ pub(super) fn recent_body(page: &Page<'_>, ui: &mut Ui, cx: &mut BodyCx<'_>, fil
let file_of = |path: &PathBuf| files.iter().find(|file| &file.path == path);
let source = keyed(files, |file: &RecentFile| file.path.clone()).with_text(|file| Cow::Borrowed(file.name.as_str()));
let (response, (opened, removed)) = if current == RecentView::Grid {
let out = page.grid::<PathBuf>(words.recent.clone(), true).show_items(ui, &source, &mut |path, _| {
let grid = page.grid::<PathBuf>(words.recent.clone(), true);
let grid = if desktop_home { grid.aspect(HOME_RECENT_PICTURE_ASPECT).regular_card_padding() } else { grid };
let out = grid.show_items(ui, &source, &mut |path, _| {
let Some(file) = file_of(path) else { return Tile::new(Label::Empty) };
page.tile(&file.name, page.age(file.opened), ThumbKey::Recent(file.path.clone()))
.corner_action(IconId::new("close"), StartRecentCommands::Remove)
+219 -22
View File
@@ -7,6 +7,7 @@ mod stories;
use super::recent::{RecentFile, RecentSort, RecentView, Template, ThumbKey, sort_recent};
use super::recent_list::{RecentList, recent_body};
use super::words::ShellWords;
use crate::buttons::button::ButtonStyleKey;
use crate::buttons::{Button, Link};
use crate::choice::Segmented;
use crate::contract::{
@@ -19,17 +20,20 @@ use crate::list::{List, ListRow, ThumbAspect, TrailingPart};
use crate::menu::{Menu, MenuItem};
use crate::notices::{Notice, NoticeLayout};
use crate::pickers::Select;
use crate::primitives::{CheckerArea, ContentPainterCx, IconSpec, Priority, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails, paint_surround};
use crate::primitives::{
CheckerArea, ContentPainterCx, HAlign, IconSpec, Priority, RectSide, Rule, RuleKind, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails,
paint_surround,
};
use crate::runtime::commands::{self, CommandRef, FireSource};
use crate::runtime::commands::{CommandSet as _, Commands as _};
use crate::runtime::env::{AgeStyle, Env, Label};
use crate::sections::Section;
use crate::style::{Corners, SurfaceKind, SurroundLook, TypeRole};
use crate::style::{Corners, StyleCx, SurfaceKind, SurroundLook, TypeRole};
use crate::tile_grid::{CaptionPlace, Tile, TileGrid};
use craft_behavior::{IconId, Proposal, SelectionChange, keyed};
use craft_theme::Variant;
use craft_theme::variant::Tone;
use egui::{CornerRadius, Rect, Response, Ui, Vec2};
use craft_theme::variant::{CustomVariant, Emphasis, RadiusStep, Tone, VariantLook};
use craft_theme::{Rgba, Tokens, Variant};
use egui::{CornerRadius, Rect, Response, Ui, Vec2, pos2, vec2};
use std::borrow::Cow;
use std::cell::RefCell;
use std::path::{Path, PathBuf};
@@ -40,10 +44,22 @@ const CARD_ZOOM: f32 = 2.0;
/// The width and height parts of a card's picture.
pub(super) const PICTURE_WIDE: u16 = 16;
pub(super) const PICTURE_HIGH: u16 = 9;
/// The aspect of the recent file pictures on the desktop Home page.
pub(super) const HOME_RECENT_PICTURE_ASPECT: f32 = 3.0 / 2.0;
/// The number of recent files shown until `max_recent` says otherwise.
const RECENT_SHOWN: usize = 12;
const HOME_BREAKPOINT: f32 = 640.0;
const HOME_RAIL_WIDTH: f32 = 170.0;
const HOME_COMPACT_WIDTH: f32 = 520.0;
const HOME_DROP_WIDTH: f32 = 540.0;
const HOME_DROP_HEIGHT: f32 = 200.0;
const HOME_DROP_ICON: f32 = 34.0;
// design: allow[literal-size/vec2](the desktop Home page's outer margins are larger than any spacing token)
const HOME_DESKTOP_INSET: Vec2 = vec2(36.0, 54.0);
const HOME_DROP_LOOK: CustomVariant = CustomVariant::new::<ButtonStyleKey>("craft_ui.home-drop", home_drop_look);
/// The revealed part of a recent row that takes the file off the list.
pub(super) const REMOVE: TrailingPart = TrailingPart::new(0);
@@ -198,6 +214,13 @@ pub struct StartScreen<'a> {
/// The text of the link that fires [`StartAction::MoreTemplates`].
#[prop(into)]
more_templates: Option<Label>,
/// The desktop Home layout set by [`Self::home_layout`].
home: Option<HomeLayout<'a>>,
}
struct HomeLayout<'a> {
title: Label,
footer_links: &'a [StartLink],
}
/// A link on the start screen's rail.
@@ -210,6 +233,7 @@ pub struct StartLink {
pub icon: Option<IconId>,
/// What the link does.
pub target: StartLinkTarget,
selected: bool,
}
/// What a [`StartLink`] does.
@@ -225,12 +249,18 @@ pub enum StartLinkTarget {
impl StartLink {
/// A link that opens `url`, shown as its tooltip.
pub fn url(label: impl Into<Label>, icon: Option<IconId>, url: impl Into<String>) -> Self {
StartLink { label: label.into(), icon, target: StartLinkTarget::Url(url.into()) }
StartLink { label: label.into(), icon, target: StartLinkTarget::Url(url.into()), selected: false }
}
/// A link that fires `command`.
pub fn command(label: impl Into<Label>, icon: Option<IconId>, command: impl Into<CommandRef>) -> Self {
StartLink { label: label.into(), icon, target: StartLinkTarget::Command(command.into()) }
StartLink { label: label.into(), icon, target: StartLinkTarget::Command(command.into()), selected: false }
}
/// Highlights this command link on a Home rail.
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
}
@@ -248,12 +278,20 @@ impl<'a> StartScreen<'a> {
thumbnails: None,
links: &[],
drop_hint: None,
home: None,
layout: StartLayout::default(),
title: None,
more_templates: None,
}
}
/// Uses a Home layout with a title above the page and a separate group of links at the bottom of its rail.
/// The navigation links come from [`Self::links`]. Narrow rooms put both groups below the content.
pub fn home_layout(mut self, title: impl Into<Label>, footer_links: &'a [StartLink]) -> Self {
self.home = Some(HomeLayout { title: title.into(), footer_links });
self
}
/// Cards, rows and templates ask `thumbnails.state(..)` for what they show; `source` gives each key's revision.
pub fn thumbnails(mut self, thumbnails: &'a Thumbnails<ThumbKey>, source: &'a dyn ThumbSource<ThumbKey>) -> Self {
self.thumbnails = Some((thumbnails, source));
@@ -370,7 +408,7 @@ pub(super) fn read_events<K: Clone, E>(events: Vec<CollectionEvent<K, E>>, lead:
impl StartScreen<'_> {
/// Shows the page across the available room and reports what the user did.
pub fn show(self, ui: &mut Ui) -> StartOutput {
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails, links, drop_hint, layout, title, more_templates } =
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails, links, drop_hint, layout, title, more_templates, home } =
self;
let env = Env::of(ui);
let collator = env.collator();
@@ -386,16 +424,16 @@ impl StartScreen<'_> {
let rail_stack = || Stack::new().gap(Gap::Tight).pad(Pad::Regular).label(words.start_links.clone());
let rail_body = |ui: &mut Ui| {
new_and_open(&page, ui);
new_and_open(&page, ui, Sizing::Content);
let _ = Divider::horizontal().show(ui);
link_items(ui, links);
link_items(ui, links, false);
};
let page_stack = || Stack::new().gap(Gap::Section).pad(Pad::Regular).fill_width();
// `beside` is whether the rail stands beside the page; without it New and Open lead the page and the links follow
// the sections.
let page_body = |ui: &mut Ui, cx: &mut BodyCx<'_>, beside: bool| {
let page_body = |ui: &mut Ui, cx: &mut BodyCx<'_>, beside: bool, drop_area: Option<(f32, bool)>| {
if !beside {
let _ = Row::new().gap(Gap::Tight).show(ui, |ui, _| new_and_open(&page, ui));
let _ = Row::new().gap(Gap::Tight).show(ui, |ui, _| new_and_open(&page, ui, Sizing::Content));
}
if layout == StartLayout::Greeting {
greeting_body(&page, ui, title.as_ref(), more_templates.as_ref(), templates, recent, max_recent);
@@ -405,7 +443,12 @@ impl StartScreen<'_> {
let mut files: Vec<RecentFile> = recent.iter().take(max_recent).cloned().collect();
sort_recent(&mut files, current_sort, &collator);
recent_section(&page, ui, &view, &sort, current_view, &files);
if let (true, Some(hint), Some((center, wide))) = (files.is_empty(), page.drop_hint, drop_area) {
home_drop(&page, ui, hint, center, wide);
} else {
let desktop_home = drop_area.is_some_and(|(_, wide)| wide);
recent_section(&page, ui, &view, &sort, current_view, &files, desktop_home);
}
if let Some(pinned) = pinned {
pinned_section(&page, ui, pinned);
}
@@ -414,15 +457,20 @@ impl StartScreen<'_> {
}
}
if !beside && !links.is_empty() {
let _ = Stack::new().gap(Gap::Tight).label(words.start_links.clone()).show(ui, |ui, _| link_items(ui, links));
let _ = Stack::new().gap(Gap::Tight).label(words.start_links.clone()).show(ui, |ui, _| link_items(ui, links, false));
}
};
if let Some(home) = home {
let response = home.show(ui, &page, links, |ui, cx, center, wide| page_body(ui, cx, true, Some((center, wide))));
return StartOutput { response, actions: actions.into_inner() };
}
// The rail stands beside the sections when the room holds the rail, the gap and the sections' least width; a
// narrower page keeps New and Open in its row and lists the links after the sections.
let rail = !links.is_empty() && {
let rail_width = rail_stack().measure_in(ui, Proposal::Ideal, |ui, _| rail_body(ui)).x;
let sections_least = page_stack().measure_in(ui, Proposal::Min, |ui, cx| page_body(ui, cx, true)).x;
let sections_least = page_stack().measure_in(ui, Proposal::Min, |ui, cx| page_body(ui, cx, true, None)).x;
ui.available_width() >= rail_width + env.tokens.space.gap.section + sections_least
};
@@ -435,16 +483,160 @@ impl StartScreen<'_> {
if rail {
let _ = Row::new().gap(Gap::Section).fill_width().show(ui, |ui, _| {
let _ = rail_stack().show(ui, |ui, _| rail_body(ui));
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, true));
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, true, None));
});
} else {
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, false));
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, false, None));
}
});
StartOutput { response: shown.output, actions: actions.into_inner() }
}
}
impl HomeLayout<'_> {
fn show(&self, ui: &mut Ui, page: &Page<'_>, links: &[StartLink], mut sections: impl FnMut(&mut Ui, &mut BodyCx<'_>, f32, bool)) -> Response {
// Keep the opening gesture on the fixed surface, outside the two independent scrolling regions.
Stack::new()
.fill()
.senses_surface()
.show(ui, |ui, cx| {
if cx.surface_double_pressed() {
page.push(StartAction::Open);
}
let room = ui.available_rect_before_wrap();
let wide = room.width() >= HOME_BREAKPOINT;
let content = if wide {
let (rail, content) = home_columns(room, page.env.direction.is_rtl());
self.rail(ui, page, links, rail);
content
} else {
Rect::from_center_size(room.center(), vec2(room.width().min(HOME_COMPACT_WIDTH), room.height()))
};
let gap = if wide { Gap::CardRow } else { Gap::Section };
let _ =
Stack::new().id_salt("home-page").fill().pad(Pad::Regular).gap(gap).scroll(Scroll::vertical()).show_at(ui, content, |ui, cx| {
let top = ui.available_rect_before_wrap().top();
if !wide {
let _ = Row::new().gap(Gap::Tight).fill_width().show(ui, |ui, _| new_and_open(page, ui, Sizing::FillWidth));
}
let _ = Text::new(self.title.clone()).role(TypeRole::Display).show(ui);
home_divider(ui);
sections(ui, cx, top + content.height() / 2.0, wide);
if !wide {
home_links(ui, page, "home-nav", links, Gap::Tight);
home_links(ui, page, "home-footer", self.footer_links, Gap::Tight);
}
});
})
.output
}
fn rail(&self, ui: &mut Ui, page: &Page<'_>, links: &[StartLink], rect: Rect) {
let stack = || Stack::new().id_salt("home-rail").pad(Pad::Regular).gap(Gap::Section);
let top = |ui: &mut Ui| {
let _ = Stack::new().id_salt("home-actions").gap(Gap::Stack).fill_width().show(ui, |ui, _| {
new_and_open(page, ui, Sizing::FillWidth);
});
home_divider(ui);
home_links(ui, page, "home-nav", links, Gap::Section);
};
let footer = |ui: &mut Ui| {
if !self.footer_links.is_empty() {
home_divider(ui);
home_links(ui, page, "home-footer", self.footer_links, Gap::Section);
}
};
// A short window scrolls the entire rail so the fixed footer cannot crowd the opening buttons out.
let footer_fits = !self.footer_links.is_empty()
&& stack()
.measure_in(ui, Proposal::Ideal, |ui, _| {
top(ui);
footer(ui);
})
.y
<= rect.height();
let rail = stack().fill().scroll(Scroll::vertical());
if footer_fits {
let _ = rail.footer(|ui, _| footer(ui)).show_at(ui, rect, |ui, _| top(ui));
} else {
let _ = rail.show_at(ui, rect, |ui, _| {
top(ui);
footer(ui);
});
}
}
}
fn home_columns(room: Rect, rtl: bool) -> (Rect, Rect) {
// Leave enough height for the two scroll regions on short windows.
let inset_y = HOME_DESKTOP_INSET.y.min((room.height() - HOME_DROP_HEIGHT).max(0.0) / 2.0);
let room = room.shrink2(vec2(HOME_DESKTOP_INSET.x, inset_y));
let gap = HOME_DESKTOP_INSET.x;
if rtl {
let rail = Rect::from_min_max(pos2(room.right() - HOME_RAIL_WIDTH, room.top()), room.max);
let content = Rect::from_min_max(room.min, pos2(rail.left() - gap, room.bottom()));
(rail, content)
} else {
let rail = Rect::from_min_max(room.min, pos2(room.left() + HOME_RAIL_WIDTH, room.bottom()));
let content = Rect::from_min_max(pos2(rail.right() + gap, room.top()), room.max);
(rail, content)
}
}
fn home_links(ui: &mut Ui, page: &Page<'_>, id: &'static str, links: &[StartLink], gap: Gap) {
if !links.is_empty() {
let _ = Stack::new().id_salt(id).gap(gap).label(page.words.start_links.clone()).fill_width().show(ui, |ui, _| link_items(ui, links, true));
}
}
fn home_divider(ui: &mut Ui) {
let env = Env::of(ui);
let style = StyleCx::of_env(ui.ctx(), &env);
let mut look = style.rule(RuleKind::Divider);
look.color = style.color(home_edge(&env.tokens)).egui();
let scale = ui.ctx().pixels_per_point();
let room = ui.available_rect_before_wrap();
let line = Rect::from_min_size(room.min, vec2(room.width(), look.width.points(scale)));
let _ = Stack::new().show_at_taking_room(ui, line, |ui, _| ui.painter().extend(Rule::edge(&look, line, RectSide::Top, scale)));
}
/// Panel dividers can match the canvas surround exactly, so use existing muted ink on that surround.
fn home_edge(tokens: &Tokens) -> Rgba {
let color = &tokens.color;
if color.line.divider == color.surface.canvas { color.text.faint } else { color.line.divider }
}
fn home_drop_look(tokens: &Tokens) -> VariantLook {
let mut look = Variant::SECONDARY.resolve(tokens).radius(RadiusStep::Control);
if let Some(edge) = &mut look.edge {
edge.rest = home_edge(tokens);
}
look
}
fn home_drop(page: &Page<'_>, ui: &mut Ui, hint: &Label, center: f32, wide: bool) {
let room = ui.available_rect_before_wrap();
let width = HOME_DROP_WIDTH.min(room.width());
let top = (center - HOME_DROP_HEIGHT / 2.0).max(room.top());
let slot = Rect::from_min_max(room.min, pos2(room.right(), top + HOME_DROP_HEIGHT));
let left = room.center().x - width / 2.0;
let card = Rect::from_min_max(pos2(left, top), pos2(left + width, slot.bottom()));
let _ = Stack::new().id_salt("home-drop").show_at_taking_room(ui, slot, |ui, _| {
if clicked(&Button::new(hint.clone()).id_salt("drop").variant(Variant::Custom(HOME_DROP_LOOK)).show_at(ui, card)) {
page.push(StartAction::Open);
}
let tokens = &page.env.tokens;
let (side, offset) = if wide {
(HOME_DROP_ICON, (HOME_DROP_ICON + tokens.typography.label.line_height) / 2.0 + tokens.space.gap.stack)
} else {
let side = tokens.size.icon.lg;
(side, side + tokens.space.gap.tight)
};
let icon = Rect::from_center_size(card.center() - vec2(0.0, offset), Vec2::splat(side));
let _ = Icon::new(IconSpec::svg(IconId::new("image"))).show_at(ui, icon);
});
}
/// The greeting page's sections: the title, the templates without a section heading, the more-templates link and the
/// recent files as rows in the order the app gave them. Like production's File > Home page it shows neither Pinned nor
/// the drop card, so the `pinned` and `drop_hint` props do not apply to it.
@@ -478,19 +670,19 @@ fn greeting_body(
}
/// New and Open, the first Tab stops of the page.
fn new_and_open(page: &Page<'_>, ui: &mut Ui) {
fn new_and_open(page: &Page<'_>, ui: &mut Ui, sizing: Sizing) {
let words = page.words;
if clicked(&Button::new(words.new.clone()).id_salt("new").variant(Variant::PRIMARY).show(ui)) {
if clicked(&Button::new(words.new.clone()).id_salt("new").variant(Variant::PRIMARY).sizing(sizing).show(ui)) {
page.push(StartAction::New);
}
if clicked(&Button::new(words.open.clone()).id_salt("open").show(ui)) {
if clicked(&Button::new(words.open.clone()).id_salt("open").sizing(sizing).show(ui)) {
page.push(StartAction::Open);
}
}
/// The links, one under another: a URL opens through its `Link` (the URL is its tooltip), a command fires as a
/// pointer activation.
fn link_items(ui: &mut Ui, links: &[StartLink]) {
fn link_items(ui: &mut Ui, links: &[StartLink], home: bool) {
for (at, link) in links.iter().enumerate() {
match &link.target {
StartLinkTarget::Url(url) => {
@@ -503,6 +695,10 @@ fn link_items(ui: &mut Ui, links: &[StartLink]) {
}
StartLinkTarget::Command(command) => {
let mut button = Button::new(link.label.clone()).id_salt(("start-link", at));
if home {
let variant = if link.selected { Variant::look(Emphasis::Soft, Tone::Accent) } else { Variant::GHOST };
button = button.variant(variant).align(HAlign::Start).sizing(Sizing::FillWidth);
}
if let Some(icon) = &link.icon {
button = button.icon(icon.clone());
}
@@ -521,6 +717,7 @@ fn recent_section(
sort: &RefCell<Bind<'_, RecentSort>>,
current: RecentView,
files: &[RecentFile],
desktop_home: bool,
) {
let words = page.words;
let modes = [
@@ -539,7 +736,7 @@ fn recent_section(
let _ = Segmented::new(words.view.clone(), view.borrow_mut().reborrowed(), &modes).show(ui);
let _ = Select::new(words.sort.clone(), sort.borrow_mut().reborrowed(), &orders).show(ui);
})
.show(ui, |ui, cx| recent_body(page, ui, cx, files, current, &words.no_recent));
.show(ui, |ui, cx| recent_body(page, ui, cx, files, current, &words.no_recent, desktop_home));
}
fn pinned_section(page: &Page<'_>, ui: &mut Ui, folders: &[PathBuf]) {
+219
View File
@@ -163,6 +163,225 @@ fn the_recent_menu_offers_show_in_folder_where_the_platform_can_reveal() {
assert_eq!(fixture.by_label("Show in Folder").is_some(), craft_platform::open::CAN_REVEAL);
}
fn home_screen(has_recent: bool) -> (Fixture, Log) {
let log: Log = Rc::default();
let seen = Rc::clone(&log);
let files: Vec<_> = has_recent.then(|| RecentFile::new("/tmp/work/Poster.psd", "Poster.psd")).into_iter().collect();
let links = [StartLink::command("Home", None, "window.home").selected(true), StartLink::url("Learn", None, "https://example.test/learn")];
let footer = [
StartLink::url("Website", None, "https://example.test"),
StartLink::url("Discord", None, "https://example.test/chat"),
StartLink::url("GitHub", None, "https://example.test/code"),
];
let (mut view, mut sort) = (RecentView::Grid, RecentSort::Opened);
let fixture = Fixture::new(move |ui| {
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &files)
.links(&links)
.home_layout("Photo app", &footer)
.drop_hint("Drop an image")
.show(ui);
seen.borrow_mut().extend(out.actions);
});
(fixture, log)
}
/// At a desktop width the navigation stays left of the recent files and the community links sit below it.
#[trial]
fn the_home_screen_places_navigation_to_the_left_of_recent_files() {
let (mut fixture, _) = home_screen(true);
fixture.room(egui::vec2(1100.0, 700.0)).settle();
let rect = |label| fixture.by_label(label).expect(label).rect;
let recent = rect("Recent");
let new = rect("New…");
let open = rect("Open…");
assert!((new.width() - open.width()).abs() < 1.0);
assert!(open.top() - new.bottom() >= 6.0, "New and Open have room between them");
assert!(rect("Home").top() - open.bottom() >= 24.0, "the divider separates the actions from navigation");
assert!(recent.left() - new.right() >= 36.0, "the rail is separated from the content");
assert!(rect("Photo app").top() >= 54.0);
assert!(recent.top() - rect("Photo app").bottom() >= 32.0, "the title rule has space above and below");
for label in ["Home", "Learn", "Website", "Discord", "GitHub"] {
let navigation = rect(label);
assert!(navigation.right() < recent.left(), "{label} {navigation:?} must be left of Recent {recent:?}");
}
assert!(rect("Home").bottom() < rect("Learn").top());
assert!(rect("Website").top() > fixture.shown().center().y);
assert!(rect("Discord").top() - rect("Website").bottom() >= 6.0);
assert!(rect("GitHub").top() - rect("Discord").bottom() >= 6.0);
}
/// A desktop Recent tile gives its picture and filename room while keeping the whole card clickable.
#[trial]
fn desktop_home_recent_cards_give_the_picture_and_caption_room() {
use egui::{Shape, pos2, vec2};
let (mut fixture, log) = home_screen(true);
fixture.room(vec2(1100.0, 700.0)).settle();
let card = fixture.by_label("Poster.psd").expect("the recent file shows").rect;
let shapes = fixture.frame_shapes();
let picture = shapes
.iter()
.find_map(|shape| match shape {
Shape::Rect(shape)
if card.contains_rect(shape.rect)
&& shape.rect.width() > card.width() * 0.8
&& shape.rect.width() < card.width() - 1.0
&& shape.rect.height() > 100.0 =>
{
Some(shape.rect)
}
_ => None,
})
.expect("the tile paints an inset picture well");
let caption = shapes
.iter()
.find_map(|shape| match shape {
Shape::Text(text) if text.galley.text() == "Poster.psd" => Some(text.pos),
_ => None,
})
.expect("the tile paints its filename");
assert!((390.0..400.0).contains(&card.width()), "{card:?}");
assert!(card.height() >= 285.0, "there is more vertical room: {card:?}");
assert!(picture.left() - card.left() >= 8.0, "the picture has horizontal padding: {picture:?}");
assert!(picture.top() - card.top() >= 8.0, "the picture has top padding: {picture:?}");
assert!(caption.x - card.left() >= 8.0 && caption.y - picture.bottom() >= 8.0, "the filename has space: {caption:?}");
log.borrow_mut().clear();
fixture.click_at(pos2(card.left() + 3.0, card.top() + 3.0)).settle();
assert_eq!(*log.borrow(), vec![StartAction::OpenRecent(PathBuf::from("/tmp/work/Poster.psd"))]);
}
/// The Home surround can have the same colour as ordinary separators. The title and drop card still need visible ink.
#[trial]
fn the_home_title_and_drop_card_keep_their_outlines_visible() {
use craft_ui::runtime::env::{Env, RootEnv};
use craft_ui::testing::Frames;
use egui::{Color32, Shape, vec2};
let ppp = 1.25;
for mode in [craft_theme::Mode::Light, craft_theme::Mode::Dark] {
let mut frames = Frames::new();
frames.root(RootEnv::default().mode(mode));
frames.screen(vec2(1100.0, 700.0));
frames.pixels_per_point(ppp);
let (mut view, mut sort) = (RecentView::Grid, RecentSort::Opened);
let mut canvas = Color32::TRANSPARENT;
frames.record_paint();
frames.frame(Vec::new(), |ui| {
canvas = Color32::from(craft_theme::Srgba::from(Env::of(ui).tokens.color.surface.canvas));
let _ = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &[])
.home_layout("Photo app", &[])
.drop_hint("Drop an image")
.show(ui);
});
let tree = frames.tree();
let title =
tree.keys().into_iter().find(|key| tree.name_of(*key) == Some("Photo app")).and_then(|key| tree.bounds_of(key)).expect("the Home title");
let mut paint = frames.take_paint().expect("the frame drew Home");
paint.textures_delta.clear();
let rule = paint
.shapes
.iter()
.find_map(|shape| match &shape.shape {
Shape::LineSegment { points, stroke }
if (points[1].x - points[0].x) > 800.0 && (title.bottom()..title.bottom() + 32.0).contains(&points[0].y) =>
{
Some(stroke)
}
_ => None,
})
.expect("a full-width title rule");
assert!(rule.color.a() != 0 && rule.color != canvas, "the title rule contrasts with the {mode:?} surround");
assert!((rule.width * ppp - 1.0).abs() < 0.01);
let card = paint
.shapes
.iter()
.find_map(|shape| match &shape.shape {
Shape::Rect(rect)
if (rect.rect.width() - 540.0).abs() < 1.0 && (rect.rect.height() - 200.0).abs() < 1.0 && !rect.stroke.is_empty() =>
{
Some(rect)
}
_ => None,
})
.expect("the drop card has an outline");
assert!(card.stroke.color != canvas, "the drop card contrasts with the {mode:?} surround");
assert!(card.corner_radius.nw < 12, "the drop card uses control corners");
}
}
/// A one-point change at the breakpoint switches from a centred page to the reading-start rail.
#[trial]
fn the_home_screen_changes_layout_at_640_points_in_both_directions() {
for rtl in [false, true] {
let direction = if rtl { craft_i18n::Direction::Rtl } else { craft_i18n::Direction::Ltr };
let (mut fixture, _) = home_screen(true);
fixture.direction(direction).room(egui::vec2(639.0, 700.0)).settle();
let rect = |label| fixture.by_label(label).expect(label).rect;
let actions = rect("New…").union(rect("Open…"));
assert!((rect("New…").center().y - rect("Open…").center().y).abs() < 1.0);
assert!(actions.width() <= 520.0 && (actions.center().x - 319.5).abs() < 1.0);
assert!(rect("Home").top() > rect("Recent").top());
fixture.room(egui::vec2(640.0, 700.0)).settle();
let rect = |label| fixture.by_label(label).expect(label).rect;
assert!(rect("New…").bottom() < rect("Open…").top());
let (nav, content) = (rect("Home"), rect("Recent"));
assert!(if rtl { nav.left() > content.right() } else { nav.right() < content.left() }, "RTL {rtl}: {nav:?} beside {content:?}");
}
}
/// A short desktop rail scrolls as a unit without changing the page beside it.
#[trial]
fn a_short_home_rail_scrolls_to_its_community_links() {
let (mut fixture, _) = home_screen(true);
fixture.room(egui::vec2(1100.0, 120.0)).settle();
let recent = fixture.by_label("Recent").expect("the page is visible").rect;
let opening = fixture.by_label("New…").expect("the rail's first button");
assert!(fixture.shown().contains(opening.center()));
assert!(!fixture.by_label("GitHub").is_some_and(|link| fixture.shown().contains(link.center())));
fixture.frame(vec![moved(opening.center())]).frame(vec![craft_ui::testing::pointer::wheel(-400.0)]).settle();
let link = fixture.by_label("GitHub").expect("the end of the rail can be scrolled into view");
assert!(fixture.shown().contains(link.center()), "the link sits inside the short rail: {:?}", link.rect);
assert_eq!(fixture.by_label("Recent").expect("the page stays visible").rect, recent);
}
/// The empty card has its own pointer and keyboard activation and the blank page opens only on a double-click.
#[trial]
fn the_home_drop_card_is_bounded_and_opens_by_keyboard_or_pointer() {
use egui::{Key, Modifiers};
let (mut fixture, log) = home_screen(false);
fixture.room(egui::vec2(1100.0, 700.0)).settle();
let card = fixture.by_label("Drop an image").expect("an empty page has a drop target");
assert!((card.rect.width() - 540.0).abs() < 1.0 && (card.rect.height() - 200.0).abs() < 1.0, "{:?}", card.rect);
assert!((card.center().y - fixture.shown().center().y).abs() < 24.0, "{:?}", card.rect);
fixture.click(&card).settle();
assert_eq!(*log.borrow(), vec![StartAction::Open]);
log.borrow_mut().clear();
let corner = fixture.shown().max - egui::vec2(30.0, 30.0);
fixture.click_at(corner).click_at(corner).settle();
assert_eq!(*log.borrow(), vec![StartAction::Open], "blank room opens once");
let (mut fixture, log) = home_screen(false);
fixture.room(egui::vec2(1100.0, 700.0)).settle();
let card = fixture.by_label("Drop an image").expect("a separate keyboard target");
let focused = |fixture: &Fixture| fixture.focused().and_then(|id| fixture.node_of(id)).is_some_and(|target| target.node == card.node);
for _ in 0..10 {
if focused(&fixture) {
break;
}
fixture.key(Key::Tab, Modifiers::NONE).settle();
}
assert!(focused(&fixture), "Tab reaches the drop target");
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(*log.borrow(), vec![StartAction::Open]);
}
/// An empty recent list on a page says so in a line at the reading start under its heading, where its rows would
/// begin, not in the start screen's centred empty state (a File page's Open list).
#[trial]
+1 -1
View File
@@ -219,7 +219,7 @@ impl<'a> StatusReadout<'a> {
};
let field = Field::new(words.readout_zoom.clone())
.side(SideLabel::new().kind(LabelKind::Hidden))
.show(ui, |ui, _| ZoomField::new(words.readout_zoom.clone(), current, document).scrub(true).show(ui));
.show(ui, |ui, _| ZoomField::new(words.readout_zoom.clone(), current, document).scrub(true).status_bar().show(ui));
let field = field.inner.map(|zoom| {
invalid_zoom = zoom.invalid_zoom;
events = zoom.view;
+22 -8
View File
@@ -91,8 +91,7 @@ pub struct MenuItemOutput {
pub opens_submenu: bool,
/// A submenu row's submenu is the open one of its level: show the `Menu` after the row.
pub submenu_open: bool,
/// The row is its level's active row and paints with the row fill: the pointer moved onto it, or the keyboard
/// moved to it.
/// The row is its level's active row: the pointer moved onto it, or the keyboard moved to it.
pub active: bool,
/// The row's rect grown by the menu's padding: where a submenu hangs from, so its first row is level with this one
/// and it starts at the popup's edge.
@@ -102,6 +101,10 @@ pub struct MenuItemOutput {
}
impl MenuItemOutput {
pub(super) fn sibling_submenu_open(&self) -> bool {
self.level.sibling_submenu_open(self.id)
}
/// A submenu row's menu was shown at `rect` (`open`), or closed itself (`!open`).
pub(crate) fn note_submenu(&self, open: bool, rect: Rect) {
self.level.note_submenu(self.id, open, rect);
@@ -241,6 +244,7 @@ pub struct MenuItem<'a> {
opens: bool,
open: bool,
active: bool,
submenu_engaged: bool,
}
impl<'a> MenuItem<'a> {
@@ -266,6 +270,7 @@ impl<'a> MenuItem<'a> {
opens: false,
open: false,
active: false,
submenu_engaged: false,
}
.label(label)
}
@@ -560,13 +565,21 @@ impl Component for MenuItem<'_> {
let asked = enabled && (typed || cx.activation().is_some());
if self.submenu {
self.opens = asked || (enabled && forward) || (enabled && takes_over);
if self.opens && level.open_submenu(cx.id) {
frame::request_own_repaint(&ctx);
if self.opens {
let replaces_sibling = level.sibling_submenu_open(cx.id);
if level.open_submenu(cx.id) {
// An earlier row may already have drawn the old submenu in this pass.
if replaces_sibling && frame::discardable(&ctx) {
frame::discard_pass(&ctx, "menu: a sibling replaced the open submenu");
}
frame::request_own_repaint(&ctx);
}
}
self.open = level.submenu_open(cx.id);
// The active row is in the open submenu: this row keeps only the open-submenu tint.
if self.open && level.descended(cx.id, focused) {
// The active row is in the submenu. Keep the accent on its parent so the active path stays visible.
self.active = false;
self.submenu_engaged = enabled;
}
return;
}
@@ -600,9 +613,10 @@ impl Component for MenuItem<'_> {
fn flags(&self) -> Flags {
let mut flags = Flags::empty();
flags.set(Flags::CHECKED, self.check == Some(true) || self.radio_mark == Some(true) || self.entry == Some(true));
flags.set(Flags::LEAD, self.active);
// The row whose submenu is open keeps the hover tint while another row is active.
flags.set(Flags::EMPHASIZED, self.open && !self.active);
let highlighted = self.active || self.submenu_engaged;
flags.set(Flags::LEAD, highlighted);
// If aim holds an open submenu while a sibling takes the highlight, keep the parent's quieter tint.
flags.set(Flags::EMPHASIZED, self.open && !highlighted);
flags
}
+5
View File
@@ -279,6 +279,11 @@ impl MenuLevel {
self.with(|state| state.open_submenu.as_ref().is_some_and(|open| open.row == id))
}
/// Whether a sibling's submenu is open in this level.
pub(super) fn sibling_submenu_open(&self, id: Id) -> bool {
self.with(|state| state.open_submenu.as_ref().is_some_and(|open| open.row != id))
}
/// The submenu of row `id` was shown at `rect`, or closed itself.
pub(super) fn note_submenu(&self, id: Id, open: bool, rect: Rect) {
self.with(|state| match &mut state.open_submenu {
+10 -5
View File
@@ -10,13 +10,13 @@ use crate::contract::{
Trigger,
};
use crate::display::Divider;
use crate::runtime::env::{Env, Label};
use crate::runtime::env::{Env, Label, with_env};
use crate::runtime::focus::{FocusPolicy, Initial};
use crate::runtime::frame;
use crate::runtime::overlay::CloseReason;
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
use craft_behavior::overlay::{Align, Side};
use craft_behavior::{Arrows, Metrics, NavShape, Roving, Sense, Value};
use craft_behavior::{Arrows, Metrics, MotionMode, NavShape, Roving, Sense, Value};
use craft_keymap::{Chord, Key};
use egui::{Response, Ui};
@@ -288,9 +288,14 @@ impl<'a> Menu<'a> {
let label = label.into();
let head = MenuItem::submenu(label.clone()).enabled(enabled).show(ui);
let mut open = head.submenu_open;
let mut body = body;
let shown =
Menu::submenu(label, &head.response).anchor(Anchor::Rect(head.frame)).open(Bind::bound(&mut open)).show(ui, |ui, cx| body(ui, cx));
let show = |ui: &mut Ui| {
Menu::submenu(label, &head.response)
.id(head.response.id.with("submenu"))
.anchor(Anchor::Rect(head.frame))
.open(Bind::bound(&mut open))
.show(ui, body)
};
let shown = if head.sibling_submenu_open() { with_env(ui, |env| env.motion = Some(MotionMode::Off), show) } else { show(ui) };
// `MenuItem::update` does not run in a measuring run, so `open` is false there and would clear the level's
// open submenu the real run set.
if crate::runtime::measure::effect(ui.ctx(), "menu::note_submenu") {
+55 -11
View File
@@ -22,8 +22,9 @@ use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps};
use craft_behavior::{
Codec, ColumnKey, HitLevel, HitPriority, Metrics, NavMove, NumberCodec, PartKey, PressPhase, Sense, ValueDrag, decimals_for_step, wheel_step,
};
use craft_theme::{Stateful, States};
use egui::{Rect, Vec2};
use craft_theme::{Rgba, Stateful, States};
use egui::{CornerRadius, Rect, Vec2};
use std::borrow::Cow;
use std::marker::PhantomData;
use std::ops::RangeInclusive;
@@ -115,9 +116,12 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
/// The range typed, stepped and scrubbed values stay in.
#[prop]
range: Option<RangeInclusive<f64>>,
/// What one arrow press, one wheel notch and one point of scrub change; the default is 1.
/// What one arrow press, one wheel notch and one point of scrub change unless overridden. The default is 1.
#[prop(quantity = "step")]
step: Option<f64>,
/// The change per point of scrub, in shown units. An omitted, non-positive or non-finite rate uses the field step.
#[prop(quantity = "step")]
scrub_step: Option<f64>,
/// Where an arrow press, a Page key and a wheel notch go from the current value, for values on a ladder (the zoom
/// ladder); the step is ignored for them. The range still holds the result.
#[prop(func = "Fn(f64, i32) -> f64")]
@@ -128,6 +132,8 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
/// Whether the unit is drawn inside the field or left to the host to draw after it.
#[prop]
unit_placement: UnitPlacement,
#[style_key]
status_zoom: bool,
/// The rows of the list a chevron after the field opens; Alt+Down opens it too.
#[prop]
presets: Option<&'a [Entry<NumberPick>]>,
@@ -135,6 +141,9 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
/// value at once, as far as the slider would, and the release closes the slider.
#[prop]
popup_slider: Option<RangeInclusive<f64>>,
/// Whether the popup slider snaps to the configured step; defaults to true.
#[prop]
snap_popup_slider: bool,
/// A typed value goes to the nearest multiple of the step when it commits.
#[prop]
snap_typed: bool,
@@ -203,11 +212,14 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
unit_kind: None,
range: None,
step: None,
scrub_step: None,
stepper: None,
unit: None,
unit_placement: UnitPlacement::Inside,
status_zoom: false,
presets: None,
popup_slider: None,
snap_popup_slider: true,
snap_typed: false,
automatic: false,
commit_decimals: None,
@@ -240,6 +252,13 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
self
}
/// Keeps the entire zoom percentage together in an unframed well in the status bar.
#[must_use]
pub(super) fn status_zoom(mut self) -> Self {
self.status_zoom = true;
self.sizing(Sizing::Content)
}
/// A drag on the field's side label scrubs the value too, with or without the focus in the field.
#[must_use]
pub fn scrub_by_label(mut self) -> Self {
@@ -263,7 +282,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
/// The unit drawn inside the field after the number: the field's own, else the symbol of its unit kind; none when
/// the host draws it after the field.
fn shown_unit(&self, units: &Units) -> Option<Label> {
if self.unit_placement == UnitPlacement::After {
if self.status_zoom || self.unit_placement == UnitPlacement::After {
return None;
}
self.unit.clone().or_else(|| self.unit_kind.map(|kind| units.symbol(kind).into()))
@@ -289,6 +308,11 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
value.and_then(NumberValue::number).map(|stored| self.to_shown(stored))
}
/// Whether the field uses the dash for a missing or invalid value.
fn shows_blank(&self, shown: Option<&V>) -> bool {
shown.is_none() || non_finite(shown) || (self.status_zoom && shown.and_then(NumberValue::number).is_none())
}
/// The field's codec: the one set, else the env's locale and the spellings of the unit kind (a length field
/// reads every length spelling).
fn number_codec(&self, units: &Units) -> NumberCodec {
@@ -336,6 +360,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
decimals: self.commit_decimals,
mixed,
names,
suffix: self.status_zoom.then(|| units.symbol(UnitKind::Percent)),
scale: self.scale,
value: PhantomData,
}
@@ -405,12 +430,23 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
type Style = NumberStyle;
type Output = NumberOutput<V>;
fn style(cx: &StyleCx<'_>, _: NumberFieldStyleKey<V>) -> NumberStyle {
fn style(cx: &StyleCx<'_>, key: NumberFieldStyleKey<V>) -> NumberStyle {
let field = FieldStyle::at(cx);
let mut surface = field.surface.clone();
if key.status_zoom {
surface.kind = None;
surface.radius = CornerRadius::ZERO;
// Use the theme's recessed field color; focus and invalid states still use the usual borders.
surface.fill = Stateful::new(cx.color(cx.tokens.color.surface.sunken));
let clear = cx.color(Rgba::TRANSPARENT);
if let Some(border) = &mut surface.border {
border.off = States::new(clear, clear, clear, clear);
}
}
let faint = cx.color(cx.tokens.color.text.faint);
let muted = cx.color(cx.tokens.color.text.muted);
NumberStyle {
surface: field.surface.clone(),
surface,
// The width is the value area, at most a number cell, and the adornments beside it, at least a cell
// (`measure`); the style's minimum is only the height.
metrics: field.clone().sized_by_content().metrics,
@@ -440,8 +476,15 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
let content = content_sized(cx);
// A mixed field is sized as it is with a value, so it keeps its width when the selection changes.
let blank = V::blank().unwrap_or_else(|| V::of_number(self.rule().blank()));
let sample = codec.sample(cx.value().unwrap_or(&blank));
let mut text = cx.field_text(&TextRun::new(sample.as_ref()).role(TypeRole::Mono));
let shown = cx.value();
let no_zoom_value = self.status_zoom && self.shows_blank(shown);
let (sample, role) = if no_zoom_value {
// Text editors draw their hint in the proportional face.
(Cow::Borrowed(BLANK), self.options.role)
} else {
(codec.sample(shown.unwrap_or(&blank)), TypeRole::Mono)
};
let mut text = cx.field_text(&TextRun::new(sample.as_ref()).role(role));
if content {
text.x = crate::layout::ambient_width(cx.ui.ctx(), &VALUES, text.x).map_or(text.x, |width| width.max(text.x));
}
@@ -476,7 +519,7 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
self.options.steps_value = self.presets.is_none() && self.popup_slider.is_none();
let shown = cx.value();
if self.options.placeholder.is_none() {
if shown.is_none() || non_finite(shown) {
if self.shows_blank(shown) {
self.options.placeholder = Some(BLANK.into());
} else if self.automatic {
self.options.placeholder = Some(cx.words::<TextWords>().automatic.clone());
@@ -510,11 +553,12 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
proposed == host || (proposed.named() == host.named() && at_precision(proposed) == at_precision(host))
}
/// A drag on the body of a field not in edit, or on its side label with `scrub_by_label`, moves a step a point;
/// A drag on the body of a field not in edit, or on its side label with `scrub_by_label`, moves by the scrub step per point;
/// a drag on the popup slider's chevron moves the value as far as the same drag on the slider.
fn scrub(&self) -> Option<Scrub<V>> {
let rule = self.rule();
let drag = ValueDrag::relative(rule.step, rule.bounds()).warp(true).hide_cursor(true).coarse(LARGE_STEPS).fine(1.0 / LARGE_STEPS);
let step = self.scrub_step.filter(|step| step.is_finite() && *step > 0.0).unwrap_or(rule.step);
let drag = ValueDrag::relative(step, rule.bounds()).warp(true).hide_cursor(true).coarse(LARGE_STEPS).fine(1.0 / LARGE_STEPS);
// Rounded to the field's decimals, so a scrubbed value carries no float noise. The step is not a grid
// here: an Alt drag moves by a share of it.
let decimals = self.decimals();
+1 -1
View File
@@ -64,7 +64,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
let start = cx.value().and_then(NumberValue::number).unwrap_or_else(|| self.settle_stored((range.start() + range.end()) / 2.0));
let mut shown = start;
let name = cx.label();
let step = self.step.map(|step| self.to_stored(step));
let step = self.step.filter(|_| self.snap_popup_slider).map(|step| self.to_stored(step));
let (rule, scale) = (self.rule(), self.scale);
let edit = ui.show(popup, Overlay::popover(), |ui, _| {
let slider = Slider::new(Bind::bound(&mut shown), range.clone()).label(name.clone());
+20 -5
View File
@@ -110,6 +110,7 @@ pub(super) struct Ruled<V> {
pub(super) decimals: Option<usize>,
pub(super) mixed: bool,
pub(super) names: Vec<(u32, String)>,
pub(super) suffix: Option<String>,
/// How many shown units make one stored unit (1 for a field that shows what it holds).
pub(super) scale: f64,
pub(super) value: PhantomData<fn() -> V>,
@@ -124,6 +125,7 @@ impl<V> Clone for Ruled<V> {
decimals: self.decimals,
mixed: self.mixed,
names: self.names.clone(),
suffix: self.suffix.clone(),
scale: self.scale,
value: PhantomData,
}
@@ -141,6 +143,19 @@ impl<V: NumberValue> Ruled<V> {
v.number().filter(|number| number.is_finite()).map(|number| number * self.scale)
}
fn with_suffix(&self, mut text: String) -> String {
if let Some(suffix) = &self.suffix
&& !text.is_empty()
{
text.push_str(suffix);
}
text
}
fn without_suffix<'a>(&self, text: &'a str) -> &'a str {
self.suffix.as_deref().and_then(|suffix| text.trim_end().strip_suffix(suffix)).unwrap_or(text)
}
/// The name `text` spells, as a value of the field's type.
fn name_of(&self, text: &str) -> Option<V> {
let text = text.trim();
@@ -158,7 +173,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
}
match v.named().and_then(|id| self.names.iter().find(|(name, _)| *name == id)) {
Some((_, label)) => label.clone(),
None => self.inner.format(&self.shown(v)),
None => self.with_suffix(self.inner.format(&self.shown(v))),
}
}
@@ -175,7 +190,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
if text.trim().is_empty() && (self.mixed || V::blank().is_none()) {
return Err(NotAValue);
}
let (read, mut note) = self.inner.parse_tagged(text, &self.shown(start))?;
let (read, mut note) = self.inner.parse_tagged(self.without_suffix(text), &self.shown(start))?;
match read {
Some(number) => {
note.held = (number < self.rule.low || number > self.rule.high).then_some(number);
@@ -186,7 +201,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
}
fn applies_as_typed(&self, text: &str) -> bool {
!self.snap && !self.mixed && is_plain(text) && matches!(self.inner.parse(text, &None), Ok(Some(_)))
!self.snap && !self.mixed && is_plain(text) && matches!(self.inner.parse(self.without_suffix(text), &None), Ok(Some(_)))
}
fn filter(&self, c: char) -> bool {
@@ -196,7 +211,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
fn normalise(&self, text: &str, v: &V) -> String {
match v.named() {
Some(_) => self.format(v),
None => self.inner.normalise(text, &self.shown(v)),
None => self.with_suffix(self.inner.normalise(self.without_suffix(text), &self.shown(v))),
}
}
@@ -210,7 +225,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
// A field that rounds what it commits shows no more places than that.
None if self.rule.low.is_finite() && self.rule.high.is_finite() => {
let codec = self.decimals.map_or_else(|| self.inner.clone(), |places| self.inner.clone().at_most(places));
Cow::Owned(codec.widest(&(self.rule.low..=self.rule.high)))
Cow::Owned(self.with_suffix(codec.widest(&(self.rule.low..=self.rule.high))))
}
None => Cow::Owned(self.format(current)),
}
+12 -1
View File
@@ -32,12 +32,13 @@ pub struct ZoomField {
stepper: bool,
scrub: bool,
enabled: bool,
status_bar: bool,
}
impl ZoomField {
/// A zoom field named `label` over `view` (`None` when no view is known) of a document of `document` units.
pub fn new(label: impl Into<Label>, view: Option<CanvasView>, document: Size) -> Self {
ZoomField { label: label.into(), view, document, stepper: false, scrub: false, enabled: true }
ZoomField { label: label.into(), view, document, stepper: false, scrub: false, enabled: true, status_bar: false }
}
/// The arrow keys and the wheel step along the zoom ladder.
@@ -61,6 +62,13 @@ impl ZoomField {
self
}
/// Uses the status bar's space and field appearance.
#[must_use]
pub(crate) fn status_bar(mut self) -> Self {
self.status_bar = true;
self
}
/// Shows the field and reports the view changes it made.
pub fn show(self, ui: &mut Ui) -> ZoomFieldOutput {
let env = Env::of(ui);
@@ -83,6 +91,9 @@ impl ZoomField {
if self.scrub {
field = field.scrub_by_label();
}
if self.status_bar {
field = field.status_zoom();
}
let shown = field.show(ui);
let invalid_zoom = range.filter(|_| shown.cut).map(|range| InvalidZoom { low: *range.start(), high: *range.end() });
let view = match self.view {
+10 -6
View File
@@ -149,13 +149,13 @@ struct GridSizes {
}
impl GridSizes {
fn of(cx: &StyleCx<'_>, card: bool, rows: RowHeight) -> GridSizes {
fn of(cx: &StyleCx<'_>, card: bool, rows: RowHeight, regular_card_padding: bool) -> GridSizes {
let spacing =
ArrangeSpacing::new(if card { cx.tokens.space.gap.section } else { cx.tokens.space.gap.stack }, cx.tokens.space.gap.inline, rows.of(cx));
GridSizes {
card: cx.tokens.size.thumb.card,
thumbs: [cx.tokens.size.thumb.sm, cx.tokens.size.thumb.md, cx.tokens.size.thumb.lg],
around: Tile::around(cx, card),
around: Tile::around(cx, card, regular_card_padding),
spacing,
// Bare tiles sit with no gap between them: the room around each picture keeps them apart.
bare_spacing: if card { spacing } else { ArrangeSpacing { gap: 0.0, ..spacing } },
@@ -239,6 +239,9 @@ pub struct TileGrid<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// Tiles are framed cards: the picture inset in a raised surface with the name and detail at the reading start.
#[prop(flag)]
card: bool,
/// Framed cards use the theme's regular padding around their picture and caption.
#[prop(flag)]
regular_card_padding: bool,
/// The headers over runs of tiles, in display order.
#[prop]
groups: &'a [TileGroup<K>],
@@ -311,6 +314,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
caption: CaptionPlace::Below,
detail_line: false,
card: false,
regular_card_padding: false,
groups: &[],
collapsible: false,
tail: &[],
@@ -391,7 +395,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
/// The layout of this pass: `previous` when it was made from the same recipe, else a new arrangement. A card is
/// the picture plus what the tile adds around it in every tiling.
fn laid_out(&self, previous: Option<GridLayout>, source: &dyn ItemSource<K>, width: f32, item: Option<Vec2>, cx: &StyleCx<'_>) -> GridLayout {
let style = GridSizes::of(cx, self.card, self.items.row_height);
let style = GridSizes::of(cx, self.card, self.items.row_height, self.regular_card_padding);
let spacing = style.spacing(self.caption);
let around = style.around.get(self.caption, self.detail_line);
// A card never outgrows the grid: in a column narrower than a card the card takes the column.
@@ -793,7 +797,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for TileGrid<'_, K
fn dress_inputs(&self) -> u64 {
use std::hash::{Hash as _, Hasher as _};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
(self.caption, self.detail_line, self.card).hash(&mut hasher);
(self.caption, self.detail_line, self.card, self.regular_card_padding).hash(&mut hasher);
hasher.finish()
}
@@ -802,7 +806,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for TileGrid<'_, K
if self.card_columns == 0 {
return 0.0;
}
let style = GridSizes::of(cx, self.card, self.items.row_height);
let style = GridSizes::of(cx, self.card, self.items.row_height, self.regular_card_padding);
let aspect = if self.aspect.is_finite() && self.aspect > 0.0 { self.aspect } else { 1.0 };
let around = style.around.get(self.caption, self.detail_line);
let card = style.card(self.picture_side(&style, item, around), aspect, around).x;
@@ -826,7 +830,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for TileGrid<'_, K
/// Every tile gets the grid's caption place and detail line, the card look, and its row's rename state.
fn dress<'r>(&self, tile: Self::Item<'r>, row: &RowState) -> Self::Item<'r> {
let tile = tile.caption(self.caption).detail_line(self.detail_line).renaming(row.renaming);
if self.card { tile.card() } else { tile }
if self.card { tile.card().regular_card_padding(self.regular_card_padding) } else { tile }
}
fn can_rename(&self, key: &K) -> bool {
+33 -15
View File
@@ -121,8 +121,8 @@ pub(super) struct AroundPicture {
}
impl AroundPicture {
fn of(cx: &StyleCx<'_>, card: bool) -> AroundPicture {
let around = |place: CaptionPlace, detail: bool| Sizes::of(cx, card, place).around(place, detail);
fn of(cx: &StyleCx<'_>, card: bool, regular_card_padding: bool) -> AroundPicture {
let around = |place: CaptionPlace, detail: bool| Sizes::of(cx, card, place, regular_card_padding).around(place, detail);
AroundPicture {
below: around(CaptionPlace::Below, false),
below_detail: around(CaptionPlace::Below, true),
@@ -145,11 +145,12 @@ impl AroundPicture {
impl Sizes {
/// The sizes of a tile with its caption in `place`. A bare tile keeps only the room its selection ring draws in, so
/// a grid packs bare tiles close.
fn of(cx: &StyleCx<'_>, card: bool, place: CaptionPlace) -> Sizes {
fn of(cx: &StyleCx<'_>, card: bool, place: CaptionPlace, regular_card_padding: bool) -> Sizes {
let (tokens, control) = (cx.tokens, cx.control());
let line = tokens.typography.get(TypeRole::Caption).line_height;
let name_line = if card { tokens.typography.get(TypeRole::BodyStrong).line_height } else { line };
let inset = match (card, place) {
(true, _) if regular_card_padding => tokens.space.pad.regular,
(true, _) => tokens.space.pad.control,
(false, CaptionPlace::None) => tokens.space.gap.tight,
(false, _) => tokens.space.gap.inline,
@@ -297,6 +298,10 @@ pub struct Tile<'a> {
#[style_key]
#[prop]
caption: CaptionPlace,
/// The grid asked for the theme's regular padding around a framed card.
#[style_key]
#[prop]
regular_card_padding: bool,
/// The card has a line for the detail, whether this tile has one or not: the grid's, applied to its tiles.
#[prop]
detail_line: bool,
@@ -305,6 +310,10 @@ pub struct Tile<'a> {
#[style_key]
#[prop(flag)]
card: bool,
/// Draws the preview directly on the tile so a small symbol has no separate background or selection frame.
#[style_key]
#[prop(flag)]
flat_thumbnail: bool,
/// A second line under the name.
#[prop(into)]
detail: Option<Label>,
@@ -377,8 +386,10 @@ impl<'a> Tile<'a> {
Tile {
common: Common::new(),
caption: CaptionPlace::Below,
regular_card_padding: false,
detail_line: false,
card: false,
flat_thumbnail: false,
detail: None,
accessible_name: None,
rating: None,
@@ -470,12 +481,12 @@ impl<'a> Tile<'a> {
/// What a tile adds around its picture: its padding, the caption band under the picture or the column at its
/// reading start. A tile grid sizes a tile as the picture plus this.
pub fn around_picture(cx: &StyleCx<'_>, place: CaptionPlace, detail: bool) -> Around {
Sizes::of(cx, false, place).around(place, detail)
Sizes::of(cx, false, place, false).around(place, detail)
}
/// What a tile adds around its picture for every caption arrangement.
pub(super) fn around(cx: &StyleCx<'_>, card: bool) -> AroundPicture {
AroundPicture::of(cx, card)
pub(super) fn around(cx: &StyleCx<'_>, card: bool, regular_card_padding: bool) -> AroundPicture {
AroundPicture::of(cx, card, regular_card_padding)
}
/// Whether the caption band holds a detail line.
@@ -643,12 +654,19 @@ impl Component for Tile<'_> {
let (state, text) = (&colors.state, &colors.text);
let clear = Rgba::TRANSPARENT;
let c = |rgba: Rgba| cx.color(rgba);
let sizes = Sizes::of(cx, key.card, key.caption);
let sizes = Sizes::of(cx, key.card, key.caption, key.regular_card_padding);
// Selection and hover are rings around the picture; only a card has a fill of its own.
let fill = if key.card {
let raised = colors.surface.raised;
let (rest, hover, pressed) = (c(raised), c(over(state.hover, raised)), c(over(state.pressed, raised)));
Stateful::new(rest).off(States::new(rest, hover, pressed, rest)).on(States::new(rest, hover, pressed, rest))
let on = if key.flat_thumbnail {
let selected = c(over(state.selected, raised));
let selected_hover = c(over(state.selected_hover, raised));
States::new(selected, selected_hover, pressed, selected)
} else {
States::new(rest, hover, pressed, rest)
};
Stateful::new(rest).off(States::new(rest, hover, pressed, rest)).on(on)
} else {
Stateful::new(c(clear))
};
@@ -827,7 +845,7 @@ impl Component for Tile<'_> {
let style = cx.style;
let picture = placed.picture;
let flat = CornerRadius::ZERO;
{
if !self.flat_thumbnail {
// Filled from the outside in, under the picture, so the rings sit outside its edge.
let (ring, halo) = (cx.resolve(&style.ring_width), cx.resolve(&style.halo_width));
let draw = ui.draw();
@@ -837,12 +855,12 @@ impl Component for Tile<'_> {
if ring > 0.0 {
draw.fill(&PaintShape::Rect(picture.expand(ring), flat), cx.resolve(&style.ring));
}
}
if style.sizes.card {
ui.draw().surface(picture, SurfaceKind::Sunken, Corners::All);
} else {
let placeholder = if cx.env.surface() == SurfaceKind::Sunken { style.placeholder_on_sunken } else { style.placeholder };
ui.draw().fill(&PaintShape::Rect(picture, flat), placeholder);
if style.sizes.card {
ui.draw().surface(picture, SurfaceKind::Sunken, Corners::All);
} else {
let placeholder = if cx.env.surface() == SurfaceKind::Sunken { style.placeholder_on_sunken } else { style.placeholder };
ui.draw().fill(&PaintShape::Rect(picture, flat), placeholder);
}
}
if let Some(paint) = self.first.take() {
let _ = ui.child("picture", picture, RowThumb::new(paint));
+100
View File
@@ -322,6 +322,106 @@ fn a_narrow_bar_gives_way_from_its_end_so_the_message_elides_before_the_readout(
assert!(!cut(&narrow, "Doc"), "the readout's text was cut while the message after it could still give way");
}
fn status_zoom(zoom: f64, comma: bool) -> Fixture {
let mut fixture = Fixture::new(move |ui| {
let size = Size::new(2000.0, 1500.0);
let canvas = Rect::from_min_max(egui::Pos2::ZERO, egui::Pos2::new(800.0, 600.0));
let scale = craft_ui::runtime::env::Env::of(ui).scale.0;
let view = CanvasView::new(canvas, Point::new(1000.0, 750.0), zoom / f64::from(scale));
Bar::new("Status", BarKind::Status).show(ui, |ui, _| {
StatusReadout::new(Bind::given(view), size, StatusItem::DocumentSizes, &StatusValues::default()).show(ui);
});
});
if comma {
use craft_host::{AppInfo, Host};
use std::sync::Arc;
let (i18n, problems) = craft_i18n::I18n::from_owned([("de".to_owned(), String::new(), String::new())], &["de"]);
assert!(problems.is_empty(), "{problems:?}");
i18n.set_format(craft_i18n::Format::from_tag("de"));
fixture.host(Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).build()));
}
fixture.room(Vec2::new(600.0, 80.0)).settle();
fixture
}
#[trial]
fn the_status_zoom_shows_its_complete_value_and_percent() {
for (zoom, comma, expected) in [(0.7969, false, "79.69%"), (0.7969, true, "79,69%"), (32.0, false, "3200%"), (31.9999, false, "3199.99%")] {
let fixture = status_zoom(zoom, comma);
let number = fixture.texts().iter().find(|text| text.text == expected).expect(expected);
assert!(
!number.elided && number.rect.min.x + SLACK >= number.clip.min.x && number.rect.max.x <= number.clip.max.x + SLACK,
"{expected} is clipped: {:?} outside {:?}",
number.rect,
number.clip,
);
}
}
#[trial]
fn the_status_zoom_shows_the_complete_dash_without_a_view() {
use craft_behavior::Mixed;
use craft_ui::runtime::env::Scale;
let mut fixture = Fixture::new(|ui| {
let mut values = StatusValues::default();
values.document_sizes = Some((1024, 4096));
Bar::new("Status", BarKind::Status).show(ui, |ui, _| {
StatusReadout::new(Bind::given(Mixed::<CanvasView>::Mixed), Size::new(2000.0, 1500.0), StatusItem::DocumentSizes, &values).show(ui);
});
});
fixture.scale(Scale::new(1.25)).room(Vec2::new(600.0, 80.0)).settle();
let zoom = fixture.by_label("Zoom").expect("the status zoom field");
assert!(fixture.tree().is_disabled_key(zoom.node));
let dash = fixture.texts().iter().find(|text| text.text == "—" && zoom.rect.contains(text.rect.center())).expect("a dash inside the zoom field");
assert!(
!dash.elided && dash.rect.min.x + SLACK >= dash.clip.min.x && dash.rect.max.x <= dash.clip.max.x + SLACK,
"the empty zoom dash is clipped: {:?} outside {:?}",
dash.rect,
dash.clip,
);
}
#[trial]
fn the_status_zoom_still_scrubs_and_applies_edited_text() {
use egui::{Event, Key, Modifiers};
let view = Rc::new(Cell::new(CanvasView::new(Rect::from_min_size(egui::Pos2::ZERO, Vec2::new(800.0, 600.0)), Point::ZERO, 1.0)));
let shown = view.clone();
let committed = Rc::new(Cell::new(None));
let seen = committed.clone();
let mut fixture = Fixture::new(move |ui| {
let mut view = shown.get();
Bar::new("Status", BarKind::Status).show(ui, |ui, _| {
let output =
StatusReadout::new(Bind::bound(&mut view), Size::new(2000.0, 1500.0), StatusItem::DocumentSizes, &StatusValues::default()).show(ui);
if let Some(view) = output.view.committed() {
seen.set(Some(view.zoom));
}
});
shown.set(view);
});
fixture.room(Vec2::new(600.0, 80.0)).settle();
let zoom = fixture.by_label("Zoom").expect("the status zoom field");
fixture.drag(&zoom, Vec2::new(12.0, 0.0)).settle();
let scrubbed = view.get().zoom;
assert!(scrubbed > 1.0, "the status bar still scrubs the zoom to the right");
fixture.click(&zoom).settle();
fixture.key(Key::A, Modifiers::COMMAND);
fixture.frame(vec![Event::Paste("079.69%".to_owned())]).settle();
let before_tab = view.get().zoom;
committed.set(None);
fixture.key(Key::Tab, Modifiers::NONE).settle();
assert_eq!(view.get().zoom, before_tab, "Tab does not change the current zoom");
assert_eq!(committed.get(), None, "Tab does not commit the draft");
let zoom = fixture.by_label("Zoom").expect("the status zoom field");
assert_eq!(fixture.tree().value_of(zoom.node), Some("79.69%"), "Tab rewrites the draft with its suffix");
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert!(committed.get().is_some_and(|value| (value - 0.7969).abs() < 1e-7), "Enter commits the percent-bearing zoom");
}
/// A Row in a Bar under right-to-left measures in a room unbounded at its start edge, the left one: a labelled check
/// box there lays out with finite rects inside the bar, after the button before it in reading order. Guards against a
/// label row built from the room's start and width, which was NaN there.
+70
View File
@@ -267,6 +267,76 @@ fn a_settled_menu_bar_takes_its_mnemonics_and_f10() {
assert!(fixture.by_label("New").is_some(), "Alt+F opens File");
}
#[trial]
fn switching_sibling_submenus_paints_only_the_new_submenu() {
use craft_behavior::MotionMode;
use craft_ui::menu::Menu;
use craft_ui::runtime::env::Scale;
use craft_ui::testing::pointer;
use egui::Shape;
for motion in [MotionMode::Full, MotionMode::Off] {
let runs = Rc::new(Cell::new(0));
let counted = Rc::clone(&runs);
let mut fixture = Fixture::new(move |ui| {
Lazy::new("status", 0.0).settles(true).content(1).show(ui, |_| counted.set(counted.get() + 1));
let titles = vec![MenuTitle::new("Filter", |ui| {
Menu::submenu_row(ui, "Blur", |ui, _| {
MenuItem::new("Gaussian Blur").show(ui);
MenuItem::new("Motion Blur").show(ui);
});
Menu::submenu_row(ui, "Sharpen", |ui, _| {
MenuItem::new("Unsharp Mask").show(ui);
});
})];
MenuBar::new("Main menu", titles).show(ui);
});
fixture.os(Os::Windows).room(egui::vec2(480.0, 320.0)).scale(Scale::new(1.25)).motion(motion).settle();
let filter = fixture.by_label("Filter").expect("the Filter title");
fixture.click(&filter).settle();
let blur = fixture.by_label("Blur").expect("the Blur row");
let sharpen = fixture.by_label("Sharpen").expect("the Sharpen row");
fixture.frame(vec![pointer::moved(blur.center())]).advance(0.25).idle(1);
assert!(fixture.texts().iter().any(|run| run.text == "Gaussian Blur"), "the first submenu starts open");
for (next, previous, shown, hidden) in [(sharpen, blur, "Unsharp Mask", "Gaussian Blur"), (blur, sharpen, "Gaussian Blur", "Unsharp Mask")] {
runs.set(0);
let shapes = fixture.frame_shapes_with(vec![pointer::moved(next.center())]);
assert_eq!(runs.get(), 0, "switching submenus leaves unrelated regions settled");
let painted = |label: &str| fixture.texts().iter().any(|run| run.text == label);
assert!(painted(shown), "the switch frame paints {shown}");
assert!(!painted(hidden), "the switch frame no longer paints {hidden}");
let highlighted = |target| shapes.iter().any(|shape| matches!(shape, Shape::Rect(row) if row.rect == target && row.fill.a() > 0));
assert!(highlighted(next.rect) && !highlighted(previous.rect), "only the new parent row is highlighted");
let child_surfaces = shapes.iter().filter(|shape| {
matches!(shape, Shape::Rect(surface)
if surface.rect.left() >= next.rect.right() && surface.corner_radius != egui::CornerRadius::ZERO && surface.fill.a() == 255
)
});
assert_eq!(child_surfaces.count(), 1, "only the new submenu surface is painted");
fixture.advance(0.25).idle(1);
}
// Moving diagonally across Sharpen toward the open Blur menu keeps Blur open.
let toward_blur = egui::pos2(sharpen.rect.right() - 2.0, sharpen.center().y);
fixture.frame(vec![pointer::moved(toward_blur)]);
assert!(!fixture.texts().iter().any(|run| run.text == "Unsharp Mask"), "aiming into Blur does not switch menus");
let blur_item = fixture.by_label("Gaussian Blur").expect("the Blur submenu is still open");
fixture.frame(vec![pointer::moved(blur_item.center())]);
fixture.key(Key::Escape, Modifiers::NONE);
assert_eq!(
fixture.texts().iter().any(|run| run.text == "Gaussian Blur"),
motion == MotionMode::Full,
"ordinary dismissal follows the menu's inherited motion mode",
);
assert!(!fixture.texts().iter().any(|run| run.text == "Unsharp Mask"), "the replaced submenu stays closed");
fixture.advance(0.25).idle(1);
assert!(!fixture.texts().iter().any(|run| run.text == "Gaussian Blur"), "Escape finishes closing the submenu");
assert!(fixture.by_label("Blur").is_some(), "Escape leaves the parent menu open");
}
}
/// A menu bar in a settled region with a content version underlines its mnemonics while Alt is held: the modifiers
/// it paints by are a recorded read, so the frame Alt goes down runs the region, and so does the frame it comes up,
/// though the version stays the same. In between the region settles again.
+53
View File
@@ -1,5 +1,7 @@
//! Menu rows: the detail line under the label, the row's own tooltip, the sample slot and which shortcut a row shows.
use craft_behavior::MotionMode;
use craft_host::target::Os;
use craft_i18n::Direction;
use craft_ui::buttons::Button;
use craft_ui::contract::tooltip::DELAY;
@@ -7,6 +9,7 @@ use craft_ui::contract::{CommandSet, Props as _, Show as _, ShowContainer as _,
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::commands::CommandState;
use craft_ui::runtime::env::Scale;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::Rect;
use std::cell::Cell;
@@ -226,3 +229,53 @@ fn the_menu_highlight_moves_to_the_next_row_in_the_frame_the_pointer_reaches_it(
assert_eq!(fills_in(&shapes, redo), [lit], "the row the pointer reached paints the full highlight at once");
assert!(fills_in(&shapes, undo).is_empty(), "the row the pointer left paints no highlight at once: {:?}", fills_in(&shapes, undo));
}
#[trial]
fn the_open_submenu_parent_keeps_the_accent_when_the_pointer_enters_its_child() {
for scale in [1.0, 1.25, 1.5] {
let parent_state = Rc::new(Cell::new((false, false)));
let observed = Rc::clone(&parent_state);
let mut fixture = Fixture::new(move |ui| {
let opener = Button::new("Open").show(ui);
Menu::new("Filter").opened_by(&opener, Trigger::Click).show(ui, |ui, _| {
MenuItem::new("Liquify").show(ui);
let blur = Menu::submenu_row(ui, "Blur", |ui, _| {
for label in ["Average", "Gaussian Blur", "Motion Blur", "Shape Blur", "Smart Blur"] {
MenuItem::new(label).show(ui);
}
});
observed.set((blur.active, blur.submenu_open));
Menu::submenu_row(ui, "Distort", |ui, _| {
MenuItem::new("Wave").show(ui);
});
});
});
fixture.os(Os::Windows).room(egui::vec2(660.0, 460.0)).scale(Scale::new(scale)).motion(MotionMode::Off).settle();
let opener = fixture.by_label("Open").expect("the opener");
fixture.click(&opener).settle();
let plain = fixture.by_label("Liquify").expect("the plain row").rect;
let parent = fixture.by_label("Blur").expect("the submenu row").rect;
let sibling = fixture.by_label("Distort").expect("the sibling submenu row").rect;
let shapes = fixture.frame_shapes_with(vec![pointer::moved(plain.center())]);
let accent = fills_in(&shapes, plain);
assert_eq!(accent.len(), 1, "the plain row paints one highlight at {scale}×");
let shapes = fixture.frame_shapes_with(vec![pointer::moved(parent.center())]);
assert_eq!(fills_in(&shapes, parent), accent, "the submenu row immediately uses the same highlight at {scale}×");
assert_eq!(parent_state.get(), (true, true), "the parent is active and open while hovered");
let child = fixture.by_label("Average").expect("the submenu opens on hover").rect;
fixture.frame(vec![pointer::moved(parent.center())]);
let crossing = egui::pos2(sibling.max.x - 2.0, sibling.center().y);
let shapes = fixture.frame_shapes_with(vec![pointer::moved(crossing)]);
assert_eq!(fills_in(&shapes, sibling), accent, "the crossed sibling highlights immediately at {scale}×");
assert_ne!(fills_in(&shapes, parent), accent, "while aiming through a sibling, the parent keeps its subdued tint");
assert!(fixture.by_label("Average").is_some() && fixture.by_label("Wave").is_none(), "aim still holds the original submenu open");
let shapes = fixture.frame_shapes_with(vec![pointer::moved(child.center())]);
assert_eq!(fills_in(&shapes, child), accent, "the child row immediately uses the same highlight at {scale}×");
assert_eq!(parent_state.get(), (false, true), "the parent remains open with the active row now in its submenu");
assert_eq!(fills_in(&shapes, parent), accent, "the parent keeps its accent while its child is active at {scale}×");
}
}
+1
View File
@@ -9,6 +9,7 @@ mod linked;
mod mixed_blank;
mod number;
mod number_length;
mod number_scrub_step;
mod selectable;
mod text_field;
mod widths;
@@ -0,0 +1,60 @@
//! Numeric fields can keep fine discrete steps and a faster scrub.
use craft_ui::contract::{Bind, Show as _, ShowContainer as _, SideLabel};
use craft_ui::form::Field;
use craft_ui::testing::pointer::{moved, wheel_lines};
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::NumberField;
use egui::{Key, Modifiers, vec2};
use std::cell::Cell;
use std::rc::Rc;
const START: f64 = 30.0;
fn angle_field(scrub_step: Option<f64>) -> (Fixture, Rc<Cell<Option<f64>>>) {
let value = Rc::new(Cell::new(Some(START)));
let shown = Rc::clone(&value);
let mut fixture = Fixture::new(move |ui| {
Field::new("Angle").side(SideLabel::new().scrub(true)).show(ui, |ui, _| {
let mut current = shown.get();
let field = NumberField::new("Angle", Bind::bound(&mut current)).step(0.01).fixed_decimals(2).range(-359.99..=359.99).scrub_by_label();
let field = match scrub_step {
Some(step) => field.scrub_step(step),
None => field,
};
field.show(ui);
shown.set(current);
});
});
fixture.settle();
(fixture, value)
}
fn scrub_caption(fixture: &mut Fixture) {
let field = fixture.by_label("Angle").expect("the Angle number field");
let caption = fixture.texts().iter().find(|text| text.text == "Angle").expect("the visible scrub caption").rect;
assert!(!field.rect.intersects(caption), "the caption is a separate handle");
fixture.drag_at(caption.center(), vec2(50.0, 0.0)).settle();
}
#[trial]
fn a_separate_scrub_rate_keeps_fine_key_and_wheel_steps() {
let (mut fixture, value) = angle_field(Some(1.0));
scrub_caption(&mut fixture);
assert_eq!(value.get(), Some(80.0), "50 points of caption drag add 50 degrees");
let field = fixture.by_label("Angle").expect("the Angle number field");
fixture.click(&field).key(Key::ArrowUp, Modifiers::NONE).settle();
assert_eq!(value.get(), Some(80.01), "an arrow still adds one hundredth");
fixture.frame(vec![moved(field.center())]);
fixture.frame(vec![wheel_lines(1.0)]).settle();
assert_eq!(value.get(), Some(80.02), "one wheel notch still adds one hundredth");
}
#[trial]
fn an_omitted_or_invalid_scrub_rate_uses_the_field_step() {
for rate in [None, Some(0.0), Some(-1.0), Some(f64::NAN), Some(f64::INFINITY)] {
let (mut fixture, value) = angle_field(rate);
scrub_caption(&mut fixture);
assert_eq!(value.get(), Some(30.50), "the fallback rate for {rate:?} is 0.01 per point");
}
}
@@ -1 +1,9 @@
config_version = 1
[[exception]]
name = "home-desktop-insets"
kind = "marker"
rule = "literal-size/vec2"
path = "crates/ui-shell/src/shell/start.rs"
reason = "The desktop Home page's outer margins (36 and 54 points) are larger than any spacing token."
count = 1