dialogs-w11: net change of 7 commits

- dialogs-w11: written by an agent
- dialogs-w11: finished by an agent
- dialogs-w11: measure_layer takes Overlay::full_window (combine)
- dialogs-w11: BrushWorkspace's queue is visible to its trials (combine)
- dialogs-w11: review fixes (review-1)
- dialogs-w11: the held-OK trial reads one tree for the shown and disabled checks (dialogs run round)
- dialogs-w11: a resizable window takes its default or content size only to open (dialogs run round)
This commit is contained in:
aiongg
2026-11-15 04:46:06 +00:00
parent 66a61366fa
commit b8cbaab7fa
19 changed files with 849 additions and 316 deletions
@@ -4,6 +4,7 @@
use craft_ui::canvas::{PixelRect, RasterSource};
use craft_ui::contract::Entry;
use craft_ui::patterns::form_dialogs::{DialogFields, Param, ParamKind};
use craft_ui::primitives::textures::ThumbSource;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::pending::Job;
@@ -108,13 +109,11 @@ impl GalleryThumb {
/// `preview` is the picture the canvas shows; its revision moves when a render lands. `render` starts the
/// job that renders `effects` over `visible` (document pixels, widened by the filters' reach) at `zoom`
/// (screen pixels per document pixel): the workspace asks again when the effects, the visible part or the
/// zoom change, and a newer request replaces the one running.
/// zoom change, and a newer request replaces the one running. `catalog` and `thumb_source` are what the
/// columns list and the automation surface checks keys against.
pub trait FilterGallerySource: Send + Sync {
/// The catalog the gallery lists and the effects name their filters in.
// P3(dialogs-w11): dl.K59 — default body until the app's sources implement it.
fn catalog(&self) -> &dyn FilterCatalog {
todo!("dl.K59")
}
fn catalog(&self) -> &dyn FilterCatalog;
/// The rendered preview.
fn preview(&self) -> &dyn RasterSource;
@@ -122,11 +121,8 @@ pub trait FilterGallerySource: Send + Sync {
/// The job that renders `effects` over `visible` at `zoom` into the preview.
fn render(&self, effects: &[EffectLayer], visible: PixelRect, zoom: f64) -> Job<PreviewDone, String>;
/// The thumbnails the filter tree shows.
// P3(dialogs-w11): dl.K59 — default body until the app's sources implement it.
fn thumb_source(&self) -> &dyn craft_ui::primitives::textures::ThumbSource<GalleryThumb> {
todo!("dl.K59")
}
/// The thumbnails the filter tree shows: each filter applied to a small crop of the layer.
fn thumb_source(&self) -> &dyn ThumbSource<GalleryThumb>;
}
/// The catalog as one pass reads it: the folders and every filter in them, looked up by key.
+230 -184
View File
@@ -7,11 +7,12 @@
//! effect-layer stack ([`EffectStack`]) and the preview's status. No tool strip and no options bar; a drag on
//! the preview pans (the Hand tool is the canvas's only tool).
//!
//! The session is the stack ([`FilterGallerySession`]) with [`EditHistory`] undo. The app's catalog
//! ([`FilterCatalog`]) names the filters and their parameters, its thumbnail source renders the folders'
//! pictures, and its [`FilterGallerySource`] renders the preview of the visible part
//! ([`FilterGalleryWorkspace::visible`]) as a job whenever the stack, the zoom or the visible part change. OK
//! runs `filter.filterGallery` with the effects; a smart filter opened again passes its recorded effects.
//! The session is the stack ([`FilterGallerySession`]) with [`EditHistory`] undo. The app's
//! [`FilterGallerySource`] holds its catalog ([`FilterCatalog`]), which names the filters and their parameters,
//! the thumbnail source that renders the folders' pictures, and the preview of the visible part
//! ([`FilterGalleryWorkspace::visible`]), rendered as a job whenever the stack, the zoom, the visible part or the
//! source change. The app hosts the workspace as a `HostedWorkspace`; OK runs `filter.filterGallery` with the
//! effects; a smart filter opened again passes its recorded effects.
//!
//! Files: `catalog` and `session`; `tree`, `stack`, `parameters` and this file's body.
//!
@@ -45,17 +46,18 @@ use craft_theme::Srgba;
use craft_ui::canvas::{NavigationOptions, PixelRect, ViewCommands};
use craft_ui::contract::{Bind, Commands as _, Pattern, Pending, Remember as _, ShowContainer as _};
use craft_ui::dialog::{
DialogOutput, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowZoomBar,
SideFooter,
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace,
FullWindowZoomBar, SideFooter, WorkspaceCx, WorkspacePass,
};
use craft_ui::patterns::form_dialogs::FieldValue;
use craft_ui::patterns::form_dialogs::{FieldValue, set_param_field};
use craft_ui::primitives::Checker;
use craft_ui::primitives::textures::{ThumbSource, Thumbnails};
use craft_ui::primitives::textures::{ThumbnailOptions, Thumbnails};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::runtime::words::CommonWords;
use craft_ui::sections::{DialogRole, FooterButton};
use egui::Ui;
use egui::{Context, Ui};
use serde_json::{Value, json};
use crate::ui::wide_angle::PreviewDone;
@@ -109,40 +111,22 @@ pub enum FilterGalleryEvent {
PickColor(ColorRequest),
}
/// What [`FilterGalleryWorkspace::show`] reports.
#[derive(Debug)]
#[non_exhaustive]
pub struct FilterGalleryOutput {
/// What happened this pass, in order.
pub events: Vec<FilterGalleryEvent>,
/// A color parameter's swatch pressed: the app opens its picker and answers into the selected
/// effect's fields ([`FilterGalleryWorkspace::set_color`]).
pub pick_color: Option<ColorRequest>,
/// The dialog: its response, why it closed and which footer button was picked (0 is OK, 1 is Cancel).
pub dialog: DialogOutput,
/// The undo step name of every stack change: the workspace's name.
fn history_name(words: &FilterGalleryWords) -> Arc<str> {
words.name.clone().as_str().into()
}
impl FilterGalleryOutput {
/// OK was chosen.
pub fn accepted(&self) -> bool {
self.dialog.picked == Some(OK)
}
}
/// The footer button that accepts.
const OK: usize = 0;
/// What one pass of the two closures shares.
struct Pass<'w> {
workspace: &'w mut FilterGalleryWorkspace,
events: Vec<FilterGalleryEvent>,
pick_color: Option<ColorRequest>,
}
/// The Filter Gallery workspace.
/// The Filter Gallery workspace, hosted as a [`FullWindowWorkspace`] over the app's [`FilterGallerySource`]: its
/// pass reports [`FilterGalleryEvent`]s, and OK answers the session.
///
/// Keys: the zoom commands zoom the preview, never the canvas behind; ⌘Z and ⇧⌘Z step the stack's history (a field
/// being edited steps its own text first); Enter OK, Esc Cancel.
///
/// Automation fields: `effects` (the stack as `[{filter, params, visible}]`), `select` (the selected layer's
/// index) and `zoom` (`"fit"` or the zoom, 1 = 100 %), which it lists and sets; and the actions `add` and `delete`
/// (`true`), `toggle` (a layer's index: its eye flips), `move` (`{from, to}`), `filter` (a filter key for the
/// selected layer) and `params` (values merged into the selected layer's parameters). Each change is one undo step
/// and is reported by the next pass.
#[derive(Pattern)]
pub struct FilterGalleryWorkspace {
session: FilterGallerySession,
@@ -194,122 +178,6 @@ impl FilterGalleryWorkspace {
}
}
/// Shows the workspace for this pass: the title (the selected effect's filter name as the subject's prefix,
/// PhotoCraft's "{effect} (layer, 66%)"), the side columns at the end edge (settings with the top footer
/// outermost, then the folders), the zoom bar (progress while the preview renders, else the render's time),
/// and the canvas over `source`'s preview with the Hand tool. Changes go through
/// [`FilterGallerySession::apply`] and are recorded in the history; a change, a zoom or a pan starts a new
/// preview job of `source`.
///
/// `thumb_source` renders the pictures `thumbs` asks for (one per filter, the filter applied to a small
/// crop of the layer).
pub fn show(
&mut self,
ui: &mut Ui,
catalog: &dyn FilterCatalog,
thumbs: &Thumbnails<GalleryThumb>,
thumb_source: &dyn ThumbSource<GalleryThumb>,
source: &dyn FilterGallerySource,
) -> FilterGalleryOutput {
let env = Env::of(ui);
let words = env.words::<FilterGalleryWords>();
let common = env.words::<CommonWords>();
let index = FilterIndex::of(catalog);
let events = std::mem::take(&mut self.queued);
self.selected = self.selected.min(self.session.effects.len().saturating_sub(1));
let name = self.session.effects.get(self.selected).map_or_else(|| words.name.clone(), |effect| index.label(&effect.filter));
let title = FullWindowTitle::new(name).subject(self.subject.clone()).zoom(self.percent).label(&env);
let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)];
let history_name: Arc<str> = words.name.clone().as_str().into();
let navigation = self.navigation;
let checkerboard = self.checkerboard;
let pass = RefCell::new(Pass { workspace: self, events, pick_color: None });
let mut dialog = FullWindowDialog::new(title)
.buttons(buttons)
.side_footer(SideFooter::top())
.sides(|ui, _| {
let mut pass = pass.borrow_mut();
let current = pass.workspace.selected;
let mut changes = Vec::new();
let mut stack_pick = None;
let mut pick_color = None;
FullWindowSide::new(words.settings.clone()).headerless().show(ui, |ui, _| {
if let Some(effect) = pass.workspace.session.effects.get(current) {
let parameters = EffectParameters::new(current, effect, &index).show(ui);
changes.extend(parameters.change);
pick_color = parameters.pick_color;
}
let stack = EffectStack::new(&pass.workspace.session.effects, current, &index).show(ui);
stack_pick = stack.selected;
changes.extend(stack.change);
FullWindowStatus::of(&pass.workspace.status).show(ui);
});
pass.pick_color = pick_color;
for change in changes {
pass.apply(change, catalog, &history_name);
}
if let Some(pick) = stack_pick {
pass.workspace.selected = pick.min(pass.workspace.session.effects.len().saturating_sub(1));
}
let current_filter =
pass.workspace.session.effects.get(pass.workspace.selected).map(|effect| effect.filter.clone()).unwrap_or_default();
let mut tree_pick = None;
FullWindowSide::new(words.filters.clone()).headerless().show(ui, |ui, _| {
tree_pick = FilterTree::new(&index, &current_filter, thumbs, thumb_source).show(ui).picked;
});
if let Some(filter) = tree_pick {
let at = pass.workspace.selected;
pass.apply(EffectChange::set_filter(at, filter), catalog, &history_name);
}
})
.show(ui, |ui, cx| {
let mut pass = pass.borrow_mut();
let workspace = &mut *pass.workspace;
while let Some(step) = cx.take_step(workspace.history.can_undo(), workspace.history.can_redo()) {
workspace.step(step);
}
let mut view = workspace.view;
while let Some((command, _)) = cx.take_command::<ViewCommands>() {
view.apply(command);
}
let (visible, zoom) = workspace.visible();
let key = (workspace.revision, visible, zoom.to_bits());
let effects = &workspace.session.effects;
let status = cx.pending(key, || source.render(effects, visible, zoom)).clone();
let mut bar = FullWindowZoomBar::new(Bind::bound(&mut view)).progress(FullWindowStatus::of(&status).progress());
if let Pending::Ready(done) = &status {
let milliseconds = done.timing.as_millis().to_string();
bar = bar.note(Label::from(words.preview_ms.fill(&[("n", milliseconds.as_str())])));
}
bar.show(ui);
let mut canvas = FullWindowCanvas::new(Bind::bound(&mut view), source.preview()).navigation(navigation);
if let Some(checker) = checkerboard {
canvas = canvas.checkerboard(checker);
}
canvas.show(ui);
(view, status)
});
// Once per pass, after the real run: the view it settled and the render status are stored.
dialog.settle(|_, (view, status)| {
let view = std::mem::take(view);
let workspace = &mut *pass.borrow_mut().workspace;
workspace.status = status.clone();
workspace.shown = Some(view.view());
workspace.percent = view.zoom_percent();
workspace.zoom = view.device_zoom();
workspace.view = view;
});
let Pass { workspace, mut events, pick_color } = pass.into_inner();
events.append(&mut workspace.queued);
if workspace.selected != workspace.reported {
workspace.reported = workspace.selected;
events.push(FilterGalleryEvent::Select(workspace.selected));
}
FilterGalleryOutput { events, pick_color, dialog: dialog.output }
}
/// The effect-layer stack as it is now.
pub fn session(&self) -> &FilterGallerySession {
&self.session
@@ -328,7 +196,7 @@ impl FilterGalleryWorkspace {
(PixelRect::new(part.x0 as i32, part.y0 as i32, part.x1 as i32, part.y1 as i32), self.zoom)
}
/// The color the app picked for a [`FilterGalleryOutput::pick_color`] request: written into the request's
/// The color the app picked for a [`FilterGalleryEvent::PickColor`] request: written into the request's
/// `key` of the selected effect (one undo step).
pub fn set_color(&mut self, key: &str, color: Srgba) {
let index = self.selected.min(self.session.effects.len().saturating_sub(1));
@@ -358,50 +226,228 @@ impl FilterGalleryWorkspace {
self.revision += 1;
self.history.record(&EditEvent::set(Mixed::Same(before), self.session.clone(), name.clone(), None));
}
}
impl Pass<'_> {
/// Applies `change` through the catalog, records it and reports it.
fn apply(&mut self, change: EffectChange, catalog: &dyn FilterCatalog, name: &Arc<str>) {
let workspace = &mut *self.workspace;
let before = workspace.session.clone();
let mut selected = workspace.selected;
if workspace.session.apply(change.clone(), catalog, &mut selected) {
workspace.selected = selected;
workspace.record(before, name);
self.events.push(FilterGalleryEvent::Stack(change));
/// Applies `change` through `catalog`, records it as one undo step named `name` and queues its report for the
/// next pass to give: the one path of every stack change, from the columns and from automation. Returns whether
/// the stack changed.
fn change(&mut self, change: EffectChange, catalog: &dyn FilterCatalog, name: &Arc<str>) -> bool {
let before = self.session.clone();
let mut selected = self.selected;
if !self.session.apply(change.clone(), catalog, &mut selected) {
return false;
}
self.selected = selected;
self.record(before, name);
self.queued.push(FilterGalleryEvent::Stack(change));
true
}
/// The selected layer's index, kept on a layer that exists.
fn clamped_selection(&self) -> usize {
self.selected.min(self.session.effects.len().saturating_sub(1))
}
/// Sets the automation field `field` to `value` over `catalog`; `Err` says why it refused.
fn set_field(&mut self, catalog: &dyn FilterCatalog, name: &Arc<str>, field: &str, value: Value) -> Result<(), String> {
let rejects = |value: &Value| FieldRefusal::Rejects(value).message(field);
let index = |value: &Value| value.as_u64().and_then(|at| usize::try_from(at).ok());
let selected = self.clamped_selection();
let change = match field {
"effects" => {
let effects: Vec<EffectLayer> = serde_json::from_value(value.clone()).map_err(|_| rejects(&value))?;
if effects.is_empty() || effects.iter().any(|effect| catalog.filter(&effect.filter).is_none()) {
return Err(rejects(&value));
}
EffectChange::Replace { effects }
}
"select" => {
let at = index(&value).ok_or_else(|| rejects(&value))?;
self.selected = at.min(self.session.effects.len().saturating_sub(1));
return Ok(());
}
"zoom" => {
match (value.as_str(), value.as_f64()) {
(Some("fit"), _) => self.view.apply(ViewCommands::FitOnScreen),
(_, Some(zoom)) if zoom.is_finite() && zoom > 0.0 => self.view.set_device_zoom(zoom),
_ => return Err(rejects(&value)),
};
return Ok(());
}
"add" | "delete" => match value.as_bool() {
Some(true) if field == "add" => EffectChange::Add,
Some(true) => EffectChange::Delete,
Some(false) => return Ok(()),
None => return Err(rejects(&value)),
},
"toggle" => {
let at = index(&value).ok_or_else(|| rejects(&value))?;
let effect = self.session.effects.get(at).ok_or_else(|| rejects(&value))?;
EffectChange::set_visible(at, !effect.visible)
}
"move" => {
let count = self.session.effects.len();
let (from, to) = (value.get("from").and_then(index), value.get("to").and_then(index));
let (Some(from), Some(to)) = (from, to) else { return Err(rejects(&value)) };
if from >= count || to >= count {
return Err(rejects(&value));
}
EffectChange::move_to(from, to)
}
"filter" => {
let key = value.as_str().filter(|key| catalog.filter(key).is_some()).ok_or_else(|| rejects(&value))?;
EffectChange::set_filter(selected, key)
}
"params" => {
let (Some(effect), Some(entries)) = (self.session.effects.get(selected), value.as_object()) else { return Err(rejects(&value)) };
let filter = catalog.filter(&effect.filter).ok_or_else(|| FieldRefusal::Inactive.message(field))?;
let mut fields = effect.fields.clone();
for (key, entry) in entries {
set_param_field(&filter.params, &mut fields, key, entry.clone())?;
}
EffectChange::with_fields(selected, fields)
}
_ => return Err(FieldRefusal::Unknown.message(field)),
};
self.change(change, catalog, name);
Ok(())
}
}
// P3(dialogs-w11): dl.K59 — the workspace's trait surface; `show` and the automation fields are written in phase 3.
impl craft_ui::dialog::FullWindowWorkspace for FilterGalleryWorkspace {
impl FullWindowWorkspace for FilterGalleryWorkspace {
type Source = dyn FilterGallerySource;
type Event = FilterGalleryEvent;
type Result = FilterGallerySession;
const KEY: &'static str = "filter.filterGallery";
fn show(
&mut self,
ui: &mut egui::Ui,
cx: craft_ui::dialog::WorkspaceCx<'_, Self::Source>,
) -> craft_ui::dialog::WorkspacePass<Self::Event, Self::Result> {
let _ = (ui, cx);
todo!("dl.K59")
/// Shows the workspace for this pass: the title (the selected effect's filter name as the subject's prefix,
/// PhotoCraft's "{effect} (layer, 66%)"), the side columns at the end edge (settings with the top footer
/// outermost, then the folders with the source's thumbnails), the zoom bar (progress while the preview renders,
/// else the render's time), and the canvas over the source's preview with the Hand tool. Changes go through
/// [`FilterGallerySession::apply`] and are recorded in the history; a change, a zoom, a pan or a new source
/// starts a new preview job. A swatch press reports [`FilterGalleryEvent::PickColor`].
///
/// OK closes at once: the gallery never holds its OK (`cx.hold_ok` is not read).
fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass<FilterGalleryEvent, FilterGallerySession> {
let WorkspaceCx { source, revision: source_revision, open, .. } = cx;
let (catalog, thumb_source) = (source.catalog(), source.thumb_source());
let thumbs = Thumbnails::<GalleryThumb>::in_context(ui.ctx(), "filterGallery.thumbs", ThumbnailOptions::default());
let env = Env::of(ui);
let words = env.words::<FilterGalleryWords>();
let common = env.words::<CommonWords>();
let index = FilterIndex::of(catalog);
let mut events = std::mem::take(&mut self.queued);
self.selected = self.clamped_selection();
let name = self.session.effects.get(self.selected).map_or_else(|| words.name.clone(), |effect| index.label(&effect.filter));
let title = FullWindowTitle::new(name).subject(self.subject.clone()).zoom(self.percent).label(&env);
let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)];
let history_name = history_name(&words);
let navigation = self.navigation;
let checkerboard = self.checkerboard;
let shared = RefCell::new(&mut *self);
let mut dialog = FullWindowDialog::new(title)
.opened(open)
.buttons(buttons)
.side_footer(SideFooter::top())
.sides(|ui, _| {
let mut workspace = shared.borrow_mut();
let current = workspace.selected;
let mut changes = Vec::new();
let mut stack_pick = None;
let mut pick_color = None;
FullWindowSide::new(words.settings.clone()).headerless().show(ui, |ui, _| {
if let Some(effect) = workspace.session.effects.get(current) {
let parameters = EffectParameters::new(current, effect, &index).show(ui);
changes.extend(parameters.change);
pick_color = parameters.pick_color;
}
let stack = EffectStack::new(&workspace.session.effects, current, &index).show(ui);
stack_pick = stack.selected;
changes.extend(stack.change);
FullWindowStatus::of(&workspace.status).show(ui);
});
if let Some(request) = pick_color {
workspace.queued.push(FilterGalleryEvent::PickColor(request));
}
for change in changes {
workspace.change(change, catalog, &history_name);
}
if let Some(pick) = stack_pick {
workspace.selected = pick.min(workspace.session.effects.len().saturating_sub(1));
}
let current_filter = workspace.session.effects.get(workspace.selected).map(|effect| effect.filter.clone()).unwrap_or_default();
let mut tree_pick = None;
FullWindowSide::new(words.filters.clone()).headerless().show(ui, |ui, _| {
tree_pick = FilterTree::new(&index, &current_filter, &thumbs, thumb_source).show(ui).picked;
});
if let Some(filter) = tree_pick {
let at = workspace.selected;
workspace.change(EffectChange::set_filter(at, filter), catalog, &history_name);
}
})
.show(ui, |ui, cx| {
let mut workspace = shared.borrow_mut();
let workspace = &mut **workspace;
while let Some(step) = cx.take_step(workspace.history.can_undo(), workspace.history.can_redo()) {
workspace.step(step);
}
let mut view = workspace.view;
while let Some((command, _)) = cx.take_command::<ViewCommands>() {
view.apply(command);
}
let (visible, zoom) = workspace.visible();
// A new source (a document edit under the open gallery) previews again, and a late preview of the old
// pixels lands under a key no pass asks for.
let key = (workspace.revision, source_revision, visible, zoom.to_bits());
let effects = &workspace.session.effects;
let status = cx.pending(key, || source.render(effects, visible, zoom)).clone();
let mut bar = FullWindowZoomBar::new(Bind::bound(&mut view)).progress(FullWindowStatus::of(&status).progress());
if let Pending::Ready(done) = &status {
let milliseconds = done.timing.as_millis().to_string();
bar = bar.note(Label::from(words.preview_ms.fill(&[("n", milliseconds.as_str())])));
}
bar.show(ui);
let mut canvas = FullWindowCanvas::new(Bind::bound(&mut view), source.preview()).navigation(navigation);
if let Some(checker) = checkerboard {
canvas = canvas.checkerboard(checker);
}
canvas.show(ui);
(view, status)
});
// Once per pass, after the real run: the view it settled and the render status are stored.
dialog.settle(|_, (view, status)| {
let view = std::mem::take(view);
let mut workspace = shared.borrow_mut();
workspace.status = status.clone();
workspace.shown = Some(view.view());
workspace.percent = view.zoom_percent();
workspace.zoom = view.device_zoom();
workspace.view = view;
});
let workspace = shared.into_inner();
events.append(&mut workspace.queued);
if workspace.selected != workspace.reported {
workspace.reported = workspace.selected;
events.push(FilterGalleryEvent::Select(workspace.selected));
}
let result = dialog.output.result(|| workspace.session.clone());
WorkspacePass::new(dialog.output.response, events).result(result)
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K59")
fn json_fields(&self) -> Option<Value> {
let zoom = if self.view.is_fit() { json!("fit") } else { json!(self.view.device_zoom()) };
let effects = serde_json::to_value(&self.session.effects).unwrap_or_default();
Some(json!({ "effects": effects, "select": self.clamped_selection(), "zoom": zoom }))
}
fn set_json_field(&mut self, ctx: &egui::Context, source: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, source, field, value);
todo!("dl.K59")
fn set_json_field(&mut self, ctx: &Context, source: &Self::Source, field: &str, value: Value) -> Result<(), String> {
let name = history_name(&Env::of_root(ctx).words::<FilterGalleryWords>());
self.set_field(source.catalog(), &name, field, value)
}
fn confirm(&mut self, ctx: &egui::Context, source: &Self::Source) -> Option<Self::Result> {
let _ = (ctx, source);
todo!("dl.K59")
fn confirm(&mut self, _: &Context, _: &Self::Source) -> Option<FilterGallerySession> {
Some(self.session.clone())
}
}
@@ -4,8 +4,10 @@ use craft_ui::patterns::form_dialogs::DialogFields;
use super::catalog::FilterCatalog;
/// One effect layer: a filter, its fields (the catalog's parameters) and its eye.
/// One effect layer: a filter, its fields (the catalog's parameters) and its eye. It serialises as
/// `{filter, params, visible}`, with a choice by its option's name, as the engine's effects do.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct EffectLayer {
/// The filter's key in the catalog.
@@ -135,6 +137,11 @@ impl FilterGallerySession {
}
_ => false,
},
// The stack never empties: a gallery always has one layer to show.
EffectChange::Replace { effects } if !effects.is_empty() && effects != self.effects => {
self.effects = effects;
true
}
EffectChange::Add => {
let copy = self.effects[current].clone();
self.effects.insert(current + 1, copy);
+24 -11
View File
@@ -8,16 +8,17 @@ use std::time::Duration;
use craft_theme::Srgba;
use craft_ui::canvas::{PixelRect, RasterSource};
use craft_ui::contract::Job;
use craft_ui::contract::{Bind, Job};
use craft_ui::dialog::{FullWindowWorkspace as _, WorkspaceCx};
use craft_ui::patterns::form_dialogs::{Param, ParamKind};
use craft_ui::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails};
use craft_ui::primitives::textures::{FakeThumbSource, ThumbSource, ThumbnailOptions, Thumbnails};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use craft_ui::value_drag::SliderScale;
use egui::Ui;
use super::{
EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGalleryOpen, FilterGallerySession,
FilterGallerySource, FilterGalleryWorkspace, FilterIndex, FilterTree, GalleryFilter, GalleryThumb,
EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGalleryEvent, FilterGalleryOpen,
FilterGallerySession, FilterGallerySource, FilterGalleryWorkspace, FilterIndex, FilterTree, GalleryFilter, GalleryThumb,
};
use crate::ui::mock_image::MockImage;
use crate::ui::wide_angle::PreviewDone;
@@ -110,13 +111,23 @@ fn start() -> FilterGallerySession {
session
}
/// The picture under the effects, with a render that is done at once or never finishes.
/// The app's side of the workspace: the catalog, the thumbnails, and the picture under the effects, with a render
/// that is done at once or never finishes.
struct MockSource {
image: MockImage,
rendering: bool,
thumbs: FakeThumbSource<GalleryThumb>,
}
impl FilterGallerySource for MockSource {
fn catalog(&self) -> &dyn FilterCatalog {
&MockGallery
}
fn thumb_source(&self) -> &dyn ThumbSource<GalleryThumb> {
&self.thumbs
}
fn preview(&self) -> &dyn RasterSource {
&self.image
}
@@ -136,19 +147,21 @@ impl FilterGallerySource for MockSource {
}
}
/// Shows the workspace over the session the story keeps.
/// Shows the workspace over the session the story keeps, its open state bound to the story's.
fn workspace(ui: &mut Ui, data: &mut StoryData, rendering: bool) -> StoryOutput {
let image = MockImage::default();
let session = data.value("session", start()).clone();
let mut workspace = FilterGalleryWorkspace::new(FilterGalleryOpen::new(image.size(), "Photo", session));
let thumbs = Thumbnails::<GalleryThumb>::in_context(ui.ctx(), "gallery-story-thumbs", ThumbnailOptions::default());
let out = workspace.show(ui, &MockGallery, &thumbs, &FakeThumbSource::<GalleryThumb>::new(), &MockSource { image, rendering });
let source: &dyn FilterGallerySource = &MockSource { image, rendering, thumbs: FakeThumbSource::new() };
let pass = workspace.show(ui, WorkspaceCx::new(source, Bind::bound(data.value("open", true))));
// A swatch press asks the app for a color; the story has no picker.
if let Some(request) = out.pick_color {
workspace.set_color(&request.key, Srgba::from_rgb_array([0.2, 0.7, 0.9]));
for event in &pass.events {
if let FilterGalleryEvent::PickColor(request) = event {
workspace.set_color(&request.key, Srgba::from_rgb_array([0.2, 0.7, 0.9]));
}
}
*data.value("session", start()) = workspace.session().clone();
out.dialog.into()
StoryOutput::from(pass.response)
}
#[story(FilterGalleryWorkspace, covers = [Default], drive = Drive::Never)]
+29 -15
View File
@@ -9,15 +9,16 @@ use std::time::Duration;
use craft_behavior::PixelSize;
use craft_host::{AppInfo, Host};
use craft_imaging::ui::filter_gallery::{
EffectChange, EffectLayer, FilterCatalog, FilterCategory, FilterGalleryEvent, FilterGalleryOpen, FilterGalleryOutput, FilterGallerySession,
FilterGallerySource, FilterGalleryWorkspace, GalleryFilter, GalleryThumb,
EffectChange, EffectLayer, FilterCatalog, FilterCategory, FilterGalleryEvent, FilterGalleryOpen, FilterGallerySession, FilterGallerySource,
FilterGalleryWorkspace, GalleryFilter, GalleryThumb,
};
use craft_imaging::ui::wide_angle::PreviewDone;
use craft_ui::canvas::{PixelRect, RasterSource};
use craft_ui::contract::Job;
use craft_ui::contract::{Bind, Job};
use craft_ui::dialog::{FullWindowWorkspace as _, WorkspaceCx};
use craft_ui::patterns::form_dialogs::{Param, ParamKind};
use craft_ui::primitives::Revision;
use craft_ui::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails};
use craft_ui::primitives::textures::{FakeThumbSource, ThumbSource};
use craft_ui::testing::{Fixture, trial};
use craft_ui::value_drag::SliderScale;
use egui::{Color32, ColorImage, Key, Modifiers, Vec2};
@@ -91,8 +92,11 @@ fn gallery_stack_new_delete_reorder_and_eye() {
// Undo of a Delete gives the layer back and clamps the selection.
/// A flat picture the size of the layer, whose render finishes only when `done`.
/// The app's side: the catalog, the thumbnails, and a flat picture the size of the layer, whose render finishes only
/// when `done`.
struct Flat {
catalog: Catalog,
thumbs: FakeThumbSource<GalleryThumb>,
done: bool,
}
@@ -115,6 +119,14 @@ impl RasterSource for Flat {
}
impl FilterGallerySource for Flat {
fn catalog(&self) -> &dyn FilterCatalog {
&self.catalog
}
fn thumb_source(&self) -> &dyn ThumbSource<GalleryThumb> {
&self.thumbs
}
fn preview(&self) -> &dyn RasterSource {
self
}
@@ -133,31 +145,33 @@ impl FilterGallerySource for Flat {
}
}
/// A workspace in a fixture and what its passes reported.
/// A workspace in a fixture and the events its passes reported.
struct Rig {
fixture: Fixture,
workspace: Rc<RefCell<FilterGalleryWorkspace>>,
outputs: Rc<RefCell<Vec<FilterGalleryOutput>>>,
events: Rc<RefCell<Vec<FilterGalleryEvent>>>,
}
/// Shows the workspace through its trait `show`, as a host does, with the open state kept across passes.
fn rig(session: FilterGallerySession, done: bool) -> Rig {
let workspace = Rc::new(RefCell::new(FilterGalleryWorkspace::new(FilterGalleryOpen::new(LAYER, "Layer 1", session))));
let outputs = Rc::new(RefCell::new(Vec::new()));
let (shown, sink) = (workspace.clone(), outputs.clone());
let source = Flat { done };
let events = Rc::new(RefCell::new(Vec::new()));
let (shown, sink) = (workspace.clone(), events.clone());
let source = Flat { catalog: Catalog, thumbs: FakeThumbSource::new(), done };
let mut open = true;
let mut fixture = Fixture::new(move |ui| {
let thumbs = Thumbnails::<GalleryThumb>::in_context(ui.ctx(), "gallery-test-thumbs", ThumbnailOptions::default());
let out = shown.borrow_mut().show(ui, &Catalog, &thumbs, &FakeThumbSource::<GalleryThumb>::new(), &source);
sink.borrow_mut().push(out);
let source: &dyn FilterGallerySource = &source;
let pass = shown.borrow_mut().show(ui, WorkspaceCx::new(source, Bind::bound(&mut open)));
sink.borrow_mut().extend(pass.events);
});
fixture.host(Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).build()));
fixture.room(WINDOW).settle();
Rig { fixture, workspace, outputs }
Rig { fixture, workspace, events }
}
impl Rig {
fn events(&self) -> Vec<FilterGalleryEvent> {
self.outputs.borrow().iter().flat_map(|out| out.events.clone()).collect()
self.events.borrow().clone()
}
}
+18 -5
View File
@@ -125,25 +125,38 @@ impl<'a> FullWindowDialog<'a> {
/// viewports are unavailable it fills the main window. The dialog's focus policy moves into the fallback overlay.
#[must_use]
pub fn own_window(mut self, spec: WindowSpec) -> Self {
self.props.mount = Mount::viewport_with(Overlay::full_window(self.props.focus), spec);
self.props.focus = FocusPolicy::NONE;
// A viewport mount takes its scope from the fallback overlay and holds `props.focus` at none.
let focus = std::mem::replace(self.focus_mut(), FocusPolicy::NONE);
self.props.mount = Mount::viewport_with(Overlay::full_window(focus), spec);
self
}
/// Who gets Enter: the dialog's submit, or the body.
#[must_use]
pub fn enter(mut self, rule: EnterRule) -> Self {
self.props.focus = FocusPolicy { enter: rule, ..self.props.focus };
let focus = self.focus_mut();
*focus = FocusPolicy { enter: rule, ..*focus };
self
}
/// What takes the keyboard focus when the dialog opens.
#[must_use]
pub fn initial_focus(mut self, initial: Initial) -> Self {
self.props.focus = self.props.focus.initial(initial);
let focus = self.focus_mut();
*focus = focus.initial(initial);
self
}
/// The dialog's focus policy, wherever its mount keeps it: the fallback overlay's in its own window, else the
/// container's. Every builder and the footer go through it, so the order of `own_window` and the others does not
/// matter.
fn focus_mut(&mut self) -> &mut FocusPolicy {
match &mut self.props.mount {
Mount::Viewport { fallback, .. } => &mut fallback.focus,
_ => &mut self.props.focus,
}
}
/// The dialog's own command scope, a child of [`ViewCommands::SCOPE`]: the dialog is an instance of `scope` and still
/// of the view scope. Both scopes' chords act wherever the focus is inside the dialog, and the view commands still
/// reach the zoom bar; `scope`'s commands reach the dialog's body by `take_command` on its context.
@@ -275,7 +288,7 @@ impl Container for FullWindowDialog<'_> {
}
fn footer(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) {
let enter = self.props.focus.enter == EnterRule::Submit;
let enter = self.focus_mut().enter == EnterRule::Submit;
let (content, buttons) = (&mut self.footer, &self.buttons);
let (picked, guard, on_pick, settle) = (&mut self.picked, &mut self.guard, &mut self.on_pick, &mut self.settle);
if self.sides.is_some() {
@@ -14,6 +14,15 @@ use crate::runtime::env::Label;
///
/// The events of the pass that finishes the workspace go with it: a workspace whose app needs them folds them into
/// its [`Result`](FullWindowWorkspace::Result).
///
/// - Automation: [`json_fields`](FullWindowWorkspace::json_fields), [`set_json_field`](FullWindowWorkspace::set_json_field)
/// and [`confirm`](FullWindowWorkspace::confirm) are what the host's `ui.dialog` surface reaches. Each key applies or
/// is refused on its own; the events a set produces are queued by the workspace and reported by its next pass.
/// - Source revision: [`WorkspaceCx::revision`] moves with each new source; the workspace adds it to its pending key.
/// - Held OK: under [`WorkspaceCx::hold_ok`] the workspace makes its Accept button `stays_open`, disables it while
/// [`WorkspaceCx::ok_waits`], and reports the answer OK would give in [`WorkspacePass::held`]. The app takes it
/// ([`HostedWorkspace::take_ok`]) and answers ([`HostedWorkspace::answer_ok`]); a refusal reaches
/// [`ok_failed`](FullWindowWorkspace::ok_failed).
pub trait FullWindowWorkspace: Send + 'static {
/// What the workspace reads from the app each pass, usually a `dyn` trait of the workspace's crate.
type Source: ?Sized + Send + Sync;
@@ -69,6 +78,14 @@ pub struct WorkspaceCx<'a, S: ?Sized> {
pub ok_waits: bool,
}
impl<'a, S: ?Sized> WorkspaceCx<'a, S> {
/// A pass over `source` with the open state bound to `open`, at the first revision, with OK not held: what a
/// workspace shown outside a [`HostedWorkspace`] gets. The host's stories and trials build it.
pub fn new(source: &'a S, open: Bind<'a, bool>) -> Self {
WorkspaceCx { source, revision: 0, open, hold_ok: false, ok_waits: false }
}
}
/// What one pass of a [`FullWindowWorkspace`] reports.
#[non_exhaustive]
pub struct WorkspacePass<E, R> {
@@ -81,22 +98,20 @@ pub struct WorkspacePass<E, R> {
pub result: Option<DialogResult<R>>,
/// The result OK would give, reported in the pass the Accept button is picked under `cx.hold_ok`; `result`
/// stays `None` then.
// P3(dialogs-w11): dl.K57 `WorkspacePass::held`
pub held: Option<R>,
}
impl<E, R> WorkspacePass<E, R> {
/// A pass with `events` that leaves the workspace open.
pub fn new(response: Response, events: Vec<E>) -> Self {
WorkspacePass { response, events, result: None, held: None } // P3(dialogs-w11): dl.K57
WorkspacePass { response, events, result: None, held: None }
}
/// The result a held OK gives this pass.
// P3(dialogs-w11): dl.K57 `WorkspacePass::held`
#[must_use]
pub fn held(self, held: Option<R>) -> Self {
let _ = (self, held);
todo!("dl.K57")
pub fn held(mut self, held: Option<R>) -> Self {
self.held = held;
self
}
/// How the workspace finished this pass.
@@ -109,6 +124,8 @@ impl<E, R> WorkspacePass<E, R> {
/// A [`FullWindowWorkspace`] the [`DialogHost`](crate::dialog::DialogHost) owns, with the app's source. It keeps the
/// events of each pass until the app takes them, and finishes as the workspace's pass says: OK's answer, or Cancel.
/// It forwards the host's automation calls (`json_fields`, `set_json_field`, `confirm`) to the workspace with its
/// source.
///
/// ```ignore
/// dialogs.open(HostedWorkspace::new(LiquifyWorkspace::new(open), Arc::new(source)));
@@ -121,6 +138,19 @@ impl<E, R> WorkspacePass<E, R> {
/// doc.run("filter.liquify", steps);
/// }
/// ```
///
/// A workspace whose OK the app checks first opens [`held_ok`](HostedWorkspace::held_ok): OK files its answer and
/// the workspace stays shown until the app answers.
///
/// ```ignore
/// dialogs.open(HostedWorkspace::new(FillWorkspace::new(open), Arc::new(source)).held_ok());
/// dialogs.run(ui);
/// if let Some(fill) = dialogs.get_mut::<HostedWorkspace<FillWorkspace>>()
/// && let Some(session) = fill.take_ok()
/// {
/// fill.answer_ok(doc.run("edit.contentAwareFill", session).map_err(|error| error.label()));
/// }
/// ```
pub struct HostedWorkspace<W: FullWindowWorkspace> {
id: DialogId,
workspace: W,
@@ -129,7 +159,14 @@ pub struct HostedWorkspace<W: FullWindowWorkspace> {
open: bool,
revision: u64,
hold_ok: bool,
/// From the filed OK until the app's answer: the workspace disables its OK.
ok_waits: bool,
/// The held OK's answer, kept until the app answers it.
filed: Option<W::Result>,
/// `take_ok` has not handed out `filed` yet.
untaken: bool,
/// The app accepted the held OK: the next pass finishes with `filed`.
finish: bool,
#[cfg(feature = "testing")]
facts: crate::testing::StoryOutput,
}
@@ -146,6 +183,9 @@ impl<W: FullWindowWorkspace> HostedWorkspace<W> {
revision: 0,
hold_ok: false,
ok_waits: false,
filed: None,
untaken: false,
finish: false,
#[cfg(feature = "testing")]
facts: crate::testing::StoryOutput::default(),
}
@@ -175,27 +215,50 @@ impl<W: FullWindowWorkspace> HostedWorkspace<W> {
}
/// The OK the workspace is holding for the app to act on, once; `None` when none is held.
pub fn take_ok(&mut self) -> Option<W::Result> {
todo!("dl.K57")
pub fn take_ok(&mut self) -> Option<W::Result>
where
W::Result: Clone,
{
if !std::mem::take(&mut self.untaken) {
return None;
}
self.filed.clone()
}
/// The app's answer to a held OK: `Ok` closes the workspace with it, `Err(reason)` keeps it open and shows
/// `reason`.
/// The app's answer to a held OK: `Ok` closes the workspace with it in the next pass, `Err(reason)` keeps it
/// open with OK enabled again and hands `reason` to [`FullWindowWorkspace::ok_failed`]. Does nothing while no OK
/// is held.
pub fn answer_ok(&mut self, answer: Result<(), Label>) {
let _ = answer;
todo!("dl.K57")
if self.filed.is_none() {
return;
}
match answer {
Ok(()) => self.finish = true,
Err(reason) => {
self.filed = None;
self.untaken = false;
self.ok_waits = false;
self.workspace.ok_failed(reason);
}
}
}
/// The app's source the workspace shows.
// P3(dialogs-w11): dl.K57 `HostedWorkspace::source`
pub fn source(&self) -> &Arc<W::Source> {
todo!("dl.K57")
&self.source
}
/// The events of the passes since the last call, in order.
pub fn take_events(&mut self) -> Vec<W::Event> {
std::mem::take(&mut self.events)
}
/// Files a held OK's `result` for the app; OK waits for the answer.
fn file(&mut self, result: W::Result) {
self.filed = Some(result);
self.untaken = true;
self.ok_waits = true;
}
}
impl<W: FullWindowWorkspace> StackDialog for HostedWorkspace<W> {
@@ -206,6 +269,12 @@ impl<W: FullWindowWorkspace> StackDialog for HostedWorkspace<W> {
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<W::Result>> {
// The app accepted the held OK: the first pass after the answer finishes, whichever pass of a frame it is.
if std::mem::take(&mut self.finish)
&& let Some(result) = self.filed.take()
{
return Some(DialogResult::Ok(result));
}
let cx = WorkspaceCx {
source: &*self.source,
revision: self.revision,
@@ -219,6 +288,11 @@ impl<W: FullWindowWorkspace> StackDialog for HostedWorkspace<W> {
self.facts = crate::contract::Outcome::story_facts(&pass.response);
}
self.events.extend(pass.events);
// A pick reaches only the pass whose input held it; a later pass of the frame finds OK waiting and files
// nothing more.
if let Some(result) = pass.held.filter(|_| self.hold_ok && !self.ok_waits) {
self.file(result);
}
pass.result
}
@@ -227,7 +301,15 @@ impl<W: FullWindowWorkspace> StackDialog for HostedWorkspace<W> {
}
fn confirm(&mut self, ctx: &Context) -> Option<W::Result> {
self.workspace.confirm(ctx, &*self.source)
if self.ok_waits {
return None;
}
let result = self.workspace.confirm(ctx, &*self.source)?;
if self.hold_ok {
self.file(result);
return None;
}
Some(result)
}
fn json_fields(&self) -> Option<serde_json::Value> {
@@ -1,21 +1,23 @@
//! The story of the full-window dialog shell.
use std::ops::RangeInclusive;
use std::sync::Arc;
use super::{FullWindowDialog, FullWindowWorkspace, HostedWorkspace, WorkspaceCx, WorkspacePass};
use crate::canvas::{PixelRect, RasterSource};
use crate::contract::{Bind, Show as _, ShowContainer as _};
use crate::dialog::stories::hosted;
use crate::dialog::{DialogWords, FullWindowCanvas, FullWindowSide, FullWindowView, FullWindowZoomBar};
use crate::dialog::{DialogWords, FieldRefusal, FullWindowCanvas, FullWindowSide, FullWindowView, FullWindowZoomBar};
use crate::display::Text;
use crate::form::SliderField;
use crate::primitives::Revision;
use crate::runtime::env::Env;
use crate::runtime::env::{Env, Label};
use crate::runtime::windows::WindowSpec;
use crate::runtime::words::CommonWords;
use crate::sections::{DialogRole, FooterButton};
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use craft_behavior::PixelSize;
use egui::{Color32, ColorImage, Ui};
use egui::{Color32, ColorImage, Context, Ui};
/// The drive of the workspace: a click on Cancel.
fn cancel(fixture: &mut Fixture) {
@@ -28,6 +30,18 @@ fn cancel(fixture: &mut Fixture) {
/// the side columns, with Apply when the story asks for it.
#[story(FullWindowDialog<'static>, covers = [Default], drive = Drive::Custom(cancel))]
fn full_window_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
liquify_shell(ui, data, false)
}
/// The same workspace in an OS window of its own, as RAW Develop opens; the story kit has no viewports, so it fills
/// the window.
#[story(FullWindowDialog<'static>, covers = [], drive = Drive::Custom(cancel))]
fn own_window_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
liquify_shell(ui, data, true)
}
/// The Liquify shell of the stories above, in its own window when `own_window` says so.
fn liquify_shell(ui: &mut Ui, data: &mut StoryData, own_window: bool) -> StoryOutput {
let apply = *data.value("apply", false);
let mut brush = *data.value("brush size", 50.0_f64);
let env = Env::of(ui);
@@ -36,7 +50,11 @@ fn full_window_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
if apply {
buttons.push(FooterButton::new(env.words::<DialogWords>().apply.clone(), DialogRole::Other).stays_open(true));
}
let shown: StoryOutput = FullWindowDialog::new("Liquify")
let mut dialog = FullWindowDialog::new("Liquify");
if own_window {
dialog = dialog.own_window(WindowSpec::dialog());
}
let shown: StoryOutput = dialog
.opened(Bind::bound(data.value("open", true)))
.buttons(buttons)
.sides(|ui, _| {
@@ -77,12 +95,24 @@ impl RasterSource for Flat {
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct BrushChanged(pub(super) f64);
/// The brush sizes the sample workspace's slider and its `brush` field take.
const BRUSH_SIZES: RangeInclusive<f64> = 1.0..=100.0;
/// The index of OK among the sample workspace's buttons.
const ACCEPT: usize = 0;
/// A workspace as Liquify shows one, for the hosted story and trials: the zoom bar over the canvas in the body, the
/// brush size in a side column, OK and Cancel. OK answers the brush size.
/// brush size in a side column, OK and Cancel. OK answers the brush size; automation reads and sets it as `brush`.
#[derive(Default)]
pub(super) struct BrushWorkspace {
pub(super) view: FullWindowView,
pub(super) brush: f64,
/// The source revision the last pass showed.
pub(super) revision: u64,
/// Why the app refused the last held OK.
pub(super) failed: Option<Label>,
/// What automation changed since the last pass, reported by the next one.
pub(super) queued: Vec<BrushChanged>,
}
impl FullWindowWorkspace for BrushWorkspace {
@@ -93,25 +123,60 @@ impl FullWindowWorkspace for BrushWorkspace {
const KEY: &'static str = "story.brushWorkspace";
fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass<BrushChanged, f64> {
let WorkspaceCx { source, open, .. } = cx; // P3(dialogs-w11): dl.K57
let WorkspaceCx { source, revision, open, hold_ok, ok_waits, .. } = cx;
self.revision = revision;
let common = Env::of(ui).words::<CommonWords>();
let mut events = std::mem::take(&mut self.queued);
let before = self.brush;
let (view, brush) = (&mut self.view, &mut self.brush);
let (view, brush, failed) = (&mut self.view, &mut self.brush, &self.failed);
let ok = FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(hold_ok).enabled(!ok_waits);
let shown = FullWindowDialog::new("Liquify")
.opened(open)
.buttons([FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)])
.buttons([ok, FooterButton::new(common.cancel.clone(), DialogRole::Cancel)])
.sides(|ui, _| {
FullWindowSide::new("Properties").show(ui, |ui, _| {
SliderField::new("Brush size", Bind::bound(&mut *brush), 1.0..=100.0).step(1.0).show(ui);
SliderField::new("Brush size", Bind::bound(&mut *brush), BRUSH_SIZES).step(1.0).show(ui);
if let Some(reason) = failed {
Text::new(reason.clone()).show(ui);
}
});
})
.show(ui, |ui, _| {
FullWindowZoomBar::new(Bind::bound(&mut *view)).show(ui);
FullWindowCanvas::new(Bind::bound(&mut *view), source).show(ui);
});
let events = if self.brush == before { Vec::new() } else { vec![BrushChanged(self.brush)] };
if self.brush != before {
events.push(BrushChanged(self.brush));
}
let held = (hold_ok && shown.output.picked == Some(ACCEPT)).then_some(self.brush);
let result = shown.output.result(|| self.brush);
WorkspacePass::new(shown.output.response, events).result(result)
WorkspacePass::new(shown.output.response, events).result(result).held(held)
}
fn json_fields(&self) -> Option<serde_json::Value> {
Some(serde_json::json!({ "brush": self.brush }))
}
fn set_json_field(&mut self, _: &Context, _: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> {
if field != "brush" {
return Err(FieldRefusal::Unknown.message(field));
}
let Some(size) = value.as_f64().filter(|size| BRUSH_SIZES.contains(size)) else {
return Err(FieldRefusal::Rejects(&value).message(field));
};
if size != self.brush {
self.brush = size;
self.queued.push(BrushChanged(size));
}
Ok(())
}
fn confirm(&mut self, _: &Context, _: &Self::Source) -> Option<f64> {
Some(self.brush)
}
fn ok_failed(&mut self, reason: Label) {
self.failed = Some(reason);
}
}
@@ -40,12 +40,14 @@ mod hosting {
use super::super::HostedWorkspace;
use super::super::stories::{BrushChanged, BrushWorkspace, Flat};
use crate::contract::Role;
use crate::dialog::{DialogHost, DialogResult};
use crate::dialog::{DialogHost, DialogResult, FieldRefusal};
use crate::runtime::env::Label;
use crate::testing::access::AccessTree;
use crate::testing::input::key_press;
use crate::testing::pointer::click;
use crate::testing::pointer::{click, moved, press, release};
use crate::testing::{Frames, trial};
use egui::{Key, Modifiers, Pos2, Rect, Ui};
use serde_json::json;
use std::cell::{Cell, RefCell};
use std::sync::Arc;
@@ -66,6 +68,12 @@ mod hosting {
bounds(tree, role, name).unwrap_or_else(|| panic!("no {role:?} named {name:?}")).center()
}
/// Whether the first button named `name` in `tree` is disabled.
fn disabled(tree: &AccessTree, name: &str) -> bool {
let key = tree.keys().into_iter().find(|key| tree.role_of(*key) == Some(Role::BUTTON) && tree.name_of(*key) == Some(name));
tree.is_disabled_key(key.unwrap_or_else(|| panic!("no button named {name:?}")))
}
/// The bounds of the workspace dialog in the last frame's tree.
fn dialog_bounds(frames: &mut Frames) -> Option<Rect> {
bounds(&frames.tree(), Role::DIALOG, Some("Liquify"))
@@ -112,6 +120,87 @@ mod hosting {
click(&mut frames, cancel, &mut ui);
assert_eq!(host.borrow_mut().take::<Hosted>(), Some(DialogResult::Cancel), "Cancel cancels");
assert!(host.borrow().stack().is_empty(), "the cancelled workspace leaves the stack");
// The automation surface reaches the workspace through the host.
let ctx = frames.ctx.clone();
let id = host.borrow_mut().open(workspace());
frames.idle(10, &mut ui);
assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "brush", json!(42.0)), Ok(()), "the workspace takes its brush");
frames.idle(2, &mut ui);
let events = host.borrow_mut().get_mut::<Hosted>().expect("still open").take_events();
assert_eq!(events, vec![BrushChanged(42.0)], "the next pass reports the automation change once");
assert_eq!(
host.borrow_mut().set_json_field(&ctx, id, "size", json!(1.0)),
Err(FieldRefusal::Unknown.message("size")),
"an unknown field is refused"
);
let fields = host.borrow().open_dialogs().into_iter().find(|open| open.id == id).and_then(|open| open.fields);
assert_eq!(fields, Some(json!({ "brush": 42.0 })), "the fields list the new brush");
assert!(host.borrow_mut().confirm::<Hosted>(&ctx), "automation answers OK");
assert_eq!(host.borrow_mut().take::<Hosted>(), Some(DialogResult::Ok(42.0)), "OK answers the brush automation set");
}
#[trial]
fn a_held_ok_files_the_result_until_the_app_answers() {
let host = RefCell::new(DialogHost::new());
let rerun = Cell::new(false);
let mut frames = Frames::new();
let mut ui = |ui: &mut Ui| {
host.borrow_mut().run(ui);
if rerun.get() && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the OK frame runs twice");
}
};
let take_ok = |host: &RefCell<DialogHost>| host.borrow_mut().get_mut::<Hosted>().expect("open").take_ok();
host.borrow_mut().open(workspace().held_ok());
frames.idle(30, &mut ui);
let ok = centre(&frames.tree(), Role::BUTTON, Some("OK"));
// The release runs two passes; only the first has the click.
frames.frame(vec![moved(ok)], &mut ui);
frames.frame(vec![press(ok)], &mut ui);
rerun.set(true);
let passes = frames.frame(vec![release(ok)], &mut ui);
rerun.set(false);
frames.idle(2, &mut ui);
assert_eq!(passes, 2, "the OK frame ran twice");
assert_eq!(take_ok(&host), Some(10.0), "OK files its result");
assert_eq!(take_ok(&host), None, "the filed OK is taken once");
// `Frames::tree` takes the last frame's tree, so both reads share one.
let tree = frames.tree();
assert!(bounds(&tree, Role::DIALOG, Some("Liquify")).is_some(), "the workspace stays shown while the app checks");
assert_eq!(host.borrow_mut().take::<Hosted>(), None, "a held OK does not finish the workspace");
assert!(disabled(&tree, "OK"), "OK is disabled while the answer waits");
click(&mut frames, ok, &mut ui);
assert_eq!(take_ok(&host), None, "a click on the waiting OK files nothing");
let reason = Label::from("Nothing to fill");
host.borrow_mut().get_mut::<Hosted>().expect("open").answer_ok(Err(reason.clone()));
frames.idle(2, &mut ui);
assert_eq!(
host.borrow().get::<Hosted>().and_then(|hosted| hosted.workspace().failed.clone()),
Some(reason),
"the refusal reaches the workspace"
);
assert!(!disabled(&frames.tree(), "OK"), "a refused OK is enabled again");
click(&mut frames, ok, &mut ui);
assert_eq!(take_ok(&host), Some(10.0), "a click on the enabled OK files the result again");
host.borrow_mut().get_mut::<Hosted>().expect("open").answer_ok(Err(Label::from("Still nothing")));
let ctx = frames.ctx.clone();
assert!(!host.borrow_mut().confirm::<Hosted>(&ctx), "automation's OK on a held workspace does not close it");
assert_eq!(take_ok(&host), Some(10.0), "automation's OK files the result");
let revision = || host.borrow().get::<Hosted>().map(|hosted| hosted.workspace().revision).expect("open");
assert_eq!(revision(), 0);
host.borrow_mut().get_mut::<Hosted>().expect("open").set_source(Arc::new(Flat));
frames.idle(2, &mut ui);
assert_eq!(revision(), 1, "a new source moves the workspace's revision");
host.borrow_mut().get_mut::<Hosted>().expect("open").answer_ok(Ok(()));
frames.idle(2, &mut ui);
assert_eq!(host.borrow_mut().take::<Hosted>(), Some(DialogResult::Ok(10.0)), "the accepted OK finishes with its result");
assert!(dialog_bounds(&mut frames).is_none(), "the workspace closed");
}
#[trial]
@@ -1186,7 +1186,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
fn record(&mut self, stage: &mut MemoryStage, ctx: &Context, id: Id) {
if let Some(size) = self.body_size {
crate::contract::steps::record_size(ctx, id, size);
crate::contract::steps::record_body_size(ctx, &self.props.mount, id, size);
}
if let Some(size) = self.header_size {
crate::contract::steps::record_size(ctx, sub(id, "header"), size);
@@ -137,7 +137,7 @@ pub(super) fn measure_layer(props: &ContainerProps, id: Id, ui: &Ui) -> areas::L
match &props.mount {
Mount::Viewport { .. } if windows::WindowHost::of(ui.ctx()).viewports_available() => ui.layer_id(),
Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } => areas::layer_of(overlay.rank.tier(), area),
Mount::FullWindow => areas::layer_of(crate::contract::mount::full_window_overlay(props.focus).rank.tier(), area),
Mount::FullWindow => areas::layer_of(crate::contract::Overlay::full_window(props.focus).rank.tier(), area),
_ => ui.layer_id(),
}
}
+29 -18
View File
@@ -37,6 +37,10 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &
(presence.visible.then_some(presence.t), !open)
};
let closed = || Mounted { host: Box::new(ClosedHost), exiting: false };
let full_window = |focus: FocusPolicy| match layer(&Overlay::full_window(focus)) {
(Some(fade), exiting) => Mounted { host: Box::new(FullWindowHost { focus, exiting, fade, dismissed: None }), exiting },
(None, _) => closed(),
};
let mounted = match &props.mount {
Mount::Inline => Mounted { host: Box::new(Inline), exiting: false },
Mount::Pane(pane) => Mounted { host: Box::new(PaneHost(*pane)), exiting: false },
@@ -45,12 +49,13 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &
(Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props.save.clone(), exiting, fade, at.size)), exiting },
(None, _) => closed(),
},
Mount::FullWindow => match layer(&full_window_overlay(props.focus)) {
(Some(fade), exiting) => Mounted { host: Box::new(FullWindowHost { focus: props.focus, exiting, fade, dismissed: None }), exiting },
(None, _) => closed(),
},
Mount::FullWindow => full_window(props.focus),
Mount::Viewport { fallback, spec } => {
if !WindowHost::of(ctx).viewports_available() {
let viewports = WindowHost::of(ctx).viewports_available();
// A full-window container without OS windows covers the main window, as `Mount::FullWindow` does.
if !viewports && fallback.is_full_window() {
full_window(fallback.focus)
} else if !viewports {
match layer(fallback) {
(Some(fade), exiting) => {
Mounted { host: Box::new(LayerHost::new(fallback.clone(), props.save.clone(), exiting, fade, at.size)), exiting }
@@ -267,14 +272,8 @@ impl Host for LayerHost {
}
}
/// The overlay of a full-window mount: a modal rank with no backdrop (the dialog covers the window) and the
/// container's focus policy as its scope, so the layer stack gives it the key class, blocking and dismissal rules
/// of a modal.
pub(super) fn full_window_overlay(focus: FocusPolicy) -> Overlay {
Overlay::full_window(focus) // P3(dialogs-w11): dl.K15
}
/// Over the whole window, on a layer of its own.
/// Over the whole window, on a layer of its own: [`Overlay::full_window`] of the container's focus policy, so the
/// layer stack gives it the key class, blocking and dismissal rules of a modal.
struct FullWindowHost {
focus: FocusPolicy,
exiting: bool,
@@ -289,9 +288,10 @@ impl Host for FullWindowHost {
}
let ctx = parent.ctx().clone();
// Opened in an embedded shell, the full-window layer fills the shell's region, as a modal there does.
let region = overlay::region_for(env, &full_window_overlay(self.focus));
let overlay = Overlay::full_window(self.focus);
let region = overlay::region_for(env, &overlay);
let window = region.unwrap_or_else(|| ctx.content_rect());
let overlay = full_window_overlay(self.focus).place(Place::Float(FloatPlace::at(window.min)));
let overlay = overlay.place(Place::Float(FloatPlace::at(window.min)));
let layer = Layer { id, owner: id, overlay: &overlay, anchor: Rect::ZERO, env, exiting: self.exiting, fade: self.fade, size: None, region };
// The body is shown at the window's rect, which takes no room in the layer; the layer claims the window, so its
// recorded rect is the window's.
@@ -336,20 +336,31 @@ impl Host for ViewportHost {
let by_rank = || if self.overlay.rank.is_modal() { WindowSpec::dialog() } else { WindowSpec::tool() };
let spec = self.spec.clone().unwrap_or_else(by_rank);
let placed = self.overlay.placed;
let full_window = self.overlay.is_full_window();
// A full-window container fills its window, so the window's own layout memory holds the size the user gave
// it; before it has one the window opens at the opener's content size, large enough for a workspace.
let measured = || {
let remembered = layout_memory::read(&ctx, id);
if full_window { remembered.or_else(|| Some(ctx.content_rect().size())) } else { remembered }
};
let open = ViewportOpen {
id,
title: title.as_str(),
// A placed rect is the caller's size for the window, then a resizable fallback's default size, as the layer
// takes it; the measured size is for a window sized by content.
// takes it; the measured size is for a window sized by content: what its body took in the window, recorded
// once the window reported its place (`steps::record_body_size`).
size: placed
.map(|rect| rect.size())
.or(self.overlay.size.filter(|_| self.overlay.fit == overlay::OverlayFit::Resizable))
.or_else(|| layout_memory::read(&ctx, id)),
.or_else(measured),
// A resizable window takes its default or content size to open; from then on its size is the user's.
follows_size: placed.is_some() || self.overlay.fit != overlay::OverlayFit::Resizable,
save: self.save.as_deref(),
spec: &spec,
limits: (Some(self.overlay.size_limits.min), self.overlay.size_limits.max),
position: placed.map(|rect| rect.min),
resizable: self.overlay.resize.edges != ResizeEdges::NONE,
// The full-window overlay has no grips (it covers the window), but its OS window is one the user sizes.
resizable: full_window || self.overlay.resize.edges != ResizeEdges::NONE,
};
let dismissed = &mut self.dismissed;
windows::show_viewport(&ctx, &open, |ui| {
+1 -1
View File
@@ -25,7 +25,7 @@ mod value;
pub(crate) use apply::{ValueEdit, apply_values, rerun_after_edit};
pub(crate) use env::{EnvStep, env, resolved, variants};
pub(crate) use finish::{before_finish, inert_response, record_size, value_changed};
pub(crate) use finish::{before_finish, inert_response, record_body_size, record_size, value_changed};
pub(super) use id::measuring;
pub(crate) use id::{draft, id, keeping_ids};
pub(crate) use label::scrub_by_label;
@@ -1,9 +1,10 @@
//! Step 17, finish: the response's click flags and the recorded size.
use crate::contract::Mount;
use crate::contract::cx::CxCore;
use crate::runtime::commands::{self, FireSource};
use crate::runtime::egui::response;
use crate::runtime::layout_memory;
use crate::runtime::{layout_memory, windows};
use craft_behavior::{EditEvent, Mixed};
use egui::{Context, Id, Response, Ui, Vec2};
@@ -40,6 +41,16 @@ pub(crate) fn record_size(ctx: &Context, id: Id, real: Vec2) {
layout_memory::record(ctx, id, real);
}
/// The size the body of container `id`, mounted by `mount`, records at step 17 under the container's id: what it took.
/// A body in an OS window that has not reported its place records nothing, since it laid out in room the OS has not
/// given; a content-sized window opens by this record once its content measured in it (`ViewportHost`).
pub(crate) fn record_body_size(ctx: &Context, mount: &Mount, id: Id, took: Vec2) {
if matches!(mount, Mount::Viewport { .. }) && windows::unplaced(ctx, id) {
return;
}
record_size(ctx, id, took);
}
/// The response of a component before any pass has created its root widget: inert, for the component's own id.
pub(crate) fn inert_response(ui: &Ui, id: Id) -> Response {
response::inert(ui, id)
@@ -1,7 +1,7 @@
//! `show_viewport_immediate`, viewport-builder conversion, viewport facts and window commands.
use craft_host::target::WindowChrome;
use egui::{Context, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportId, ViewportInfo, WindowLevel};
use craft_host::target::{Backend, WindowChrome};
use egui::{Context, Pos2, Rect, Ui, UserAttentionType, Vec2, ViewportBuilder, ViewportCommand, ViewportId, ViewportInfo, WindowLevel};
/// Whether the integration opens OS viewports: false where egui embeds them in the root (web, tests).
pub(crate) fn available(ctx: &Context) -> bool {
@@ -142,9 +142,15 @@ pub(crate) fn command(ctx: &Context, viewport: ViewportId, command: ViewportComm
ctx.send_viewport_cmd_to(viewport, command);
}
/// Raises `viewport` and gives it OS focus.
/// Raises `viewport` and gives it OS focus. A minimized window ignores `Focus`, so it is restored first. A Wayland
/// compositor lets no client focus an existing window: there the window asks for the user's attention instead.
pub(crate) fn raise(ctx: &Context, viewport: ViewportId) {
command(ctx, viewport, ViewportCommand::Focus);
command(ctx, viewport, ViewportCommand::Minimized(false));
if crate::runtime::windows::shell_of(ctx, viewport).backend == Backend::Wayland {
command(ctx, viewport, ViewportCommand::RequestUserAttention(UserAttentionType::Informational));
} else {
command(ctx, viewport, ViewportCommand::Focus);
}
ctx.request_repaint_of(viewport);
}
+1 -1
View File
@@ -52,7 +52,7 @@ use shell::{refresh, window_info};
pub(crate) use shell::{set_chrome, set_os};
use spec::chrome_of;
pub use spec::{WindowLevel, WindowSpec};
pub(crate) use viewport::{ViewportOpen, show_viewport, take_close_request};
pub(crate) use viewport::{ViewportOpen, show_viewport, take_close_request, unplaced};
/// Seconds between writes of a changed placement store.
const FLUSH_SECONDS: f64 = 1.0;
@@ -16,10 +16,8 @@ pub(crate) fn base_shell(ctx: &Context) -> ShellInfo {
}
/// The app id the app installed, which every OS window carries; empty when it set none.
#[allow(dead_code)] // P3(dialogs-w11): dl.K76
pub(crate) fn app_id(ctx: &Context) -> String {
let _ = ctx;
todo!("dl.K76")
shared(ctx, |shared| shared.app_id.clone())
}
/// The operating system of the shell: the one source of the key table, the chords shown, the drop operation and
@@ -2,7 +2,7 @@
use super::native::{WindowAction, act, route_hit_test};
use super::placement::{record_placement, saved_placement};
use super::shell::{os_of, refresh};
use super::shell::{app_id, os_of, refresh};
use super::spec::{WindowSpec, frame_of_spec};
use super::{Record, refuse_close_under_modal, shared};
use crate::runtime::egui::viewports;
@@ -18,6 +18,9 @@ pub(crate) struct ViewportOpen<'a> {
pub title: &'a str,
/// The size to open with when nothing is saved.
pub size: Option<Vec2>,
/// Whether the caller keeps the window at `size` once it opened: a placed window or one sized by its content does;
/// a resizable window's size is the user's.
pub follows_size: bool,
/// The key the placement is saved under.
pub save: Option<&'a str>,
/// How the window opens.
@@ -36,7 +39,8 @@ pub(crate) struct ViewportOpen<'a> {
/// The window opens at the caller's place (saved, placed or measured). From then on the window has two writers, the
/// OS and the caller, and only one writes at a time: a caller's place goes out as a command only where it differs
/// from the place the window is known at ([`keep_placed`]), and the OS's moves and resizes become the known place
/// that the caller records. A caller that follows the window so never sends it its own place back a pass late.
/// that the caller records. A caller that follows the window so never sends it its own place back a pass late. A
/// resizable window's size goes out only to open it (`ViewportOpen::follows_size`).
pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: impl FnMut(&mut Ui)) {
let viewport = viewports::viewport_id(open.id);
let saved = open.save.and_then(|key| saved_placement(ctx, key));
@@ -47,7 +51,7 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
let pos = pos.or(open.position);
let opened = PerViewport::<Record>::with(ctx, viewport, |record| record.seen.is_some());
if opened {
keep_placed(ctx, viewport, pos, size);
keep_placed(ctx, viewport, pos, size.filter(|_| open.follows_size));
}
let spec = open.spec;
let active = !shared(ctx, |shared| shared.away);
@@ -69,6 +73,7 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
}
record.level.get_or_insert(spec.level).for_egui(active, os)
});
let app = app_id(ctx);
let opens = viewports::Spec {
title: open.title,
// The builder carries the place only until the window opens: egui would send each change of it as a command.
@@ -83,7 +88,7 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
resizable: open.resizable,
taskbar: spec.taskbar,
hidden: PerViewport::<Record>::with(ctx, viewport, |record| record.awaiting_first_paint),
app_id: "", // P3(dialogs-w11): dl.K76, `shell::app_id(ctx)`
app_id: &app,
};
viewports::show_immediate(ctx, viewport, &opens, |ui| {
let ctx = ui.ctx().clone();
@@ -120,6 +125,13 @@ pub(crate) fn take_close_request(ctx: &Context, id: Id) -> bool {
})
}
/// Whether container `id` shows in an OS window that has not reported its place yet: its body lays out in room the OS
/// has not given, so what it takes there is no size of its content.
pub(crate) fn unplaced(ctx: &Context, id: Id) -> bool {
super::WindowHost::of(ctx).viewports_available()
&& PerViewport::<Record>::with(ctx, viewports::viewport_id(id), |record| record.kind.is_some() && record.seen.is_none())
}
/// How far a caller's place may differ from the known place before it is a change: the OS rounds to pixels, and a
/// placement records the position in pixels.
const ROUNDING: f32 = 0.5;
+198 -28
View File
@@ -1,18 +1,21 @@
//! `runtime::windows`: the input hook per viewport, window info per viewport, the press release after an OS
//! resize (H4), the raise of a modal's window, and `act`.
//! resize (H4), the raise of a modal's window, the mount of a full-window container, the size of a content-sized
//! window, the app id of child windows, injected keys across a focus loss, and `act`.
use craft_behavior::{Cursor, CursorIcon};
use craft_host::target::{Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind};
use craft_behavior::{Cursor, CursorIcon, PointerButton};
use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind};
use craft_keymap::{Key, Mods};
use craft_ui::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _};
use craft_ui::runtime::InstallSpec;
use craft_ui::runtime::windows::WindowSpec;
use craft_ui::runtime::focus::FocusPolicy;
use craft_ui::runtime::windows::{WindowHost, WindowSpec};
use craft_ui::style::StyleCx;
use craft_ui::testing::pointer::{moved, press};
use craft_ui::testing::trial;
use craft_ui::testing::windows::NoWindows;
use craft_ui::testing::windows::{FakeSystem, NoWindows};
use craft_ui_test_kit::contract::PlainStyle;
use craft_ui_test_kit::windows::Windows;
use egui::{Event, Pos2, Rect, Response, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
use craft_ui_test_kit::windows::{Out, Windows};
use egui::{Event, Pos2, Rect, Response, UserAttentionType, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
use std::cell::Cell;
use std::sync::Arc;
@@ -74,31 +77,68 @@ fn a_press_is_released_after_an_os_resize_of_an_undecorated_window() {
}
}
/// One frame of `windows` with the `Modal` open in the child viewport.
fn modal_frame(windows: &Windows) -> Out {
windows.frame(vec![], vec![], |ui| {
ui.ctx().show_viewport_immediate(child(), ViewportBuilder::default(), |cui, _| {
let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal()));
Modal { common: Common::new(), props }.id_salt("modal").show(cui, |_, _| {});
});
})
}
/// Whether `out` raised the child's window: restored it from the Dock or taskbar, then focused it (or, on Wayland,
/// asked for attention).
fn raised_child(out: &Out) -> bool {
out.commands.iter().any(|(id, command)| *id == child() && *command == ViewportCommand::Minimized(false))
}
/// A modal in one window blocks the others: the pointer over them shows the blocked cursor, and a close request on
/// them is refused and raises the modal's window.
/// them is refused and raises the modal's window. A minimized window ignores focus, so the raise restores it first;
/// a Wayland compositor lets no client focus a window, so there the raise asks for attention.
#[trial]
fn an_app_modal_in_one_window_blocks_the_cursor_and_the_close_of_the_others() {
let windows = Windows::new();
let frame = || {
windows.frame(vec![], vec![], |ui| {
ui.ctx().show_viewport_immediate(child(), ViewportBuilder::default(), |cui, _| {
let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal()));
Modal { common: Common::new(), props }.id_salt("modal").show(cui, |_, _| {});
});
})
};
for _ in 0..4 {
frame();
}
assert_eq!(craft_ui::runtime::cursor::current(&windows.ctx), Some(Cursor::System(CursorIcon::NotAllowed)), "the root window is blocked");
let attention = ViewportCommand::RequestUserAttention(UserAttentionType::Informational);
for (backend, focus) in [(Backend::X11, ViewportCommand::Focus), (Backend::Wayland, attention.clone())] {
let windows = Windows::with(InstallSpec::new(ShellInfo::default().backend(backend), Arc::new(FakeSystem::new())));
for _ in 0..4 {
modal_frame(&windows);
}
let blocked = Some(Cursor::System(CursorIcon::NotAllowed));
assert_eq!(craft_ui::runtime::cursor::current(&windows.ctx), blocked, "{backend:?}: the root window is blocked");
windows.root_info(ViewportInfo { events: vec![ViewportEvent::Close], ..ViewportInfo::default() });
let out = frame();
craft_ui::runtime::windows::logic(&windows.ctx);
let out_after = frame();
let sent: Vec<_> = out.commands.iter().chain(&out_after.commands).collect();
assert!(sent.contains(&&(ViewportId::ROOT, ViewportCommand::CancelClose)), "the close is refused: {sent:?}");
assert!(sent.contains(&&(child(), ViewportCommand::Focus)), "the modal's window is raised: {sent:?}");
windows.root_info(ViewportInfo { events: vec![ViewportEvent::Close], ..ViewportInfo::default() });
let out = modal_frame(&windows);
craft_ui::runtime::windows::logic(&windows.ctx);
let out_after = modal_frame(&windows);
let sent: Vec<_> = out.commands.iter().chain(&out_after.commands).collect();
assert!(sent.contains(&&(ViewportId::ROOT, ViewportCommand::CancelClose)), "{backend:?}: the close is refused: {sent:?}");
let at = |wanted: &ViewportCommand| sent.iter().position(|(id, command)| *id == child() && command == wanted);
let (restored, raised) = (at(&ViewportCommand::Minimized(false)), at(&focus));
assert!(raised.is_some(), "{backend:?}: the modal's window is raised: {sent:?}");
assert!(
matches!((restored, raised), (Some(restored), Some(raised)) if restored < raised),
"{backend:?}: the window is restored before it is raised: {sent:?}"
);
let other = if backend == Backend::Wayland { ViewportCommand::Focus } else { attention.clone() };
assert_eq!(at(&other), None, "{backend:?}: one way of raising: {sent:?}");
}
}
/// L-17: the user clicking the main window while a modal in another window blocks it brings the modal's window
/// forward with it, in the pass the main window gains focus; a pass without a focus change sends nothing.
#[trial]
fn a_blocking_modal_is_raised_when_the_main_window_gains_focus() {
let windows = Windows::new();
let focus = |on| ViewportInfo { focused: Some(on), ..ViewportInfo::default() };
windows.root_info(focus(false));
for _ in 0..4 {
modal_frame(&windows);
}
assert!(!raised_child(&modal_frame(&windows)), "the main window stays unfocused: nothing is raised");
windows.root_info(focus(true));
assert!(raised_child(&modal_frame(&windows)), "the main window gained focus: the modal's window is raised");
assert!(!raised_child(&modal_frame(&windows)), "the main window keeps focus: nothing more is raised");
}
/// A container mounted in an OS viewport that opens as `spec`, with a body the trial gives it.
@@ -120,6 +160,12 @@ impl Palette {
};
Palette { common: Common::new(), props: ContainerProps::new().mount(mount) }.label(title).id_salt(title)
}
/// A full-window container in a dialog window of its own, as a workspace that opens its own window mounts.
fn full_window(title: &'static str) -> Self {
let mount = Mount::viewport_with(Overlay::full_window(FocusPolicy::DIALOG), WindowSpec::dialog());
Palette { common: Common::new(), props: ContainerProps::new().mount(mount) }.label(title).id_salt(title)
}
}
impl Component for Palette {
@@ -173,3 +219,127 @@ fn a_palette_drops_its_level_while_the_app_is_inactive() {
frame(true, false);
assert_eq!(frame(true, false), on_top, "the frame after the main window took focus again");
}
/// A full-window container mounted in its own window opens a resizable OS window titled as the container where
/// viewports are available, and covers the main window's content where they are not.
#[trial]
fn a_full_window_viewport_fills_the_main_window_without_viewports_and_opens_its_own_with_them() {
let windows = Windows::new();
let mut out = None;
for _ in 0..4 {
out = Some(windows.frame(vec![], vec![], |ui| {
Palette::full_window("Workspace").show(ui, |_, _| {});
}));
}
let out = out.expect("the frames ran");
let (_, builder) = builder_titled(&out, "Workspace");
assert_eq!(builder.resizable, Some(true), "the user sizes the workspace's window");
let without = ShellInfo::default().caps(Caps::native(Os::Linux).difference(Caps::VIEWPORTS));
let windows = Windows::with(InstallSpec::new(without, Arc::new(FakeSystem::new())));
let content = Cell::new(Rect::NOTHING);
let mut out = None;
for _ in 0..4 {
out = Some(windows.frame(vec![], vec![], |ui| {
content.set(ui.ctx().content_rect());
Palette::full_window("Workspace").show(ui, |_, _| {});
}));
}
let out = out.expect("the frames ran");
assert!(out.builders.iter().all(|(_, builder)| builder.title.as_deref() != Some("Workspace")), "no OS window opens");
let (_, tree) = out.trees.iter().rfind(|(id, _)| *id == ViewportId::ROOT).expect("the root's tree");
let shown = tree.keys().into_iter().find(|key| tree.role_of(*key) == Some(Role::GROUP) && tree.name_of(*key) == Some("Workspace"));
assert_eq!(shown.and_then(|key| tree.bounds_of(key)), Some(content.get()), "the workspace covers the main window");
}
/// A window sized by its content sends no size before it has reported its place, so it never opens at what its body
/// took in room the OS has not given; once it has reported, it takes its content's size.
#[trial]
fn a_content_sized_window_takes_its_content_size_once_it_reported_its_place() {
const CONTENT: Vec2 = Vec2::new(200.0, 100.0);
const GIVEN: Vec2 = Vec2::new(400.0, 300.0);
let windows = Windows::new();
let frame = || {
windows.frame(vec![], vec![], |ui| {
Palette::new("tool", Some(WindowSpec::tool())).show(ui, |ui, _| {
ui.allocate_exact_size(CONTENT, egui::Sense::hover());
});
})
};
let sizes = |out: &Out| -> Vec<Vec2> {
let sent = out.commands.iter().filter(|(id, _)| *id != ViewportId::ROOT);
sent.filter_map(|(_, command)| match command {
ViewportCommand::InnerSize(size) => Some(*size),
_ => None,
})
.collect()
};
let first = frame();
let opened = first.builders.iter().filter(|(_, builder)| builder.title.as_deref() == Some("tool"));
assert!(opened.clone().count() > 0, "the window asked to open");
assert!(opened.clone().all(|(_, builder)| builder.inner_size.is_none()), "the window opens with no size of its own");
assert_eq!(sizes(&first), Vec::<Vec2>::new(), "no size goes out before the window reports its place");
let given = Rect::from_min_size(Pos2::new(100.0, 100.0), GIVEN);
let reported = ViewportInfo { inner_rect: Some(given), outer_rect: Some(given), native_pixels_per_point: Some(1.0), ..ViewportInfo::default() };
windows.child_info(reported);
let sent: Vec<Vec2> = (0..3).flat_map(|_| sizes(&frame())).collect();
let taken = sent.last().copied().expect("the window takes a size once it reported its place");
assert!(
taken.x >= CONTENT.x && taken.y >= CONTENT.y && taken.x < GIVEN.x && taken.y < GIVEN.y,
"the window takes its content's size, not the room the OS gave it: {taken:?}"
);
}
/// The OS windows the runtime opens carry the app id the app installed, as its main window does: docks and Wayland
/// compositors find the app's icon and rules by it.
#[trial]
fn a_viewport_opened_through_a_mount_carries_the_installed_app_id() {
let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(FakeSystem::new())).app_id("org.example.Craft"));
let out = windows.frame(vec![], vec![], |ui| {
Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {});
});
assert_eq!(builder_titled(&out, "tool").1.app_id.as_deref(), Some("org.example.Craft"), "the child window carries the app id");
let windows = Windows::new();
let out = windows.frame(vec![], vec![], |ui| {
Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {});
});
assert_eq!(builder_titled(&out, "tool").1.app_id, None, "without an app id the window carries none");
}
/// fx.F20: a key and a modifier injected as held are let go when the window loses focus, as the platform lets its
/// own go. Otherwise the next injected input, written against the stale state, would not announce its own Shift.
#[trial]
fn a_window_focus_loss_releases_injected_held_keys() {
let windows = Windows::new();
let host = WindowHost::of(&windows.ctx);
let held = Cell::new((false, false));
let shift_click = Cell::new(false);
let frame = |events: Vec<Event>| {
windows.frame(events, vec![], |ui| {
ui.ctx().input(|input| {
held.set((input.key_down(egui::Key::A), input.modifiers.shift));
if input.pointer.primary_pressed() && input.modifiers.shift {
shift_click.set(true);
}
});
});
};
frame(vec![]);
host.inject_key(ViewportId::ROOT, Key::A, Mods::SHIFT, true);
for _ in 0..4 {
frame(vec![]);
}
assert_eq!(held.get(), (true, true), "the injected key and Shift are held");
frame(vec![Event::WindowFocused(false)]);
frame(vec![Event::WindowFocused(true)]);
host.inject_click(ViewportId::ROOT, Pos2::new(40.0, 40.0), PointerButton::Primary, 1, Mods::SHIFT, false);
for _ in 0..8 {
frame(vec![]);
}
assert!(shift_click.get(), "the click after the focus loss holds its own Shift");
assert_eq!(held.get(), (false, false), "nothing stays held after the click");
}