Contract stubs: craft-ui-patterns (06.md items), cw.C46 senses_surface

This commit is contained in:
aiongg
2026-11-14 02:11:11 +00:00
parent 38ce55467c
commit 870c17ba97
40 changed files with 2114 additions and 69 deletions
@@ -127,6 +127,24 @@ impl EyedropperRequest {
}
}
/// A request for the files of a folder, which the host lists and answers with `HostAnswer::Listing`. A dialog row that
/// shows a folder's files asks for them this way, since the framework holds no file system access of its own.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ListingRequest {
/// The key of the row the listing fills.
pub key: String,
/// The folder to list.
pub folder: PathBuf,
}
impl ListingRequest {
/// A request for the files of `folder`, answered under `key`.
pub fn new(key: impl Into<String>, folder: impl Into<PathBuf>) -> Self {
Self { key: key.into(), folder: folder.into() }
}
}
/// What the host answered to a request, kept until the dialog applies it to its values in its next pass.
#[derive(Clone, Debug, PartialEq)]
pub enum HostAnswer {
@@ -151,4 +169,11 @@ pub enum HostAnswer {
/// The sampled colour.
color: Srgba,
},
/// The files the host listed for the listing request `key`.
Listing {
/// The request's key.
key: String,
/// The files of the folder.
files: Vec<PathBuf>,
},
}
@@ -0,0 +1,276 @@
//! The blend mode keys, as in Photoshop: Shift+ and Shift- step through the target's modes, Shift+Alt plus a
//! letter picks one ([`BlendKeys`]).
//!
//! The app lists the modes its target accepts ([`BlendKeyEntry`]: a painting tool's own Mode menu, or the layer modes)
//! with its own key type. The keys are the [`BlendShortcut`] and [`BlendStep`] command sets; the app routes the fired
//! commands here before the single-letter tool keys and gets back the entry to set. Which target a tool has, the
//! engine command and its undo step stay the app's.
//!
//! ```ignore
//! let entries = [BlendKeyEntry::new(Mode::Normal, BlendShortcut::Normal), BlendKeyEntry::new(Mode::Multiply, BlendShortcut::Multiply)];
//! if let Some(pick) = BlendKeys::new(&entries).current(&layer.blend).fired(&fired) {
//! app.set_blend(pick.into_key()); // one undo step
//! }
//! ```
use craft_ui::contract::CommandSet;
use craft_ui::runtime::commands::{CommandRef, FirePhase, Fired};
/// Photoshop's Shift+Alt letter positions: the 26 lettered blend modes. Darker Color, Lighter Color, Subtract and
/// Divide have no letter; list them with [`BlendKeyEntry::unlettered`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
#[command(prefix = "blendMode")]
#[non_exhaustive]
pub enum BlendShortcut {
/// Shift+Alt+N.
#[command(modal = "declared", label = "Normal", default = "Shift+Alt+N")]
Normal,
/// Shift+Alt+I.
#[command(modal = "declared", label = "Dissolve", default = "Shift+Alt+I")]
Dissolve,
/// Shift+Alt+Q: painting tools only.
#[command(modal = "declared", label = "Behind", default = "Shift+Alt+Q")]
Behind,
/// Shift+Alt+R: painting tools only (paints transparency).
#[command(modal = "declared", label = "Clear", default = "Shift+Alt+R")]
Clear,
/// Shift+Alt+P: groups only.
#[command(modal = "declared", label = "Pass Through", default = "Shift+Alt+P")]
PassThrough,
/// Shift+Alt+K.
#[command(modal = "declared", label = "Darken", default = "Shift+Alt+K")]
Darken,
/// Shift+Alt+M.
#[command(modal = "declared", label = "Multiply", default = "Shift+Alt+M")]
Multiply,
/// Shift+Alt+B.
#[command(modal = "declared", label = "Color Burn", default = "Shift+Alt+B")]
ColorBurn,
/// Shift+Alt+A.
#[command(modal = "declared", label = "Linear Burn", default = "Shift+Alt+A")]
LinearBurn,
/// Shift+Alt+G.
#[command(modal = "declared", label = "Lighten", default = "Shift+Alt+G")]
Lighten,
/// Shift+Alt+S.
#[command(modal = "declared", label = "Screen", default = "Shift+Alt+S")]
Screen,
/// Shift+Alt+D.
#[command(modal = "declared", label = "Color Dodge", default = "Shift+Alt+D")]
ColorDodge,
/// Shift+Alt+W.
#[command(modal = "declared", label = "Linear Dodge", default = "Shift+Alt+W")]
LinearDodge,
/// Shift+Alt+O.
#[command(modal = "declared", label = "Overlay", default = "Shift+Alt+O")]
Overlay,
/// Shift+Alt+F.
#[command(modal = "declared", label = "Soft Light", default = "Shift+Alt+F")]
SoftLight,
/// Shift+Alt+H.
#[command(modal = "declared", label = "Hard Light", default = "Shift+Alt+H")]
HardLight,
/// Shift+Alt+V.
#[command(modal = "declared", label = "Vivid Light", default = "Shift+Alt+V")]
VividLight,
/// Shift+Alt+J.
#[command(modal = "declared", label = "Linear Light", default = "Shift+Alt+J")]
LinearLight,
/// Shift+Alt+Z.
#[command(modal = "declared", label = "Pin Light", default = "Shift+Alt+Z")]
PinLight,
/// Shift+Alt+L.
#[command(modal = "declared", label = "Hard Mix", default = "Shift+Alt+L")]
HardMix,
/// Shift+Alt+E.
#[command(modal = "declared", label = "Difference", default = "Shift+Alt+E")]
Difference,
/// Shift+Alt+X.
#[command(modal = "declared", label = "Exclusion", default = "Shift+Alt+X")]
Exclusion,
/// Shift+Alt+U.
#[command(modal = "declared", label = "Hue", default = "Shift+Alt+U")]
Hue,
/// Shift+Alt+T.
#[command(modal = "declared", label = "Saturation", default = "Shift+Alt+T")]
Saturation,
/// Shift+Alt+C.
#[command(modal = "declared", label = "Color", default = "Shift+Alt+C")]
Color,
/// Shift+Alt+Y.
#[command(modal = "declared", label = "Luminosity", default = "Shift+Alt+Y")]
Luminosity,
}
impl BlendShortcut {
/// Every position, in Photoshop's menu order (as the variants).
pub const ALL: [BlendShortcut; 26] = [
BlendShortcut::Normal,
BlendShortcut::Dissolve,
BlendShortcut::Behind,
BlendShortcut::Clear,
BlendShortcut::PassThrough,
BlendShortcut::Darken,
BlendShortcut::Multiply,
BlendShortcut::ColorBurn,
BlendShortcut::LinearBurn,
BlendShortcut::Lighten,
BlendShortcut::Screen,
BlendShortcut::ColorDodge,
BlendShortcut::LinearDodge,
BlendShortcut::Overlay,
BlendShortcut::SoftLight,
BlendShortcut::HardLight,
BlendShortcut::VividLight,
BlendShortcut::LinearLight,
BlendShortcut::PinLight,
BlendShortcut::HardMix,
BlendShortcut::Difference,
BlendShortcut::Exclusion,
BlendShortcut::Hue,
BlendShortcut::Saturation,
BlendShortcut::Color,
BlendShortcut::Luminosity,
];
}
/// Shift+= and Shift+-: the next and the previous mode of the target's list.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
#[command(prefix = "blendMode")]
#[non_exhaustive]
pub enum BlendStep {
/// Shift+=: the next mode, wrapping at the end.
#[command(modal = "declared", label = "Next Blend Mode", default = "Shift+=")]
Next,
/// Shift+-: the previous mode, wrapping at the start.
#[command(modal = "declared", label = "Previous Blend Mode", default = "Shift+-")]
Previous,
}
/// One mode the target accepts, in the order of its menu: the app's key of the mode and its Shift+Alt+
/// letter position, if it has one.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct BlendKeyEntry<K> {
/// The app's key of the blend mode.
pub key: K,
/// The mode's Shift+Alt+ letter position, if it has one.
pub shortcut: Option<BlendShortcut>,
}
impl<K> BlendKeyEntry<K> {
/// The mode `key` at letter position `shortcut`.
pub fn new(key: K, shortcut: BlendShortcut) -> Self {
Self { key, shortcut: Some(shortcut) }
}
/// A mode without a letter (Darker Color, Lighter Color, Subtract, Divide): Shift+= and Shift+- reach
/// it, no letter does.
pub fn unlettered(key: K) -> Self {
Self { key, shortcut: None }
}
/// Behind (Shift+Alt+Q), for a painting tool that offers it. Without such an entry Shift+Alt+Q is consumed
/// and does nothing.
pub fn behind(key: K) -> Self {
Self::new(key, BlendShortcut::Behind)
}
/// Clear (Shift+Alt+R), for a painting tool that offers it (PhotoCraft's Brush, Pencil and Paint
/// Bucket list it after Dissolve). Without such an entry Shift+Alt+R is consumed and does nothing.
pub fn clear(key: K) -> Self {
Self::new(key, BlendShortcut::Clear)
}
}
/// What a blend mode key picked: the entry's key, and how.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BlendKeyPick<K> {
/// Shift+= or Shift+- stepped to this entry.
Stepped(K),
/// A Shift+Alt+ letter picked this entry.
Lettered(K),
}
impl<K> BlendKeyPick<K> {
/// The picked entry's key.
pub fn key(&self) -> &K {
match self {
BlendKeyPick::Stepped(key) | BlendKeyPick::Lettered(key) => key,
}
}
/// The picked entry's key, taken.
pub fn into_key(self) -> K {
match self {
BlendKeyPick::Stepped(key) | BlendKeyPick::Lettered(key) => key,
}
}
}
/// The blend mode keys over the app's list of `entries`.
///
/// - [`BlendStep`] steps to the next or previous entry, wrapping at either end; a [`current`](Self::current) that
/// isn't listed (or none) steps from the top (next) or the bottom (previous).
/// - A [`BlendShortcut`] picks the entry whose position it is. A position whose mode isn't listed (Clear or Behind for
/// layers, Pass Through for a painting tool, Overlay for the Healing Brush) picks nothing: the command is taken, so
/// the letter does not reach the single-letter tool keys.
/// - A key release picks nothing; holding a step key repeats the step.
/// - No AccessKit node: the app's blend control announces the new mode. Keys are not directional, so nothing mirrors
/// in a right-to-left interface.
#[must_use = "read the fired command with `fired`"]
pub struct BlendKeys<'a, K> {
entries: &'a [BlendKeyEntry<K>],
current: Option<&'a K>,
}
impl<'a, K: Clone + PartialEq> BlendKeys<'a, K> {
/// The keys over `entries`, in menu order.
pub fn new(entries: &'a [BlendKeyEntry<K>]) -> Self {
Self { entries, current: None }
}
/// The target's mode now, where the steps start from.
pub fn current(mut self, current: &'a K) -> Self {
self.current = Some(current);
self
}
/// The entry a fired [`BlendStep`] or [`BlendShortcut`] picks; `None` for any other command, a release, or a
/// position the list lacks.
pub fn fired(self, fired: &Fired) -> Option<BlendKeyPick<K>> {
self.command(&fired.command, fired.phase)
}
/// [`fired`](Self::fired) for a command and the phase it fired in.
pub fn command(self, command: &CommandRef, phase: FirePhase) -> Option<BlendKeyPick<K>> {
if phase == FirePhase::Release {
return None;
}
if let Some(step) = BlendStep::from_ref(command) {
let step = match step {
BlendStep::Next => 1,
BlendStep::Previous => -1,
};
return stepped(self.entries, self.current, step).map(|entry| BlendKeyPick::Stepped(entry.key.clone()));
}
let shortcut = BlendShortcut::from_ref(command)?;
self.entries.iter().find(|entry| entry.shortcut == Some(shortcut)).map(|entry| BlendKeyPick::Lettered(entry.key.clone()))
}
}
/// The entry `step` places after (or before, when negative) `current` in `entries`, wrapping; an
/// unlisted or absent `current` steps from the top (`step > 0`) or the bottom. `None` for an
/// empty list.
fn stepped<'e, K: PartialEq>(entries: &'e [BlendKeyEntry<K>], current: Option<&K>, step: i32) -> Option<&'e BlendKeyEntry<K>> {
// pc: crates/ui-egui/src/input/blend_keys.rs:18 `stepped` (`rem_euclid`; unlisted: 0 or n − 1).
let n = i32::try_from(entries.len()).ok().filter(|n| *n > 0)?;
let at = current.and_then(|c| entries.iter().position(|e| e.key == *c)).and_then(|i| i32::try_from(i).ok());
let next = match at {
Some(i) => (i + step).rem_euclid(n),
None if step > 0 => 0,
None => n - 1,
};
entries.get(usize::try_from(next).ok()?)
}
+14 -1
View File
@@ -65,6 +65,8 @@ pub struct DockAreaOutput<P> {
/// Where each dock column was placed this pass, named by a panel of its first group, in the area's layer space.
/// Hosts that anchor their own surfaces to a column read it.
pub columns: Vec<(P, Rect)>,
/// The files dropped on the area's windows this pass, for the host to open.
pub window_files: Vec<drag::OsFile>,
/// The area's response.
pub response: Response,
}
@@ -356,7 +358,18 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
if shown.output.dropped.is_some() {
cross_window::accept_cross_window(&ctx);
}
DockAreaOutput { actions, events, focused, picked, error, edit, float_space: space, columns, response: shown.output.response }
DockAreaOutput {
actions,
events,
focused,
picked,
error,
edit,
float_space: space,
columns,
window_files: Vec::new(),
response: shown.output.response,
} // P3(panels-w1): pn.C7
}
}
+4 -1
View File
@@ -16,4 +16,7 @@ pub use panes::{
};
pub use switcher::{WorkspaceSwitcher, WorkspaceSwitcherOutput};
pub use words::WorkspaceDialogWords;
pub use workspace_dialogs::{DeleteWorkspaceDialog, DeleteWorkspaceDialogOutput, NewWorkspace, NewWorkspaceDialog, NewWorkspaceDialogOutput};
pub use workspace_dialogs::{
DeleteWorkspaceDialog, DeleteWorkspaceDialogOutput, HostedDeleteWorkspace, HostedNewWorkspace, NewWorkspace, NewWorkspaceDialog,
NewWorkspaceDialogOutput,
};
@@ -7,6 +7,7 @@ mod stories;
use super::words::WorkspaceDialogWords;
use crate::choice::Checkbox;
use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog};
use crate::display::{Shade, Text};
use crate::form::{Field, Help};
use crate::patterns::form_dialogs::FormDialog;
@@ -70,17 +71,21 @@ pub struct NewWorkspaceDialog<'a, P> {
/// Binds the open state to `open`.
#[prop(name = "opened")]
open: Option<Bind<'a, bool>>,
/// Binds the name and captures to `value`.
#[prop(name = "value")]
bound: Option<Bind<'a, NewWorkspace>>,
}
impl<'a, P: Clone + Eq + Hash> NewWorkspaceDialog<'a, P> {
/// New Workspace over `set`, whose names it checks.
pub fn new(set: &'a WorkspaceSet<P>) -> Self {
NewWorkspaceDialog { set, offered: WorkspaceKeeps::ALL, open: None }
NewWorkspaceDialog { set, offered: WorkspaceKeeps::ALL, open: None, bound: None }
}
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> NewWorkspaceDialogOutput {
let NewWorkspaceDialog { set, offered, open } = self;
let NewWorkspaceDialog { set, offered, open, bound } = self;
let _ = &bound; // P3(top-w3): tp.T20
let words = Env::of(ui).words::<WorkspaceDialogWords>();
let mut form = FormDialog::<NewWorkspace>::own(words.new_title.clone());
if let Some(open) = open {
@@ -157,17 +162,21 @@ pub struct DeleteWorkspaceDialog<'a, P> {
/// Binds the open state to `open`.
#[prop(name = "opened")]
open: Option<Bind<'a, bool>>,
/// Binds the picked workspace's id to `value`.
#[prop(name = "value")]
bound: Option<Bind<'a, String>>,
}
impl<'a, P: Clone + Eq + Hash> DeleteWorkspaceDialog<'a, P> {
/// Delete Workspace over the saved workspaces of `set`.
pub fn new(set: &'a WorkspaceSet<P>) -> Self {
DeleteWorkspaceDialog { set, open: None }
DeleteWorkspaceDialog { set, open: None, bound: None }
}
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> DeleteWorkspaceDialogOutput {
let DeleteWorkspaceDialog { set, open } = self;
let DeleteWorkspaceDialog { set, open, bound } = self;
let _ = &bound; // P3(top-w3): tp.T21
let words = Env::of(ui).words::<WorkspaceDialogWords>();
let deletable = |id: &str| id != set.current;
let entries: Vec<Entry<String>> = set
@@ -199,3 +208,107 @@ impl<'a, P: Clone + Eq + Hash> DeleteWorkspaceDialog<'a, P> {
DeleteWorkspaceDialogOutput { response: shown.response, closed: shown.closed, accepted: shown.accepted }
}
}
/// A [`NewWorkspaceDialog`] the [`DialogHost`](crate::dialog::DialogHost) owns, over a copy of the workspace set. It
/// answers with the [`NewWorkspace`] at OK.
pub struct HostedNewWorkspace<P> {
id: DialogId,
set: WorkspaceSet<P>,
offered: WorkspaceKeeps,
value: NewWorkspace,
open: bool,
}
impl<P: Clone> HostedNewWorkspace<P> {
/// New Workspace over a copy of `set`, whose names it checks.
pub fn new(set: &WorkspaceSet<P>) -> Self {
let _ = set;
todo!("tp.T20")
}
/// The Capture boxes the dialog shows; the default shows all three.
#[must_use]
pub fn offered(mut self, keeps: WorkspaceKeeps) -> Self {
let _ = (&mut self, keeps);
todo!("tp.T20")
}
}
impl<P: Clone + Eq + Hash + Send + 'static> StackDialog for HostedNewWorkspace<P> {
type Result = NewWorkspace;
fn id(&self) -> DialogId {
self.id
}
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<NewWorkspace>> {
let _ = (ui, stack, &self.set, &self.offered, &self.value, &self.open);
todo!("tp.T20")
}
fn key(&self) -> Option<&str> {
Some("workspace.new")
}
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("tp.T20")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("tp.T20")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("tp.T20")
}
}
/// A [`DeleteWorkspaceDialog`] the [`DialogHost`](crate::dialog::DialogHost) owns, over a copy of the workspace set. It
/// answers with the id of the picked workspace at OK.
pub struct HostedDeleteWorkspace<P> {
id: DialogId,
set: WorkspaceSet<P>,
value: String,
open: bool,
}
impl<P: Clone> HostedDeleteWorkspace<P> {
/// Delete Workspace over a copy of the saved workspaces of `set`.
pub fn new(set: &WorkspaceSet<P>) -> Self {
let _ = set;
todo!("tp.T21")
}
}
impl<P: Clone + Eq + Hash + Send + 'static> StackDialog for HostedDeleteWorkspace<P> {
type Result = String;
fn id(&self) -> DialogId {
self.id
}
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<String>> {
let _ = (ui, stack, &self.set, &self.value, &self.open);
todo!("tp.T21")
}
fn key(&self) -> Option<&str> {
Some("workspace.delete")
}
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("tp.T21")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("tp.T21")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("tp.T21")
}
}
@@ -210,9 +210,9 @@ pub struct AboutDialog<'a> {
/// Binds the open state to `open`.
#[prop(name = "opened")]
open: Option<Bind<'a, bool>>,
/// The tab the dialog opens on.
/// Binds the shown tab to `tab`; the dialog opens on it.
#[prop]
tab: Option<AboutTab>,
tab: Option<Bind<'a, AboutTab>>,
}
impl<'a> AboutDialog<'a> {
@@ -232,6 +232,7 @@ impl<'a> AboutDialog<'a> {
let title = Label::from(words.title.fill(&[("app", info.app_name.as_str())]));
let shown = Shown { words: &words, writer: &writer, info, credits };
let _ = &tab; // P3(dialogs-w4): dl.K11, the bound tab
let view = RefCell::new(View::default());
let link = RefCell::new(None);
let mut dialog =
@@ -240,7 +241,7 @@ impl<'a> AboutDialog<'a> {
dialog = dialog.opened(open);
}
let shown_dialog = dialog.show(ui, |ui, cx| {
*view.borrow_mut() = if cx.appeared() { View { tab: tab.unwrap_or_default(), ..View::default() } } else { cx.memory::<View>().clone() };
*view.borrow_mut() = if cx.appeared() { View { tab: AboutTab::default(), ..View::default() } } else { cx.memory::<View>().clone() };
Stack::new().header(|ui, _| shown.tabs(ui, &title, &view)).show(ui, |ui, _| {
let tab = view.borrow().tab;
match tab {
@@ -466,7 +467,7 @@ pub struct HostedAbout {
id: DialogId,
info: AboutInfo,
credits: Credits,
tab: Option<AboutTab>,
tab: AboutTab,
link: Option<String>,
open: bool,
#[cfg(feature = "testing")]
@@ -480,7 +481,7 @@ impl HostedAbout {
id: dialog_id(ABOUT_KEY),
info,
credits,
tab: None,
tab: AboutTab::default(),
link: None,
open: true,
#[cfg(feature = "testing")]
@@ -491,7 +492,7 @@ impl HostedAbout {
/// The tab the dialog opens on.
#[must_use]
pub fn tab(mut self, tab: AboutTab) -> Self {
self.tab = Some(tab);
self.tab = tab;
self
}
@@ -507,12 +508,28 @@ const ABOUT_KEY: &str = "help.about";
impl StackDialog for HostedAbout {
type Result = ();
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K11")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K11")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K11")
}
fn id(&self) -> DialogId {
self.id
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let shown = AboutDialog { info: &self.info, credits: &self.credits, open: Some(Bind::bound(&mut self.open)), tab: self.tab }.show(ui);
let shown =
AboutDialog { info: &self.info, credits: &self.credits, open: Some(Bind::bound(&mut self.open)), tab: Some(Bind::bound(&mut self.tab)) }
.show(ui);
#[cfg(feature = "testing")]
{
self.facts = crate::contract::Outcome::story_facts(&shown);
@@ -2,7 +2,8 @@
//! owned by a `DialogHost`. A command form is a `ParamDialog` without a preview.
use super::fields::{DialogFields, FieldValue};
use crate::runtime::requests::{ColorRequest, HostAnswer, PathRequest};
use crate::patterns::presets::PresetRow;
use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest};
use super::form::{FormDialog, FormDialogWords};
use super::host_requests::HostRequests;
@@ -66,9 +67,9 @@ pub struct ParamResult {
impl ParamResult {
/// Stores the values of a dialog built with [`ParamDialog::remember`] for the next open. The app calls it after
/// its command succeeds, so a failed command leaves the previous values; without a remember key it does nothing.
pub fn remember(&self, ui: &Ui) {
pub fn remember(&self, ctx: &Context) {
if let Some((key, values)) = &self.remember {
let mut stage = MemoryStage::open(ui.ctx(), unique(("craft_ui::param_result", key.as_str())));
let mut stage = MemoryStage::open(ctx, unique(("craft_ui::param_result", key.as_str())));
*stage.saved::<Option<DialogFields>>(key) = Some(values.clone());
stage.write_back();
}
@@ -105,6 +106,8 @@ pub struct ParamDialogOutput {
/// The point of the preview picture a click landed on this pass (`PreviewOutput::clicked`): an eyedropper on the
/// preview samples there.
pub preview_click: Option<Pos2>,
/// The id of the extra footer button pressed this pass (`ParamDialog::extra_buttons`).
pub footer_action: Option<String>,
}
impl Outcome for ParamDialogOutput {
@@ -183,6 +186,15 @@ pub struct ParamDialog<'a> {
/// preview clicks pick a colour turns it off. The default is true.
#[prop]
click_centres: bool,
/// The canvas the rows' droppers sample (`ParamRows::canvas`).
#[prop]
canvas: Option<egui::Id>,
/// Extra footer buttons, each an id and a label; a press comes back as `ParamDialogOutput::footer_action`.
#[prop]
extra_buttons: Vec<(String, Label)>,
/// The patterns the dialog's [`ParamKind::Pattern`] rows offer.
#[prop]
patterns: Cow<'a, [PresetRow<String>]>,
/// Controls before the buttons in the footer (Color Table's Load and Save).
#[prop(func = "FnMut(&mut Ui)")]
footer_extra: Option<FooterExtra<'a>>,
@@ -245,6 +257,9 @@ impl<'a> ParamDialog<'a> {
closable: true,
preview: None,
click_centres: true,
canvas: None,
extra_buttons: Vec::new(),
patterns: Cow::Borrowed(&[]),
footer_extra: None,
below: None,
shaped: None,
@@ -335,12 +350,16 @@ impl<'a> ParamDialog<'a> {
closable,
preview,
click_centres,
canvas,
extra_buttons,
patterns,
footer_extra,
below,
shaped,
answers,
values_opened,
} = self;
let _ = (&canvas, &extra_buttons, &patterns); // P3(dialogs-w1): dl.K21, dl.K22, dl.K28
let preview_label = Env::of(ui).words::<FormDialogWords>().preview.clone();
let mut form = match bound {
@@ -396,6 +415,7 @@ impl<'a> ParamDialog<'a> {
match answer {
HostAnswer::Color { key, color } | HostAnswer::Eyedropper { key, color } => set_color_field(&params, values, &key, color),
HostAnswer::Path { key, path } => values.set(&key, FieldValue::Text(path.to_string_lossy().into_owned())),
HostAnswer::Listing { .. } => {} // P3(dialogs-w1): dl.K26
}
}
live = cx.memory::<Live>().clone();
@@ -434,8 +454,16 @@ impl<'a> ParamDialog<'a> {
preview_on: shown.preview_on,
comparing: shown.comparing,
preview_click,
footer_action: None, // P3(dialogs-w1): dl.K22, from `FormOutput::picked`
}
}
/// A note in the footer, left of the buttons (a file size estimate, say).
#[allow(dead_code)] // P3(dialogs-w1): dl.K23
pub fn footer_note(mut self, note: impl Into<Label>) -> Self {
let _ = (&mut self, note.into());
todo!("dl.K23")
}
}
/// What the footer of an installed Reset footer reads from the body.
@@ -596,6 +624,32 @@ pub struct HostedParamDialog {
opened: bool,
build: Box<Build>,
requests: HostRequests,
/// Whether the dialog is open: bound to the dialog's `opened` prop.
#[allow(dead_code)] // P3(dialogs-w1): dl.K17
open: bool,
/// The preview picture the host last gave (`set_preview`).
#[allow(dead_code)] // P3(dialogs-w1): dl.K17
preview: Option<SizedTexture>,
/// What the dialog showed in its last pass.
#[allow(dead_code)] // P3(dialogs-w1): dl.K17
shown: ShownState,
/// An OK the host holds back until it answers `answer_ok` ([`held_ok`](HostedParamDialog::held_ok)).
#[allow(dead_code)] // P3(dialogs-w1): dl.K17
held: Option<Held>,
}
/// What a [`HostedParamDialog`] showed in its last pass: whether the preview is on and held for comparing.
#[derive(Clone, Copy, Debug, Default)]
#[allow(dead_code)] // P3(dialogs-w1): dl.K17
struct ShownState {
previewing: bool,
comparing: bool,
}
/// An OK a [`HostedParamDialog`] holds back until the host answers it.
#[allow(dead_code)] // P3(dialogs-w1): dl.K17
struct Held {
result: ParamResult,
}
impl HostedParamDialog {
@@ -614,6 +668,10 @@ impl HostedParamDialog {
opened: false,
build: Box::new(build),
requests: HostRequests::new(),
open: false,
preview: None,
shown: ShownState::default(),
held: None,
}
}
@@ -670,6 +728,84 @@ impl HostedParamDialog {
self.requests.answer_eyedropper(key, color);
}
/// Sets the picture the preview pane shows; `None` shows none.
pub fn set_preview(&mut self, picture: Option<SizedTexture>) {
let _ = picture;
todo!("dl.K18")
}
/// Whether the Preview check box is on: the host renders the preview while it is.
pub fn is_previewing(&self) -> bool {
todo!("dl.K18")
}
/// Whether the Preview check box is held down to compare with the unfiltered picture.
pub fn is_comparing(&self) -> bool {
todo!("dl.K18")
}
/// The eyedropper toggle that was pressed, once.
pub fn take_eyedropper(&mut self) -> Option<EyedropperRequest> {
todo!("dl.K19")
}
/// Makes OK file its answer for the host to take instead of closing: the host checks it and answers with
/// [`answer_ok`](HostedParamDialog::answer_ok).
#[must_use]
pub fn held_ok(self) -> Self {
todo!("dl.K20")
}
/// The OK filed by a held dialog, once.
pub fn take_ok(&mut self) -> Option<ParamResult> {
todo!("dl.K20")
}
/// The host's answer to the held OK: `Ok` closes the dialog with it, `Err` shows the label as the dialog's error.
pub fn answer_ok(&mut self, answer: Result<(), Label>) {
let _ = answer;
todo!("dl.K20")
}
/// The footer button id that was pressed, once (`ParamDialog::extra_buttons`).
pub fn take_footer_action(&mut self) -> Option<String> {
todo!("dl.K22")
}
/// The folder listing a files row asked for, once.
pub fn take_listing(&mut self) -> Option<ListingRequest> {
todo!("dl.K25")
}
/// Answers the listing request `key` with the `files` of its folder.
pub fn answer_listing(&mut self, key: impl Into<String>, files: Vec<std::path::PathBuf>) {
let _ = (key.into(), files);
todo!("dl.K25")
}
/// Sets the value under `key` as an edit would; the dialog shows it in its next pass.
pub fn set_field(&mut self, key: impl Into<String>, value: FieldValue) {
let _ = (key.into(), value);
todo!("dl.K70")
}
/// Centres the preview pane on `point` of the picture.
pub fn centre_preview(&mut self, point: Pos2) {
let _ = point;
todo!("dl.K71")
}
/// The point of the picture the preview pane is centred on, once it has been shown.
pub fn preview_centre(&self) -> Option<Pos2> {
todo!("dl.K80")
}
/// Shows `color` as the live preview of the colour row `key`; `None` ends it.
pub fn preview_color(&mut self, key: &str, color: Option<craft_theme::Srgba>) {
let _ = (key, color);
todo!("dl.K77")
}
/// The host cancelled its picker, file dialog or dropper: the requests not taken yet are dropped.
pub fn cancel_requests(&mut self) {
self.requests.cancel();
@@ -687,6 +823,14 @@ impl HostedParamDialog {
}
}
/// Checks `value` against the row `field` of `params` and sets it in `fields`, as the user editing the row would; `Err`
/// says why the row refused.
#[allow(dead_code)] // P3(dialogs-w1): dl.K69
pub fn set_param_field(params: &[Param], fields: &mut DialogFields, field: &str, value: Value) -> Result<(), String> {
let _ = (params, fields, field, value);
todo!("dl.K69")
}
/// `value` read as the value a row of `kind` keeps; `None` when it isn't one, or the row keeps none.
fn read_value(kind: &ParamKind, value: Value) -> Option<FieldValue> {
Some(match kind {
@@ -699,7 +843,10 @@ fn read_value(kind: &ParamKind, value: Value) -> Option<FieldValue> {
ParamKind::Color { .. } => FieldValue::Color(serde_json::from_value(value).ok()?),
ParamKind::Point { .. } => FieldValue::Point(serde_json::from_value(value).ok()?),
ParamKind::Grid { .. } => FieldValue::Grid(serde_json::from_value(value).ok()?),
ParamKind::ReadOnlyText { .. } | ParamKind::Custom(_) | ParamKind::Section => return None,
ParamKind::Blend { .. } | ParamKind::Pattern { .. } => FieldValue::Text(value.as_str()?.to_owned()),
ParamKind::Files { .. } => todo!("dl.K26"),
ParamKind::Custom(_) => FieldValue::Json(value),
ParamKind::ReadOnlyText { .. } | ParamKind::Section => return None,
})
}
@@ -11,6 +11,7 @@ mod path_row;
#[cfg(feature = "testing")]
mod stories;
use crate::contract::SaveKey;
use crate::runtime::env::Label;
use craft_behavior::PixelSize;
use serde::{Deserialize, Serialize};
@@ -19,7 +20,7 @@ use std::path::PathBuf;
pub use as_dialog::{ExportAsDialog, ExportAsOutput, HostedExportAs};
pub use options::{
DdsCompression, DdsOptions, ExportOptionsKind, FormatOptions, FormatOptionsDialog, FormatOptionsOutput, FormatOptionsWords, HostedFormatOptions,
JpegFormat, JpegOptions, JpegPreset, TargaOptions, TiffOptions, jpeg_quality_percent,
JpegFormat, JpegOptions, JpegPreset, TargaOptions, TiffCompression, TiffOptions, jpeg_quality_percent,
};
pub use path_row::{OutputPathOutput, OutputPathRow, OutputPathWords};
@@ -325,6 +326,16 @@ pub struct ExportAsResult {
pub path: PathBuf,
/// The output size in pixels.
pub size: PixelSize,
remember: Option<(SaveKey, ExportOptions)>,
}
impl ExportAsResult {
/// Stores the settings of a dialog built with [`ExportAsDialog::remember`] for the next open. The app calls it
/// after its export succeeds, so a failed export leaves the previous settings; without a key it does nothing.
pub fn remember(&self, ctx: &egui::Context) {
let _ = (ctx, &self.remember);
todo!("dl.K41")
}
}
/// A file name safe on every platform: at most 80 characters, control characters and `< > : " / \ | ? *` replaced by
@@ -7,10 +7,11 @@ use super::{
SizeEstimate, export_file_name, size_error_label,
};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use crate::patterns::presets::{NamedPresetEvent, PresetId, PresetLibrary};
use crate::runtime::requests::{HostAnswer, PathFilter, PathRequest};
use crate::choice::Checkbox;
use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _};
use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _};
use crate::display::{Shade, Text};
@@ -108,6 +109,8 @@ pub struct ExportAsOutput {
/// app opens its file dialog for it, then answers with [`ExportAsDialog::answers`]. A cancelled pick leaves the
/// dialog open.
pub requests: HostRequests,
/// The saved-preset edits the user made this pass (add, rename, delete), for the app to store.
pub presets: Vec<NamedPresetEvent<PresetId>>,
}
impl Outcome for ExportAsOutput {
@@ -154,6 +157,12 @@ pub struct ExportAsDialog<'a> {
/// The app's save dialog is open: Export waits.
#[prop]
saving: bool,
/// Binds the saved presets of the settings to `presets`.
#[prop]
presets: Option<Bind<'a, PresetLibrary<ExportOptions>>>,
/// Saves the settings under `key` when the app calls [`ExportAsResult::remember`], and opens with them.
#[prop]
remember: Option<SaveKey>,
}
impl<'a> ExportAsDialog<'a> {
@@ -169,12 +178,15 @@ impl<'a> ExportAsDialog<'a> {
preview: None,
answers: Vec::new(),
saving: false,
presets: None,
remember: None,
}
}
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> ExportAsOutput {
let ExportAsDialog { file_name, source, bound, formats, open, defaults, preview, answers, saving } = self;
let ExportAsDialog { file_name, source, bound, formats, open, defaults, preview, answers, saving, presets, remember } = self;
let _ = (&presets, &remember); // P3(dialogs-w14): dl.K41
let env = Env::of(ui);
let words = env.words::<ExportWords>();
let pass = Pass { formats: &formats, source, words: &words, sizing: env.words::<SizingWords>(), units: env.units(), defaults };
@@ -225,8 +237,13 @@ impl<'a> ExportAsDialog<'a> {
let filters = format.map(|format| PathFilter::new(format.name, &[format.extension]));
requests.request_path(PathRequest::save(SAVE_KEY, name, filters));
}
let result = accepted.zip(answered.into_inner()).map(|(options, path)| ExportAsResult { size: options.output_size(source), options, path });
ExportAsOutput { response, closed, result, wanted_preview: wanted.into_inner(), requests }
let result = accepted.zip(answered.into_inner()).map(|(options, path)| ExportAsResult {
size: options.output_size(source),
options,
path,
remember: None,
});
ExportAsOutput { response, closed, result, wanted_preview: wanted.into_inner(), requests, presets: Vec::new() }
}
}
@@ -256,6 +273,30 @@ pub struct HostedExportAs {
}
impl HostedExportAs {
/// Opens with `library` as the saved presets.
#[must_use]
pub fn presets(mut self, library: PresetLibrary<ExportOptions>) -> Self {
let _ = (&mut self, library);
todo!("dl.K41")
}
/// Saves the settings under `key` when the app calls [`ExportAsResult::remember`], and opens with them.
#[must_use]
pub fn remember(mut self, key: SaveKey) -> Self {
let _ = (&mut self, key);
todo!("dl.K41")
}
/// The saved presets as the user left them.
pub fn saved_presets(&self) -> &PresetLibrary<ExportOptions> {
todo!("dl.K41")
}
/// The saved-preset edits since the last call, for the app to store.
pub fn take_preset_events(&mut self) -> Vec<NamedPresetEvent<PresetId>> {
todo!("dl.K41")
}
/// A hosted dialog for the document named `file_name` (no extension) of size `source`, opening with `options`.
pub fn new(file_name: impl Into<String>, source: PixelSize, options: ExportOptions) -> Self {
HostedExportAs {
@@ -329,6 +370,20 @@ const EXPORT_KEY: &str = "file.exportAs";
impl StackDialog for HostedExportAs {
type Result = ExportAsResult;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K41")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K41")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K41")
}
fn id(&self) -> DialogId {
self.id
}
@@ -2,11 +2,12 @@
//! JPEG, layered TIFF, Targa and DDS are one form over four parameter lists; OK and Cancel, Enter and Escape come from
//! `ParamDialog`, and Cancel abandons the save.
use super::SizeEstimate;
use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use crate::form::Field;
use crate::layout_components::{Row, Stack};
use crate::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamResult};
use crate::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamResult, PreviewRequest};
use crate::pickers::Select;
use crate::runtime::env::{Env, Label};
use crate::runtime::overlay::CloseReason;
@@ -171,6 +172,25 @@ pub struct TiffOptions {
pub discard_layers: bool,
/// Don't ask again: the app clears its "ask before saving layered TIFF" preference.
pub dont_show_again: bool,
/// How the pixel data is compressed.
pub compression: TiffCompression,
/// Save the reduced-resolution levels of a pyramidal TIFF.
pub pyramid: bool,
/// Keep the transparency as an alpha channel.
pub transparency: bool,
}
/// How a TIFF's pixel data is compressed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TiffCompression {
/// No compression.
#[default]
None,
/// LZW.
Lzw,
/// ZIP (Deflate).
Zip,
}
/// What Targa Options answers with.
@@ -274,8 +294,8 @@ const DEFAULT_QUALITY: u8 = 8;
const QUALITY: &str = "quality";
const FORMAT: &str = "format";
const DISCARD: &str = "discard";
const DONT_SHOW: &str = "dontShow";
const DISCARD: &str = "discardLayers";
const DONT_SHOW: &str = "dontShowAgain";
const BITS: &str = "bits";
const COMPRESSION: &str = "compression";
const MIPMAPS: &str = "mipmaps";
@@ -318,17 +338,30 @@ pub struct FormatOptionsDialog<'a> {
/// The options the dialog opens with.
#[prop]
initial: Option<FormatOptions>,
/// The estimated size of the saved file, shown in the footer: `None` is unknown (not asked yet), `Some(None)` is
/// being worked out.
#[prop]
estimate: Option<Option<SizeEstimate>>,
}
impl<'a> FormatOptionsDialog<'a> {
/// The dialog for the options of `kind`.
pub fn new(kind: ExportOptionsKind) -> Self {
FormatOptionsDialog { kind, open: None, initial: None }
FormatOptionsDialog { kind, open: None, initial: None, estimate: None }
}
/// Offers the TIFF rows of a document: Discard Layers when it has `layered`, Transparency when it is `transparent`,
/// and the note about the layers when `layer_note` is set.
#[must_use]
pub fn tiff_document(mut self, layered: bool, transparent: bool, layer_note: bool) -> Self {
let _ = (&mut self, layered, transparent, layer_note);
todo!("dl.K42")
}
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> FormatOptionsOutput {
let FormatOptionsDialog { kind, open, initial } = self;
let FormatOptionsDialog { kind, open, initial, estimate } = self;
let _ = &estimate; // P3(dialogs-w14): dl.K42
let words = Env::of(ui).words::<FormatOptionsWords>();
let start = initial.filter(|options| options.kind() == kind).unwrap_or_else(|| FormatOptions::default_for(kind));
let title = match kind {
@@ -377,6 +410,17 @@ pub struct HostedFormatOptions {
}
impl HostedFormatOptions {
/// The settings the app should estimate the file size for, once, when they changed since the last call.
pub fn wanted_estimate(&mut self) -> Option<PreviewRequest<FormatOptions>> {
todo!("dl.K42")
}
/// The app's estimate for the settings of `revision`; an answer for an older revision is dropped.
pub fn set_estimate(&mut self, revision: u64, estimate: Option<SizeEstimate>) {
let _ = (revision, estimate);
todo!("dl.K42")
}
/// The options dialog of `kind`.
pub fn new(kind: ExportOptionsKind) -> Self {
HostedFormatOptions {
@@ -405,12 +449,26 @@ impl HostedFormatOptions {
impl StackDialog for HostedFormatOptions {
type Result = FormatOptions;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K42")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K42")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K42")
}
fn id(&self) -> DialogId {
self.id
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<FormatOptions>> {
let shown = FormatOptionsDialog { kind: self.kind, open: Some(Bind::bound(&mut self.open)), initial: self.initial }.show(ui);
let shown = FormatOptionsDialog { kind: self.kind, open: Some(Bind::bound(&mut self.open)), initial: self.initial, estimate: None }.show(ui);
#[cfg(feature = "testing")]
{
self.facts = crate::contract::Outcome::story_facts(&shown);
@@ -548,6 +606,9 @@ fn answer(start: FormatOptions, result: &ParamResult) -> FormatOptions {
ExportOptionsKind::Tiff => FormatOptions::Tiff(TiffOptions {
discard_layers: fields.bool(DISCARD).unwrap_or_default(),
dont_show_again: fields.bool(DONT_SHOW).unwrap_or_default(),
compression: TiffCompression::default(), // P3(dialogs-w14): dl.K42
pyramid: false,
transparency: false,
}),
ExportOptionsKind::Targa => {
FormatOptions::Targa(TargaOptions::new(fields.text(BITS).and_then(|bits| bits.parse().ok()).unwrap_or(TARGA_BITS)))
@@ -32,6 +32,9 @@ pub enum FieldValue {
/// three numbers reads back as `Grid`, `Point` or `Color`, which [`DialogFields::list`] turns
/// back into the list.
List(Vec<FieldValue>),
/// Any JSON value: what a [`ParamKind::Custom`](super::ParamKind::Custom) row keeps under its key. Last so an
/// untagged read keeps the fixed-shape variants above.
Json(serde_json::Value),
}
impl From<bool> for FieldValue {
@@ -0,0 +1,402 @@
//! [`FileListPicker`]: a list of chosen files (or one folder) with Browse, Remove and the other list buttons, inside a
//! dialog that loads several files.
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Selection};
use craft_host::{PickId, PickKind, PickRequest};
use craft_ui::buttons::Button;
use craft_ui::contract::{
Bind, BodyCx, CollectionEvent, Entry, Held, NoValue, Outcome, Pad, Props as _, Remember as _, ReorderRule, SelectMode, Show as _,
ShowCollection as _, ShowContainer as _, Sizing, clicked,
};
use craft_ui::display::{Shade, Text};
use craft_ui::form::Field;
use craft_ui::layout_components::Stack;
use craft_ui::list::{List, ListRow};
use craft_ui::pickers::Select;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::style::SurfaceKind;
use egui::{Response, Ui};
use std::borrow::Cow;
use std::cell::RefCell;
use std::path::{Path, PathBuf};
#[cfg(feature = "testing")]
mod stories;
craft_ui::words! {
/// The words of the file list picker.
pub struct FileListWords {
use_label: "fileListPicker.use" = "Use:";
files: "fileListPicker.files" = "Files";
folder: "fileListPicker.folder" = "Folder";
browse: "fileListPicker.browse" = "Browse…";
remove: "fileListPicker.remove" = "Remove";
add_open_files: "fileListPicker.addOpenFiles" = "Add Open Files";
sort_by_name: "fileListPicker.sortByName" = "Sort By Name";
add_files: "fileListPicker.addFiles" = "Add the files to load";
choose_folder: "fileListPicker.chooseFolder" = "Choose a folder to load";
}
}
/// Files picked one by one, or one folder whose files the app lists.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FileListMode {
/// Individual files, listed in the user's order.
#[default]
Files,
/// One folder; the app lists its files.
Folder,
}
/// The picker's value; the dialog keeps it.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct FileList {
/// Whether files or a folder are picked.
pub mode: FileListMode,
/// The chosen files in Files mode, in the user's order. The paths are distinct: they are the list's row keys, so
/// add files through [`FileList::add`].
pub files: Vec<PathBuf>,
/// The folder in Folder mode.
pub folder: Option<PathBuf>,
/// The selected file in Files mode, one of `files`.
pub selected: Option<PathBuf>,
}
impl FileList {
/// Adds paths not in the list yet, in order (Browse, Add Open Files, a drop).
pub fn add(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
for path in paths {
if !self.files.contains(&path) {
self.files.push(path);
}
}
}
/// Whether OK may run: Files mode needs a file, Folder mode a folder.
pub fn is_valid(&self) -> bool {
match self.mode {
FileListMode::Files => !self.files.is_empty(),
FileListMode::Folder => self.folder.as_ref().is_some_and(|folder| !folder.as_os_str().is_empty()),
}
}
/// Why OK can't run, for the dialog's message: "Add the files to load" or "Choose a folder to load"; `None` when
/// [`is_valid`](Self::is_valid).
pub fn problem<'l>(&self, words: &'l FileListWords) -> Option<&'l str> {
if self.is_valid() {
return None;
}
Some(match self.mode {
FileListMode::Files => words.add_files.as_str(),
FileListMode::Folder => words.choose_folder.as_str(),
})
}
}
/// The second line of a file's row.
type InfoLine<'a> = &'a dyn Fn(&Path) -> Option<String>;
/// The pick the picker is waiting for and what it asked for, kept in the picker's container while it is shown.
#[derive(Clone, Copy, Default)]
struct Ticket(Option<(PickId, PickKind)>);
/// What the picker reports.
#[derive(Debug)]
#[non_exhaustive]
pub struct FileListPickerOutput {
/// The picker's response.
pub response: Response,
/// The list, mode or folder changed in this pass.
pub changed: bool,
/// Browse queued a picker; the answer fills the list on a later pass.
pub browsing: Option<PickId>,
}
impl Outcome for FileListPickerOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// Photoshop's Load Files into Stack file list, after PhotoCraft's port of it.
///
/// The user sees "Use:" with Files and Folder (when [`folder_mode`](Self::folder_mode) is on), the list (one row per
/// file showing its name, the full path as tooltip, and the app's info line under the name when given) and a column of
/// buttons beside it, one width: Browse… (an open-many picker in Files mode, a folder picker in Folder mode, both through `host.files()`),
/// Remove (with a row selected), Add Open Files (when the app passed open documents with a path) and Sort By Name (more
/// than one file; sorts by name ignoring case). In Folder mode the list shows the folder's files the app passes and has
/// no selection.
///
/// Keys: the list is one Tab stop; arrows move the selection; Delete and Backspace remove the selected file; Cmd+] and
/// Cmd+[ move it up and down (Ctrl off macOS; Shift to the ends). Dropped files are added by the dialog with [`FileList::add`].
#[must_use = "show the picker with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
pub struct FileListPicker<'a> {
label: Label,
list: Bind<'a, FileList>,
/// Browse's picker in Files mode (purpose, filters); Folder mode asks for a folder with the same purpose.
#[prop]
request: PickRequest,
/// Offers Folder mode.
#[prop]
folder_mode: bool,
/// The open documents' paths, for Add Open Files.
#[prop]
open_files: &'a [PathBuf],
/// The files the app found in the chosen folder, shown in Folder mode.
#[prop]
folder_files: &'a [PathBuf],
/// A second line per file ("1200 × 800 px, 300 ppi, RGB"); none for no line.
#[prop]
info: Option<InfoLine<'a>>,
}
impl<'a> FileListPicker<'a> {
/// The picker named `label` over `list`; Browse asks with `PickRequest::open_many("stack")` until
/// [`request`](Self::request) replaces it.
pub fn new(label: impl Into<Label>, list: Bind<'a, FileList>) -> Self {
FileListPicker {
label: label.into(),
list,
request: PickRequest::open_many("stack"),
folder_mode: false,
open_files: &[],
folder_files: &[],
info: None,
}
}
/// Shows the picker. Takes the answer of its own Browse ticket from the host's file service.
pub fn show(self, ui: &mut Ui) -> FileListPickerOutput {
let FileListPicker { label, list, request, folder_mode, open_files, folder_files, info } = self;
let words = Env::of(ui).words::<FileListWords>();
let pass = RefCell::new(Pass { held: Held::new(list), seen: None, browsing: None });
let mut stack = Stack::new().fill();
if folder_mode {
stack = stack.header(|ui, cx| {
let mut pass = pass.borrow_mut();
let now = pass.load(cx);
let modes = [Entry::new(FileListMode::Files, words.files.clone()), Entry::new(FileListMode::Folder, words.folder.clone())];
Field::new(words.use_label.clone()).id_salt("use").show(ui, |ui, _| {
if let Some(mode) = Select::new(words.use_label.clone(), Bind::given(now.mode), &modes).id_salt("mode").show(ui).value().copied()
{
now.mode = mode;
now.selected = None;
}
});
});
}
let shown = stack
.footer(|ui, cx| {
let mut pass = pass.borrow_mut();
let host = cx.env.host().cloned();
// The footer is measured in a sizing pass before it is shown: that pass only reads the list, so the
// answer is taken and the binding written once, in the shown pass.
let sizing = ui.is_sizing_pass();
let mut measured;
let now = if sizing {
measured = pass.peek(cx);
&mut measured
} else {
pass.load(cx)
};
let folder = now.mode == FileListMode::Folder;
let (mut browse, mut remove, mut add_open, mut sort) = (false, false, false, false);
Stack::new().show(ui, |ui, _| {
let button = |ui: &mut Ui, label: &Label, key: &'static str, enabled: bool| {
clicked(&Button::new(label.clone()).enabled(enabled).sizing(Sizing::FillWidth).id_salt(key).show(ui))
};
browse = button(ui, &words.browse, "browse", true);
remove = button(ui, &words.remove, "remove", !folder && now.selected.is_some());
add_open = button(ui, &words.add_open_files, "add-open", !folder && !open_files.is_empty());
sort = button(ui, &words.sort_by_name, "sort", !folder && now.files.len() > 1);
});
if sizing {
return;
}
if remove && let Some(path) = now.selected.take() {
now.files.retain(|file| *file != path);
}
if add_open {
now.add(open_files.iter().cloned());
}
if sort {
now.files.sort_by_key(|path| file_name(path).to_lowercase());
now.selected = None;
}
if browse && let Some(host) = &host {
let asked = if folder { PickRequest::folder(request.purpose.clone()) } else { request.clone() };
let kind = asked.kind;
let id = host.files().pick(asked);
cx.memory::<Ticket>().0 = Some((id, kind));
pass.browsing = Some(id);
}
pass.finish(cx, label.as_str());
})
.footer_beside()
.show(ui, |ui, cx| {
let mut pass = pass.borrow_mut();
let now = pass.load(cx);
let folder = now.mode == FileListMode::Folder;
if folder && let Some(path) = &now.folder {
Text::new(path.to_string_lossy().into_owned()).shade(Shade::Muted).show(ui);
}
let paths: &[PathBuf] = if folder { folder_files } else { &now.files };
let source = Rows::new(paths);
let mut selection =
now.selected.as_ref().filter(|path| paths.contains(path)).map_or_else(Selection::default, |path| Selection::single(path.clone()));
let list = List::new(words.files.clone()).id_salt("files").surface(SurfaceKind::Sunken).pad(Pad::Control);
let list = if folder {
list.select(SelectMode::None)
} else {
list.select(SelectMode::Single).deletable(true).reorder(ReorderRule::new()).selection(Bind::bound(&mut selection))
};
let events = list.show_items(ui, &source, &mut |path, _| file_row(path, info)).events;
if folder {
return;
}
now.selected = selection.items.first().cloned();
for event in events {
match event {
CollectionEvent::Delete(keys) => {
now.files.retain(|path| !keys.contains(path));
now.selected = None;
}
CollectionEvent::Reorder(EditEvent::Set { after, .. } | EditEvent::Commit { after, .. }) => {
move_files(&mut now.files, &after.keys, after.to);
now.selected = Some(after.key.clone());
}
_ => {}
}
}
});
let pass = pass.into_inner();
let changed = pass.seen.as_ref().is_some_and(|(before, now)| before != now);
FileListPickerOutput { response: shown.output, changed, browsing: pass.browsing }
}
}
/// What the regions of one pass share: the bound value, its working copy and the ticket this pass issued.
struct Pass<'h> {
held: Held<'h, FileList>,
/// The value at the start of the pass and its working copy.
seen: Option<(FileList, FileList)>,
browsing: Option<PickId>,
}
impl Pass<'_> {
/// The working copy, read and given the pick answer on the region that runs first.
/// Every load asks for the answer: a measuring run gets none, so the run that receives it puts it in the copy.
fn load(&mut self, cx: &mut BodyCx<'_>) -> &mut FileList {
let held = &mut self.held;
let (_, now) = self.seen.get_or_insert_with(|| {
let before = held.read(cx).unwrap_or_default();
let mut now = before.clone();
if now.selected.as_ref().is_some_and(|path| !now.files.contains(path)) {
now.selected = None;
}
(before, now)
});
take_answer(cx, now);
now
}
/// The working copy as far as it is known, without taking the pick answer.
fn peek(&mut self, cx: &mut BodyCx<'_>) -> FileList {
match &self.seen {
Some((_, now)) => now.clone(),
None => self.held.read(cx).unwrap_or_default(),
}
}
/// Writes the working copy to the binding when the pass changed it.
fn finish(&mut self, cx: &mut BodyCx<'_>, name: &str) {
if let Some((before, now)) = &self.seen
&& before != now
{
let (before, now) = (before.clone(), now.clone());
self.held.write(cx, &before, now, name);
}
}
}
/// Puts the answer of the ticket this picker kept into `now`.
fn take_answer(cx: &mut BodyCx<'_>, now: &mut FileList) {
let Some((ticket, kind)) = cx.memory::<Ticket>().0 else { return };
let Some(picked) = cx.take_pick_answer(ticket) else { return };
cx.memory::<Ticket>().0 = None;
if kind == PickKind::Folder {
if let Some(folder) = picked.paths().into_iter().next() {
now.folder = Some(folder);
}
} else {
now.add(picked.paths());
}
}
/// The files as the list's item source: a file's path is its key (the paths in a list are distinct), so the lead and the
/// selection follow a file when the list reorders.
struct Rows<'a> {
paths: &'a [PathBuf],
names: Vec<String>,
}
impl<'a> Rows<'a> {
fn new(paths: &'a [PathBuf]) -> Self {
Rows { paths, names: paths.iter().map(|path| file_name(path)).collect() }
}
}
impl DisplayOrder<PathBuf> for Rows<'_> {
fn len(&self) -> usize {
self.paths.len()
}
fn key(&self, at: usize) -> PathBuf {
self.paths[at].clone()
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
self.names.get(at).map(|name| Cow::Borrowed(name.as_str()))
}
}
impl ItemSource<PathBuf> for Rows<'_> {}
/// One file's row: its name, the path for a screen reader, the app's info line under the name.
fn file_row<'a>(path: &Path, info: Option<InfoLine<'_>>) -> ListRow<'a> {
let name = file_name(path);
let line = info.and_then(|info| info(path));
let accessible = match &line {
Some(line) => format!("{name}, {line}"),
None => name.clone(),
};
let full = path.to_string_lossy().into_owned();
let row = ListRow::new(name).accessible_name(accessible).description(full.clone()).tooltip(full);
match line {
Some(line) => row.detail(line),
None => row,
}
}
fn file_name(path: &Path) -> String {
path.file_name().map_or_else(|| path.to_string_lossy(), |name| name.to_string_lossy()).into_owned()
}
/// Moves the files at `keys` (display order) together, so the first of them lands at `to` in the order that remains
/// once all of them are taken out.
fn move_files(files: &mut Vec<PathBuf>, keys: &[PathBuf], to: usize) {
let mut places: Vec<usize> = keys.iter().filter_map(|key| files.iter().position(|path| path == key)).collect();
places.sort_unstable();
places.dedup();
let moved: Vec<PathBuf> = places.iter().map(|&at| files[at].clone()).collect();
for &at in places.iter().rev() {
files.remove(at);
}
let to = to.min(files.len());
files.splice(to..to, moved);
}
@@ -0,0 +1,39 @@
//! Stories of the file list picker.
use super::{FileList, FileListMode, FileListPicker};
use craft_ui::contract::Bind;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use std::path::PathBuf;
/// A name of the files the stories list.
const FILES: [&str; 3] = ["sunrise.png", "harbour.png", "market.png"];
fn photos() -> Vec<PathBuf> {
FILES.iter().map(|name| PathBuf::from("/photos/trip").join(name)).collect()
}
#[story(FileListPicker<'static>, covers = [Many], drive = Drive::Never)]
fn file_list_picker_files(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut start = FileList::default();
start.add(photos());
let open = [PathBuf::from("/photos/trip/dusk.png")];
FileListPicker::new("Files to load", Bind::bound(data.value("files", start)))
.folder_mode(true)
.open_files(&open)
.info(&|_| Some("1200 × 800 px, 300 ppi, RGB".to_owned()))
.show(ui)
.into()
}
#[story(FileListPicker<'static>, covers = [Empty], drive = Drive::Never)]
fn file_list_picker_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
FileListPicker::new("Files to load", Bind::bound(data.value("empty", FileList::default()))).show(ui).into()
}
#[story(FileListPicker<'static>, covers = [], drive = Drive::Never)]
fn file_list_picker_folder(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = FileList { mode: FileListMode::Folder, folder: Some(PathBuf::from("/photos/trip")), ..FileList::default() };
let files = photos();
FileListPicker::new("Files to load", Bind::bound(data.value("folder", start))).folder_mode(true).folder_files(&files).show(ui).into()
}
@@ -508,12 +508,22 @@ pub struct HostedGuideLayoutDialog {
build: Box<Build>,
preview: Option<Vec<Guide>>,
requests: HostRequests,
/// Whether the dialog is open: bound to the dialog's `opened` prop.
#[allow(dead_code)] // P3(dialogs-w13): dl.K36
open: bool,
}
impl HostedGuideLayoutDialog {
/// A dialog opening with `values`; `build` makes it over the values.
pub fn new(values: GuideLayoutValues, build: impl for<'b> Fn(Bind<'b, GuideLayoutValues>) -> GuideLayoutDialog<'b> + Send + 'static) -> Self {
HostedGuideLayoutDialog { id: dialog_id("guides.layout"), values, build: Box::new(build), preview: None, requests: HostRequests::new() }
HostedGuideLayoutDialog {
id: dialog_id("guides.layout"),
values,
build: Box::new(build),
preview: None,
requests: HostRequests::new(),
open: true,
}
}
/// The values the dialog shows.
@@ -535,6 +545,20 @@ impl HostedGuideLayoutDialog {
impl StackDialog for HostedGuideLayoutDialog {
type Result = GuideLayoutResult;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K36")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K36")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K36")
}
fn id(&self) -> DialogId {
self.id
}
@@ -7,7 +7,7 @@ use super::{FormDialog, GUIDE_LIMIT, GuideDialogWords, HostRequests, NEW_GUIDE_C
use crate::canvas_data::{Guide, GuideColor, GuideKey};
use crate::choice::Segmented;
use crate::contract::{Bind, Entry, NoValue, Outcome, Show as _, ShowContainer as _};
use crate::contract::{Bind, Entry, NoValue, Outcome, SaveKey, Show as _, ShowContainer as _};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
@@ -112,12 +112,15 @@ pub struct NewGuideDialog<'a> {
/// Binds the open state to `open`.
#[prop(name = "opened")]
open: Option<Bind<'a, bool>>,
/// Saves the values under `key` for the next open.
#[prop]
remember: Option<SaveKey>,
}
impl<'a> NewGuideDialog<'a> {
/// New Guide over `values`, for a document measured in `units`.
pub fn new(units: GuideUnits, values: Bind<'a, NewGuideValues>) -> Self {
NewGuideDialog { units, values, edit: None, key: GuideKey::new(0), error: None, answers: Vec::new(), open: None }
NewGuideDialog { units, values, edit: None, key: GuideKey::new(0), error: None, answers: Vec::new(), open: None, remember: None }
}
/// Edit Selected Guides for `guide`, which is drawn in `preference` when it has no colour of its own: the
@@ -128,7 +131,8 @@ impl<'a> NewGuideDialog<'a> {
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> NewGuideOutput {
let NewGuideDialog { units, values, edit, key, error, answers, open } = self;
let NewGuideDialog { units, values, edit, key, error, answers, open, remember } = self;
let _ = &remember; // P3(dialogs-w13): dl.K36
let env = Env::of(ui);
let words = env.words::<GuideDialogWords>();
let number_units = env.units();
@@ -221,12 +225,15 @@ pub struct HostedNewGuideDialog {
values: NewGuideValues,
build: Box<Build>,
requests: HostRequests,
/// Whether the dialog is open: bound to the dialog's `opened` prop.
#[allow(dead_code)] // P3(dialogs-w13): dl.K36
open: bool,
}
impl HostedNewGuideDialog {
/// A dialog opening with `values`; `build` makes it over the values (`NewGuideDialog::new` or `edit`).
pub fn new(values: NewGuideValues, build: impl for<'b> Fn(Bind<'b, NewGuideValues>) -> NewGuideDialog<'b> + Send + 'static) -> Self {
HostedNewGuideDialog { id: dialog_id("guides.newGuide"), values, build: Box::new(build), requests: HostRequests::new() }
HostedNewGuideDialog { id: dialog_id("guides.newGuide"), values, build: Box::new(build), requests: HostRequests::new(), open: true }
}
/// The values the dialog shows.
@@ -234,6 +241,12 @@ impl HostedNewGuideDialog {
&self.values
}
/// Shows `error` above the fields: the app's message when it refused the position.
pub fn set_error(&mut self, error: Option<Label>) {
let _ = error;
todo!("dl.K36")
}
/// What the dialog asked of the host and the host's answers: take the colour request, answer it.
pub fn requests(&mut self) -> &mut HostRequests {
&mut self.requests
@@ -243,6 +256,20 @@ impl HostedNewGuideDialog {
impl StackDialog for HostedNewGuideDialog {
type Result = Guide;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K36")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K36")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K36")
}
fn id(&self) -> DialogId {
self.id
}
@@ -1,7 +1,7 @@
//! `HostRequests`: what a hosted dialog's rows ask of the host, kept until the host takes it.
use super::rows::ParamRowsOutput;
use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, PathRequest};
use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest};
use craft_theme::Srgba;
use egui::Pos2;
use std::path::PathBuf;
@@ -127,6 +127,46 @@ impl HostRequests {
self.answers.extend(answers);
}
/// Files a footer button's id the user pressed; it replaces one not taken yet.
#[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn request_footer_action(&mut self, id: String) {
let _ = id;
todo!("dl.K24")
}
/// The footer button id that was pressed, once.
#[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn take_footer_action(&mut self) -> Option<String> {
todo!("dl.K24")
}
/// Files a request for the files of a folder; it replaces one not taken yet.
#[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn request_listing(&mut self, request: ListingRequest) {
let _ = request;
todo!("dl.K24")
}
/// The folder listing that was requested, once.
#[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn take_listing(&mut self) -> Option<ListingRequest> {
todo!("dl.K24")
}
/// Answers the listing request `key` with the `files` of its folder: the dialog applies them in its next pass.
#[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn answer_listing(&mut self, key: impl Into<String>, files: Vec<PathBuf>) {
let _ = (key.into(), files);
todo!("dl.K24")
}
/// Shows `color` as the live preview of the colour row `key` while it is picked; `None` ends the preview.
#[allow(dead_code)] // P3(dialogs-w1): dl.K77
pub fn preview_color(&mut self, key: impl Into<String>, color: Option<Srgba>) {
let _ = (key.into(), color);
todo!("dl.K77")
}
/// Drops the colour request not taken yet (the picker was cancelled).
pub fn cancel_color(&mut self) {
self.color = None;
@@ -19,6 +19,7 @@ mod preview;
pub use dialog::{
BelowRows, FooterExtra, HostedParamDialog, ParamDialog, ParamDialogOutput, ParamDialogWords, ParamLayout, ParamResult, ResetFooter, ResetPick,
set_param_field,
};
pub use form::{FormCx, FormDialog, FormDialogWords, FormOutput};
pub use host_requests::{HostRequests, PreviewRequest};
@@ -37,7 +38,11 @@ mod report;
pub use list_manager::{ActionEnabled, ListManager, ListManagerAction, ListManagerChoice, ListManagerEntry, ListManagerOutput, ListManagerWords};
pub use password::{PasswordAnswer, PasswordDialog, PasswordOutput, PasswordPurpose, PasswordStrength, PasswordWords, Secret};
pub use report::{ReportDialog, ReportNote, ReportOutput, ReportWords};
pub use report::{HostedReport, ReportDialog, ReportNote, ReportOutput, ReportWords};
mod file_list;
pub use file_list::{FileList, FileListMode, FileListPicker, FileListPickerOutput, FileListWords};
mod sizing;
@@ -83,7 +88,7 @@ pub use export::{
DdsCompression, DdsOptions, ExportAsDialog, ExportAsOutput, ExportAsResult, ExportFormat, ExportFormatDefaults, ExportMetadata, ExportOptions,
ExportOptionsKind, ExportPreview, ExportProfile, ExportSize, ExportWords, FormatOptions, FormatOptionsDialog, FormatOptionsOutput,
FormatOptionsWords, HostedExportAs, HostedFormatOptions, JpegFormat, JpegOptions, JpegPreset, OutputPathOutput, OutputPathRow, OutputPathWords,
SizeEstimate, TargaOptions, TiffOptions, jpeg_quality_percent,
SizeEstimate, TargaOptions, TiffCompression, TiffOptions, jpeg_quality_percent,
};
// Save PDF.
@@ -95,7 +100,8 @@ mod save_for_web;
mod watermark;
pub use save_for_web::{
Animation, ColorTable, Dither, HostedSaveForWeb, MATTE_COLOR_KEY, SAVE_PATH_KEY, SaveForWebDialog, SaveForWebOptions, SaveForWebOutput,
SaveForWebResult, SaveForWebWords, WantedVariant, WebFormat, WebMetadata, WebPane, WebPictures, WebPreset, WebVariant, WebView,
Animation, ColorTable, Dither, HostedSaveForWeb, MATTE_COLOR_KEY, PALETTE_COLOR_KEY, SAVE_PATH_KEY, SaveForWebDialog, SaveForWebOptions,
SaveForWebOutput, SaveForWebResult, SaveForWebWords, WantedVariant, WebFormat, WebMetadata, WebPane, WebPictures, WebPreset, WebSlice, WebSlices,
WebVariant, WebView,
};
pub use watermark::{ROTATIONS, WATERMARK_IMAGE_KEY, Watermark, WatermarkOutput, WatermarkSettings, WatermarkStyle, WatermarkWords};
@@ -15,7 +15,7 @@ use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}
use crate::layout_components::{Grid, Stack};
use crate::patterns::presets::{GroupPath, PresetLibrary, PresetWords as LibraryWords};
use crate::patterns::presets::{GroupPath, NamedPresetEvent, PresetId, PresetLibrary, PresetWords as LibraryWords};
use crate::runtime::env::{Env, Label, UnitKind, Units};
use crate::runtime::memory::{MemoryStage, unique};
@@ -23,7 +23,7 @@ use crate::runtime::overlay::CloseReason;
use craft_behavior::{ColumnWidth, PixelSize};
use craft_theme::Srgba;
use egui::{Response, Ui};
use egui::{Context, Response, Ui};
use cards::{Left, TabId};
@@ -285,9 +285,9 @@ impl NewDocumentResult {
/// Stores the recent list of a dialog built with [`NewDocumentDialog::remember_recent`], with these settings first,
/// for the next open. The app calls it after its create command succeeds, so a failed command leaves the list as
/// it was; without a key it does nothing.
pub fn remember(&self, ui: &Ui) {
pub fn remember(&self, ctx: &Context) {
if let Some((key, list)) = &self.remember {
let mut stage = MemoryStage::open(ui.ctx(), unique(("craft_ui::new_document_recent", key.as_str())));
let mut stage = MemoryStage::open(ctx, unique(("craft_ui::new_document_recent", key.as_str())));
*stage.saved::<Vec<DocumentOptions>>(key) = list.clone();
stage.write_back();
}
@@ -309,6 +309,8 @@ pub struct NewDocumentOutput {
/// chosen or the colour button pressed), keyed `BACKGROUND_COLOR_KEY`. The app answers with
/// [`NewDocumentDialog::answers`].
pub requests: HostRequests,
/// The saved-preset edits the user made this pass (add, rename, delete), for the app to store.
pub presets: Vec<NamedPresetEvent<PresetId>>,
}
impl Outcome for NewDocumentOutput {
@@ -452,6 +454,15 @@ pub struct NewDocumentDialog<'a> {
/// The colour profiles each mode offers.
#[prop]
profiles: Vec<ColorProfiles>,
/// Binds the saved presets of the Saved tab to `saved`.
#[prop]
saved: Option<Bind<'a, PresetLibrary<DocumentOptions>>>,
/// Binds the recent documents of the Recent tab to `recent`.
#[prop]
recent: Option<Bind<'a, Vec<DocumentOptions>>>,
/// Binds the shown tab's id (`recent`, `saved` or a category's id) to `tab`.
#[prop]
tab: Option<Bind<'a, String>>,
/// The application's name, for the "Default {app} Size" card.
#[prop(into)]
app_name: Option<Label>,
@@ -478,6 +489,9 @@ impl<'a> NewDocumentDialog<'a> {
print_resolution: 300.0,
screen_resolution: 72.0,
profiles: Vec::new(),
saved: None,
recent: None,
tab: None,
app_name: None,
remember: None,
answers: Vec::new(),
@@ -497,10 +511,14 @@ impl<'a> NewDocumentDialog<'a> {
print_resolution,
screen_resolution,
profiles,
saved,
recent: recent_bound,
tab,
app_name,
remember,
answers,
} = self;
let _ = (&saved, &recent_bound, &tab); // P3(dialogs-w14): dl.K39
let recent: Vec<DocumentOptions> = remember_recent.as_ref().map_or_else(Vec::new, |key| MemoryStage::peek_saved(ui.ctx(), key));
let env = Env::of(ui);
let words = env.words::<NewDocumentWords>();
@@ -549,6 +567,7 @@ impl<'a> NewDocumentDialog<'a> {
NewDocumentResult { options, remember }
}),
requests: shown.requests,
presets: Vec::new(), // P3(dialogs-w14): dl.K39
}
}
}
@@ -571,13 +590,16 @@ pub struct HostedNewDocument {
options: DocumentOptions,
build: Box<Build>,
requests: HostRequests,
/// Whether the dialog is open: bound to the dialog's `opened` prop.
#[allow(dead_code)] // P3(dialogs-w14): dl.K39
open: bool,
}
impl HostedNewDocument {
/// A hosted dialog opening on `options`; `build` makes the dialog over them (the clipboard, the profiles, the
/// app's name).
pub fn new(options: DocumentOptions, build: impl for<'b> Fn(&'b mut DocumentOptions) -> NewDocumentDialog<'b> + Send + 'static) -> Self {
HostedNewDocument { id: dialog_id("new-document"), options, build: Box::new(build), requests: HostRequests::new() }
HostedNewDocument { id: dialog_id("new-document"), options, build: Box::new(build), requests: HostRequests::new(), open: true }
}
/// The settings the details column shows.
@@ -596,6 +618,30 @@ impl HostedNewDocument {
self.requests.answer_color(key, color);
}
/// Opens with `library` as the saved presets.
#[must_use]
pub fn saved(mut self, library: PresetLibrary<DocumentOptions>) -> Self {
let _ = (&mut self, library);
todo!("dl.K39")
}
/// Opens with `list` as the recent documents.
#[must_use]
pub fn recent(mut self, list: Vec<DocumentOptions>) -> Self {
let _ = (&mut self, list);
todo!("dl.K39")
}
/// The saved presets as the user left them.
pub fn saved_presets(&self) -> &PresetLibrary<DocumentOptions> {
todo!("dl.K39")
}
/// The saved-preset edits since the last call, for the app to store.
pub fn take_preset_events(&mut self) -> Vec<NamedPresetEvent<PresetId>> {
todo!("dl.K39")
}
/// The picker was cancelled: the request is dropped and Background Contents stays as it was.
pub fn cancel_color(&mut self) {
self.requests.cancel_color();
@@ -605,6 +651,20 @@ impl HostedNewDocument {
impl StackDialog for HostedNewDocument {
type Result = NewDocumentResult;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K39")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K39")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K39")
}
fn id(&self) -> DialogId {
self.id
}
@@ -5,12 +5,15 @@
mod parse;
use super::fields::{DialogFields, FieldValue};
use crate::patterns::blend_keys::BlendKeyEntry;
use crate::runtime::env::{Label, UnitKind};
use crate::runtime::requests::{ColorRequest, PathKind};
use crate::runtime::requests::{ColorRequest, EyedropperRequest, PathKind};
use crate::value_drag::SliderScale;
use craft_host::PickRequest;
use craft_theme::Srgba;
use egui::{Response, Ui};
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
/// What a parameter is and which control edits it. Defaults are the values a form opens with when nothing is
@@ -144,6 +147,30 @@ pub enum ParamKind {
},
/// A row the host draws: see [`Param::custom`]. It has no value of its own.
Custom(CustomRow),
/// A select of blend modes, each with the Shift+Alt key that picks it.
#[non_exhaustive]
Blend {
/// The modes: their key entries (id and shortcut) and labels.
modes: Vec<(BlendKeyEntry<String>, Label)>,
/// The id of the mode shown when nothing is remembered; the first mode when `None`.
default: Option<String>,
},
/// A pattern chosen from the dialog's pattern list (`ParamDialog::patterns`); its value is the pattern's id.
#[non_exhaustive]
Pattern {
/// The id of the pattern shown when nothing is remembered.
default: Option<String>,
},
/// A list of files or one folder (a `FileListPicker`); its value is a `{files, folder, useFolder}` object.
#[non_exhaustive]
Files {
/// Whether the list picks a folder.
folder_mode: bool,
/// The file dialog request Browse makes.
request: PickRequest,
/// The paths of the documents already open, which the list offers to add.
open_files: Vec<PathBuf>,
},
/// A section heading over the rows that follow it: see [`Param::section`]. It has no value.
Section,
}
@@ -214,6 +241,18 @@ impl ParamKind {
ParamKind::OptionalNumber { min, max, default, initial, decimals }
}
/// A select of blend `modes` with their keys; `default` is the id of the mode shown at first.
pub fn blend(modes: Vec<(BlendKeyEntry<String>, Label)>, default: Option<String>) -> Self {
let _ = (modes, default);
todo!("dl.K27")
}
/// A pattern chosen from the dialog's pattern list; `default` is the id shown at first.
pub fn pattern(default: Option<String>) -> Self {
let _ = default;
todo!("dl.K28")
}
/// Fields per row of a [`ParamKind::Grid`] of `cells`: `round(sqrt(cells))`, at least 1.
pub fn grid_side(cells: usize) -> usize {
((cells as f32).sqrt().round() as usize).max(1)
@@ -245,6 +284,9 @@ impl ParamKind {
ParamKind::Channel { default, .. } => FieldValue::Int(i64::try_from(*default).unwrap_or(0)),
ParamKind::Text { default } => FieldValue::Text(default.clone()),
ParamKind::OptionalNumber { default, .. } => FieldValue::Number((*default)?),
ParamKind::Blend { .. } => todo!("dl.K27"),
ParamKind::Pattern { .. } => todo!("dl.K28"),
ParamKind::Files { .. } => todo!("dl.K29"),
ParamKind::ReadOnlyText { .. } | ParamKind::Custom(_) | ParamKind::Section => return None,
})
}
@@ -273,6 +315,10 @@ impl ParamKind {
(ParamKind::Channel { names, .. }, FieldValue::Int(i)) => usize::try_from(*i).is_ok_and(|i| i < names.len()),
(ParamKind::Text { .. }, FieldValue::Text(_)) => true,
(ParamKind::OptionalNumber { min, max, .. }, v) => number(v).is_some_and(|n| n.is_finite() && n >= *min && n <= *max),
(ParamKind::Custom(_), FieldValue::Json(_)) => true,
(ParamKind::Blend { .. }, _) => todo!("dl.K27"),
(ParamKind::Pattern { .. }, _) => todo!("dl.K28"),
(ParamKind::Files { .. }, _) => todo!("dl.K29"),
_ => false,
}
}
@@ -316,12 +362,31 @@ pub struct CustomContext {
title: Label,
colors: DialogFields,
request: Option<ColorRequest>,
canvas: Option<egui::Id>,
}
impl CustomContext {
/// The context of a row labelled `title` over `colors`, the values at the start of the pass.
pub(crate) fn new(title: Label, colors: DialogFields) -> Self {
CustomContext { title, colors, request: None }
pub(crate) fn new(title: Label, colors: DialogFields, canvas: Option<egui::Id>) -> Self {
CustomContext { title, colors, request: None, canvas }
}
/// Arms the host's eyedropper for the colour under `request.key`, as a colour row's dropper toggle does.
pub fn arm_eyedropper(&mut self, request: EyedropperRequest) {
let _ = request;
todo!("dl.K30")
}
/// Whether the row's dropper samples now: `true` while the row wants canvas presses to pick colours.
pub fn sampling(&mut self, on: bool) {
let _ = on;
todo!("dl.K30")
}
/// The canvas the dialog's rows work on (`ParamDialog::canvas`), when it has one.
pub fn canvas(&self) -> Option<egui::Id> {
let _ = &self.canvas;
todo!("dl.K30")
}
/// Asks the host for its colour picker for the value under `key`, which needs no row of its own. The picker opens
@@ -373,6 +438,10 @@ pub(crate) struct RowOptions {
/// The lines a multi-line text row shows.
lines: Option<usize>,
units: Option<UnitChoices>,
/// The ids of the options a choice row shows disabled.
disabled_options: Vec<String>,
/// The row's select has a search field.
searchable: bool,
}
/// The units of a number row ([`Param::number_with_units`]).
@@ -432,6 +501,54 @@ impl Param {
}
}
/// A row of files or one folder: a [`ParamKind::Files`] list the user fills with Browse.
pub fn files(key: impl Into<String>, label: impl Into<Label>) -> Param {
let _ = (key.into(), label.into());
todo!("dl.K29")
}
/// Whether a [`Param::files`] row picks one folder instead of files.
#[must_use]
pub fn folder_mode(self, on: bool) -> Self {
let _ = on;
todo!("dl.K29")
}
/// The paths of the documents already open, which a [`Param::files`] row offers to add.
#[must_use]
pub fn open_files(self, paths: Vec<PathBuf>) -> Self {
let _ = paths;
todo!("dl.K29")
}
/// Shows the options `ids` of a choice row disabled.
#[must_use]
pub fn disabled_options(mut self, ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
let _ = ids.into_iter().map(Into::into).collect::<Vec<String>>();
let _ = &mut self;
todo!("cw.C39")
}
/// Whether the option `id` of a choice row takes a pick.
pub fn option_enabled(&self, id: &str) -> bool {
let _ = id;
todo!("cw.C39")
}
/// Gives a choice row's select a search field.
#[must_use]
pub fn searchable(mut self) -> Self {
let _ = &mut self;
todo!("pn.C51")
}
/// The row takes input only while `fields[key]` equals one of `values`; otherwise it is shown disabled.
#[must_use]
pub fn enabled_when_in(self, key: impl Into<String>, values: impl IntoIterator<Item = impl Into<FieldValue>>) -> Self {
let _ = (key.into(), values.into_iter().map(Into::into).collect::<Vec<FieldValue>>());
todo!("dl.K79")
}
/// A bare number row: a [`ParamKind::Number`] open on both sides. Bound it with [`Param::bounds`].
pub fn number(key: impl Into<String>, label: impl Into<Label>, default: f64, step: f64, decimals: u32) -> Self {
Self::new(key, label, ParamKind::number(None, None, default, step, decimals))
@@ -206,6 +206,9 @@ pub struct PreviewOutput {
/// texture's size is its pixel size) from its top-left corner; `None` when there was no click or it missed the
/// picture. It is reported whether or not the click centres the view: an eyedropper or a locator reads it.
pub clicked: Option<Pos2>,
/// The point of the picture a press landed on this pass, in the same units as `clicked`; unlike `clicked` it is
/// reported when the press begins, not when it ends as a click.
pub pressed: Option<Pos2>,
}
impl Outcome for PreviewOutput {
@@ -561,7 +564,14 @@ impl Component for PreviewPane<'_> {
fn finish(self, cx: Cx<'_, Self>) -> PreviewOutput {
let shown = PreviewView { transform: self.shown(cx.rect.size()), ..self.view.clone() };
PreviewOutput { response: cx.response.clone(), view: self.moved, shown, double_clicked: self.double_clicked, clicked: self.clicked }
PreviewOutput {
response: cx.response.clone(),
view: self.moved,
shown,
double_clicked: self.double_clicked,
clicked: self.clicked,
pressed: None, // P3(dialogs-w9): dl.K75
}
}
}
@@ -88,6 +88,13 @@ impl<'a> ReportDialog<'a> {
ReportDialog { title: title.into(), summary: summary.into(), notes, open: None }
}
/// Plain `lines` shown as the notes, in place of ones built with [`ReportNote`].
#[must_use]
pub fn lines(mut self, lines: Vec<Label>) -> Self {
let _ = (&mut self, lines);
todo!("dl.K12")
}
/// The notes as the Copy button hands them back, one per line with the tone's word first.
pub fn as_text(&self, env: &Env) -> String {
let words = env.words::<ReportWords>();
@@ -141,5 +148,49 @@ impl<'a> ReportDialog<'a> {
}
}
/// A [`ReportDialog`] the [`DialogHost`](crate::dialog::DialogHost) owns: a title, a summary and plain lines. The text
/// of the Copy button waits in [`take_copied`](HostedReport::take_copied) until the app puts it on the clipboard.
pub struct HostedReport {
id: crate::dialog::DialogId,
title: Label,
summary: Label,
lines: Vec<String>,
copied: Option<String>,
}
impl HostedReport {
/// A report titled `title` with one `summary` line and the `lines`.
pub fn new(title: impl Into<Label>, summary: impl Into<Label>, lines: Vec<String>) -> Self {
HostedReport { id: crate::dialog::dialog_id("report"), title: title.into(), summary: summary.into(), lines, copied: None }
}
/// The text the Copy button copied since the last call, once. The app puts it on the clipboard.
pub fn take_copied(&mut self) -> Option<String> {
self.copied.take()
}
}
impl crate::dialog::StackDialog for HostedReport {
type Result = ();
fn id(&self) -> crate::dialog::DialogId {
self.id
}
fn show(&mut self, ui: &mut Ui, stack: &crate::dialog::DialogStack) -> Option<crate::dialog::DialogResult<()>> {
let _ = (ui, stack, &self.title, &self.summary, &self.lines);
todo!("dl.K12")
}
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K12")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K12")
}
}
/// The position of the Copy button among the footer buttons.
const COPY: usize = 1;
@@ -1,7 +1,8 @@
//! `ParamRows`: a form with one `Field` per visible parameter of a [`Param`] list, over a [`DialogFields`] value.
use super::fields::{DialogFields, FieldValue};
use crate::runtime::requests::{ColorRequest, EyedropperRequest, PathRequest};
use crate::patterns::presets::PresetRow;
use crate::runtime::requests::{ColorRequest, EyedropperRequest, ListingRequest, PathRequest};
use super::param::{CustomContext, Param, ParamKind, fill_defaults, rounded};
use super::path_row::PathRow;
@@ -66,6 +67,8 @@ pub struct ParamRowsOutput {
/// The eyedropper toggle turned on this pass: the host answers with the colour the sampler picks for the request's
/// key. While a toggle is on the rows arm the sampler for `ParamRows::canvas`; turning it off files nothing.
pub eyedropper: Option<EyedropperRequest>,
/// The folder a files row asked the host to list this pass; the host answers with `HostAnswer::Listing`.
pub listing: Option<ListingRequest>,
}
impl Outcome for ParamRowsOutput {
@@ -119,6 +122,12 @@ impl<'a> ParamRows<'a> {
self
}
/// The patterns a [`ParamKind::Pattern`] row offers, by id.
pub fn patterns(mut self, rows: &'a [PresetRow<String>]) -> Self {
let _ = (&mut self, rows);
todo!("dl.K31")
}
/// Whether the rows only show their values.
pub fn read_only(mut self, on: bool) -> Self {
self.read_only = on;
@@ -167,7 +176,7 @@ impl<'a> ParamRows<'a> {
};
let shown = if read_only { with_env(ui, |scope| scope.read_only = Some(true), group) } else { group(ui) };
let (pick_color, path, eyedropper) = if read_only { Default::default() } else { (pass.color, pass.path, pass.eyedropper) };
ParamRowsOutput { response: shown.output, changed, values, pick_color, path, eyedropper }
ParamRowsOutput { response: shown.output, changed, values, pick_color, path, eyedropper, listing: None }
}
}
@@ -301,6 +310,7 @@ impl<'p> Pass<'p> {
ParamKind::OptionalNumber { min, max, initial, decimals, .. } => self.optional(ui, &line, *min..=*max, *initial, *decimals),
ParamKind::ReadOnlyText { text } => read_only_text(ui, &line, text),
ParamKind::Custom(_) => self.custom(ui, &line),
ParamKind::Blend { .. } | ParamKind::Pattern { .. } | ParamKind::Files { .. } => todo!("dl.K31"),
ParamKind::Section => {}
}
}
@@ -615,7 +625,7 @@ impl<'p> Pass<'p> {
fn custom(&mut self, ui: &mut Ui, line: &Line<'_>) {
let ParamKind::Custom(row) = &line.param.kind else { return };
let mut context = CustomContext::new(line.name.clone(), self.work.clone());
let mut context = CustomContext::new(line.name.clone(), self.work.clone(), None); // P3(dialogs-w2): dl.K30, the rows' canvas
line.show_body(ui, |ui| {
let _ = row.draw(ui, &mut self.work, &mut context);
});
@@ -44,12 +44,16 @@ mod model;
pub use hosted::HostedSaveForWeb;
pub use model::{
Animation, ColorTable, Dither, SaveForWebOptions, SaveForWebResult, WantedVariant, WebFormat, WebMetadata, WebPreset, WebVariant, WebView,
Animation, ColorTable, Dither, SaveForWebOptions, SaveForWebResult, WantedVariant, WebFormat, WebMetadata, WebPreset, WebSlice, WebSlices,
WebVariant, WebView,
};
/// The key of the matte colour request the dialog files.
pub const MATTE_COLOR_KEY: &str = "web.matte";
/// The key of the colour request the dialog files for an edited palette entry.
pub const PALETTE_COLOR_KEY: &str = "web.palette";
/// The key of the path request Save… files.
pub const SAVE_PATH_KEY: &str = "web.save";
@@ -324,6 +328,9 @@ pub struct SaveForWebDialog<'a> {
/// The host's answers to earlier requests: the matte colour and the path of the file to write.
#[prop]
answers: Vec<HostAnswer>,
/// The document's slices, for the Slices choice.
#[prop]
slices: &'a [WebSlice],
}
impl<'a> SaveForWebDialog<'a> {
@@ -340,12 +347,14 @@ impl<'a> SaveForWebDialog<'a> {
remember: None,
saving: false,
answers: Vec::new(),
slices: &[],
}
}
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> SaveForWebOutput {
let SaveForWebDialog { name, size, pictures, options, open, presets, animation, remember, saving, answers } = self;
let SaveForWebDialog { name, size, pictures, options, open, presets, animation, remember, saving, answers, slices } = self;
let _ = slices; // P3(dialogs-w15): dl.K43
let env = Env::of(ui);
let words = env.words::<SaveForWebWords>();
let sizing = env.words::<SizingWords>();
@@ -38,9 +38,19 @@ pub struct HostedSaveForWeb {
frame: u32,
requests: HostRequests,
saving: bool,
/// Whether the dialog is open: bound to the dialog's `opened` prop.
#[allow(dead_code)] // P3(dialogs-w15): dl.K43
open: bool,
}
impl HostedSaveForWeb {
/// The document's slices, for the Slices choice.
#[must_use]
pub fn slices(mut self, slices: Vec<super::WebSlice>) -> Self {
let _ = (&mut self, slices);
todo!("dl.K43")
}
/// A hosted dialog for the document `name` of `size` pixels showing `original` in the Original pane.
pub fn new(name: impl Into<String>, size: PixelSize, original: SizedTexture) -> Self {
HostedSaveForWeb {
@@ -57,6 +67,7 @@ impl HostedSaveForWeb {
frame: 0,
requests: HostRequests::new(),
saving: false,
open: true,
}
}
@@ -138,6 +149,20 @@ impl HostedSaveForWeb {
impl StackDialog for HostedSaveForWeb {
type Result = SaveForWebResult;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K43")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K43")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K43")
}
fn id(&self) -> DialogId {
self.id
}
@@ -8,9 +8,10 @@ use crate::patterns::form_dialogs::host_requests::PreviewRequest;
use crate::patterns::form_dialogs::sizing::Resample;
use crate::runtime::env::Label;
use crate::runtime::memory::{MemoryStage, SaveKey, unique};
use egui::Ui;
use egui::Context;
use egui::load::SizedTexture;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;
/// The formats of Save for Web.
@@ -179,6 +180,32 @@ pub struct SaveForWebOptions {
pub percent: f64,
/// 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.
#[serde(default)]
pub palette_edits: BTreeMap<u16, [u8; 3]>,
/// Which slices of the document the file holds.
#[serde(default)]
pub slices: WebSlices,
}
/// Which slices of the document Save for Web writes.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum WebSlices {
/// The whole image as one file.
#[default]
All,
/// The slices with these numbers.
Selected(Vec<u32>),
}
/// A slice of the document: its number and its rectangle in document pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WebSlice {
/// The slice's number.
pub number: u32,
/// The slice's rectangle in document pixels.
pub rect: egui::Rect,
}
impl Default for SaveForWebOptions {
@@ -204,6 +231,8 @@ impl Default for SaveForWebOptions {
metadata: WebMetadata::Copyright,
percent: 100.0,
resample: Resample::Bicubic,
palette_edits: BTreeMap::new(),
slices: WebSlices::All,
}
}
}
@@ -263,17 +292,19 @@ pub struct WebVariant {
pub colors: Option<u16>,
/// The texture is a reduced proxy (the long side is capped at 2048 px).
pub proxy: bool,
/// The palette the encode used, as red, green and blue, when it is an indexed format.
pub palette: Option<Vec<[u8; 3]>>,
}
impl WebVariant {
/// The encoded pane `index` of `revision`, shown from `texture`.
pub fn new(index: usize, revision: u64, texture: SizedTexture, bytes: u64) -> Self {
WebVariant { index, revision, picture: Ok(texture), bytes, colors: None, proxy: false }
WebVariant { index, revision, picture: Ok(texture), bytes, colors: None, proxy: false, palette: None }
}
/// The pane `index` of `revision` whose encode failed with `message`.
pub fn failed(index: usize, revision: u64, message: impl Into<Label>) -> Self {
WebVariant { index, revision, picture: Err(message.into()), bytes: 0, colors: None, proxy: false }
WebVariant { index, revision, picture: Err(message.into()), bytes: 0, colors: None, proxy: false, palette: None }
}
/// The palette size of an indexed format.
@@ -283,6 +314,13 @@ impl WebVariant {
self
}
/// The palette the encode used.
#[must_use]
pub fn palette(mut self, palette: Vec<[u8; 3]>) -> Self {
self.palette = Some(palette);
self
}
/// Marks the texture as a reduced proxy.
#[must_use]
pub fn proxy(mut self, proxy: bool) -> Self {
@@ -320,9 +358,9 @@ impl SaveForWebResult {
/// Stores the settings and the view for the next open of a dialog built with
/// [`SaveForWebDialog::remember`]. The app calls it after the file is written; without a remember key it does
/// nothing.
pub fn remember(&self, ui: &Ui) {
pub fn remember(&self, ctx: &Context) {
if let Some((key, last)) = &self.remember {
let mut stage = MemoryStage::open(ui.ctx(), unique(("craft_ui::save_for_web_result", key.as_str())));
let mut stage = MemoryStage::open(ctx, unique(("craft_ui::save_for_web_result", key.as_str())));
*stage.saved::<Option<Last>>(key) = Some(last.clone());
stage.write_back();
}
@@ -2,7 +2,7 @@
//! Canvas Size, and the two size rules of the export dialogs. It reads no egui and draws nothing; the dialogs show
//! `LinkedSize` through `UnitSelect` rows, one per field.
use crate::runtime::env::UnitKind;
use crate::runtime::env::{ColumnSize, UnitKind};
use craft_behavior::PixelSize;
use std::ops::RangeInclusive;
@@ -138,6 +138,24 @@ pub struct LinkedSize {
}
impl LinkedSize {
/// Sets the width of the column of the rows' fields.
#[must_use]
pub fn column_size(mut self, size: ColumnSize) -> Self {
let _ = (&mut self, size);
todo!("dl.K37")
}
/// The unit the width is shown in.
pub fn width_unit(&self) -> UnitKind {
todo!("dl.K37")
}
/// Shows the width in `unit`; `false` when the size has no such unit.
pub fn set_width_unit(&mut self, unit: UnitKind) -> bool {
let _ = unit;
todo!("dl.K37")
}
/// Fields for a document of size `original` at 72 ppi, in pixels and pixels per inch, locked, resampling and
/// absolute, with the chain drawn.
pub fn new(original: PixelSize) -> Self {
@@ -6,7 +6,7 @@ use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use crate::form::Field;
use crate::pickers::{Anchor9, ReferencePoint, Select};
use crate::runtime::env::UnitKind;
use crate::runtime::env::{ColumnSize, UnitKind};
use craft_behavior::PixelSize;
use egui::Ui;
@@ -40,6 +40,13 @@ pub struct CanvasSizeValues {
}
impl CanvasSizeValues {
/// Sets the width of the column of the rows' fields, so the dialog lines up with its siblings.
#[must_use]
pub fn column_size(mut self, size: ColumnSize) -> Self {
let _ = (&mut self, size);
todo!("dl.K37")
}
/// The values for a canvas of `size` pixels, at 72 pixels per inch, in pixels, anchored at the centre and filling
/// with the background colour.
pub fn new(size: PixelSize) -> Self {
@@ -245,6 +252,20 @@ const KEY: &str = "sizing.canvasSize";
impl StackDialog for HostedCanvasSize {
type Result = CanvasSizeResult;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K36")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K36")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K36")
}
fn id(&self) -> DialogId {
self.id
}
@@ -6,7 +6,7 @@ use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use crate::form::Field;
use crate::pickers::Select;
use crate::runtime::env::UnitKind;
use crate::runtime::env::{ColumnSize, UnitKind};
use craft_behavior::PixelSize;
use egui::Ui;
@@ -26,6 +26,8 @@ pub struct ImageSizeResult {
pub resample: Option<Resample>,
/// Whether layer effects scale with the image.
pub scale_styles: bool,
/// Whether the resolution was edited, so the app resamples at the new resolution.
pub resolution_changed: bool,
}
/// What Image Size reports: its response, how it closed and the [`ImageSizeResult`] at OK.
@@ -41,6 +43,13 @@ pub struct ImageSizeValues {
}
impl ImageSizeValues {
/// Sets the width of the column of the rows' fields, so the dialog lines up with its siblings.
#[must_use]
pub fn column_size(mut self, size: ColumnSize) -> Self {
let _ = (&mut self, size);
todo!("dl.K37")
}
/// The values for a document of `size` pixels, at 72 pixels per inch, in pixels, resampling automatically with
/// Scale Styles on.
pub fn new(size: PixelSize) -> Self {
@@ -198,6 +207,7 @@ impl<'a> ImageSize<'a> {
resolution_unit: state.size.resolution_unit(),
resample: state.size.is_resampling().then_some(state.method),
scale_styles: state.scale_styles,
resolution_changed: false, // P3(dialogs-w13): dl.K36
},
)
}
@@ -249,6 +259,20 @@ const KEY: &str = "sizing.imageSize";
impl StackDialog for HostedImageSize {
type Result = ImageSizeResult;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K36")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K36")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K36")
}
fn id(&self) -> DialogId {
self.id
}
+1
View File
@@ -1,5 +1,6 @@
//! `Inspector`, `CommandPalette`, `PreferencesWindow`, `DockArea`, `DockPanels`, `PanelSpec` and the other patterns.
pub mod blend_keys;
pub mod dock;
pub mod form_dialogs;
pub mod panels;
@@ -0,0 +1,184 @@
//! `HistoryPanel`: the undo history as a list of states and named snapshots, with a footer of snapshot buttons.
use crate::contract::{NoValue, Outcome, Pattern};
use crate::primitives::textures::{ThumbSource, Thumbnails};
use crate::runtime::env::Label;
use craft_behavior::IconId;
use craft_keymap::Mods;
use egui::{Response, Ui};
/// What a history row stands for: a named snapshot or a state of the undo stack, by number.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HistoryKey {
/// The snapshot with this number.
Snapshot(u64),
/// The state with this number.
State(u64),
}
/// One row of the history list.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct HistoryRow {
/// What the row stands for.
pub key: HistoryKey,
/// The row's name.
pub label: Label,
/// The icon before the name.
pub icon: Option<IconId>,
/// The state is one that was undone and can be redone.
pub redo: bool,
}
impl HistoryRow {
/// A row for the snapshot `id` named `label`.
pub fn snapshot(id: u64, label: impl Into<Label>) -> Self {
let _ = (id, label.into());
todo!("pn.C34")
}
/// A row for the state `id` named `label`.
pub fn state(id: u64, label: impl Into<Label>) -> Self {
let _ = (id, label.into());
todo!("pn.C34")
}
/// Shows `icon` before the name.
#[must_use]
pub fn icon(mut self, icon: IconId) -> Self {
let _ = (&mut self, icon);
todo!("pn.C34")
}
/// Marks the state as one that can be redone.
#[must_use]
pub fn redo(mut self, redo: bool) -> Self {
let _ = (&mut self, redo);
todo!("pn.C34")
}
}
/// Which buttons the history footer shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct HistoryFooter {
/// The Delete button.
pub delete: bool,
/// The New Snapshot button.
pub new_snapshot: bool,
/// The New Document button.
pub new_document: bool,
}
/// What the user did in the history panel.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum HistoryEvent {
/// The user picked a row: the document goes to it.
Select(HistoryKey),
/// The user set the row as the source of the history brush.
SetSource(HistoryKey),
/// The user renamed a snapshot.
Rename {
/// The snapshot's number.
snapshot: u64,
/// The new name.
text: String,
},
/// The user deleted the row, or the picked one when `None`.
Delete(Option<HistoryKey>),
/// The user asked for a new snapshot; `mods` were held.
NewSnapshot {
/// The modifiers held with the press.
mods: Mods,
},
/// The user asked for a new document from the picked row.
NewDocument,
}
/// What [`HistoryPanel`] reports.
pub struct HistoryPanelOutput {
/// The panel's response.
pub response: Response,
/// What the user did this pass, in order.
pub events: Vec<HistoryEvent>,
}
impl Outcome for HistoryPanelOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// The history panel: `rows` with the `current` one marked, thumbnails of the snapshots and a footer of buttons.
#[must_use = "show the panel with `show`"]
#[derive(Pattern)]
#[allow(dead_code)] // P3(panels-w8): pn.C34
pub struct HistoryPanel<'a> {
rows: &'a [HistoryRow],
current: Option<HistoryKey>,
}
impl<'a> HistoryPanel<'a> {
/// A panel over `rows`, with `current` marked.
pub fn new(rows: &'a [HistoryRow], current: Option<HistoryKey>) -> Self {
let _ = (rows, current);
todo!("pn.C34")
}
/// Marks the row that is the source of the history brush.
#[must_use]
pub fn source(mut self, source: Option<HistoryKey>) -> Self {
let _ = (&mut self, source);
todo!("pn.C34")
}
/// Shows the pictures of the rows from `source`.
#[must_use]
pub fn thumbnails(mut self, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64>) -> Self {
let _ = (&mut self, thumbnails, source);
todo!("pn.C34")
}
/// Which rows the Delete button and key take; the others refuse.
#[must_use]
pub fn can_delete(mut self, can: impl Fn(&HistoryKey) -> bool + 'a) -> Self {
let _ = (&mut self, can);
todo!("pn.C34")
}
/// Which footer buttons show.
#[must_use]
pub fn footer(mut self, footer: HistoryFooter) -> Self {
let _ = (&mut self, footer);
todo!("pn.C34")
}
/// Scrolls to `key` and shows it.
#[must_use]
pub fn reveal(mut self, key: HistoryKey) -> Self {
let _ = (&mut self, key);
todo!("pn.C34")
}
/// Opens the rename field of the snapshot `snapshot`.
#[must_use]
pub fn start_rename(mut self, snapshot: u64) -> Self {
let _ = (&mut self, snapshot);
todo!("pn.C34")
}
/// Whether the panel takes input.
#[must_use]
pub fn enabled(mut self, enabled: bool) -> Self {
let _ = (&mut self, enabled);
todo!("pn.C34")
}
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> HistoryPanelOutput {
let _ = ui;
todo!("pn.C34")
}
}
@@ -7,6 +7,13 @@ mod inspector;
pub use inspector::Inspector;
// History and modifier keys.
mod history;
mod modifier_keys;
pub use history::{HistoryEvent, HistoryFooter, HistoryKey, HistoryPanel, HistoryPanelOutput, HistoryRow};
pub use modifier_keys::ModifierKeysPanel;
// CommandPalette and Tour.
mod palette;
mod tour;
@@ -0,0 +1,26 @@
//! `ModifierKeysPanel`: on-screen toggles for the modifier keys, for a touch screen without a keyboard.
use crate::contract::{Bind, Pattern};
use craft_keymap::Mods;
use egui::{Response, Ui};
/// A panel of latching modifier-key toggles: a press on one holds that modifier for the next click or key.
#[must_use = "show the panel with `show`"]
#[derive(Pattern)]
pub struct ModifierKeysPanel<'a> {
latched: Bind<'a, Mods>,
}
impl<'a> ModifierKeysPanel<'a> {
/// A panel over the latched modifiers in `latched`.
pub fn new(latched: Bind<'a, Mods>) -> Self {
let _ = latched;
todo!("tp.T16")
}
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> Response {
let _ = (ui, &self.latched);
todo!("tp.T16")
}
}
@@ -237,4 +237,17 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
pub fn take_applied(&mut self) -> Option<T> {
self.applied.take()
}
/// The settings Apply or OK changed, once, as `(key, value)` pairs in the file's table: a `None` value removes the
/// key. The app writes just these edits into the settings file, so another instance's edits to other keys stay.
pub fn take_applied_edits(&mut self) -> Option<Vec<(String, Option<toml::Value>)>> {
todo!("tp.T18")
}
/// Takes `saved` as the new base the draft is compared with, as `reload` does, but keeps the edits the user has made
/// in the window on top of it. `Err` leaves the document as it was.
pub fn rebase(&mut self, saved: T) -> Result<(), toml::ser::Error> {
let _ = saved;
todo!("tp.T19")
}
}
@@ -258,6 +258,9 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// this many tiles. 0 asks for none.
#[prop]
columns: u16,
/// What the browser shows when `rows` is empty, in place of the default words.
#[prop(into)]
empty: Option<Label>,
}
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'a, K> {
@@ -290,6 +293,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'a, K> {
max_rows: None,
room_height: None,
columns: 0,
empty: None,
}
}
@@ -570,7 +574,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
max_rows,
room_height,
columns,
empty: empty_text,
} = self;
let _ = &empty_text; // P3(panels-w12): pn.C50
let env = Env::of(ui);
let words = env.words::<PresetWords>();
let list_id = rows_id(browser_id.unwrap_or_else(|| ui.scope_id()));
@@ -0,0 +1,138 @@
//! `PresetManager`: a dialog body for managing the presets of several kinds: a kind select over the presets of that
//! kind, with rename and delete, and the host's own action buttons.
use super::event::PresetEvent;
use super::model::PresetRow;
use crate::contract::{Bind, Entry, NoValue, Outcome, Pattern, Props};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use crate::list::RowTest;
use crate::runtime::env::Label;
use crate::runtime::overlay::CloseReason;
use craft_behavior::Value;
use egui::{Response, Ui};
use std::hash::Hash;
/// What a [`PresetManager`] took from the user in a pass.
#[derive(Debug)]
#[non_exhaustive]
pub struct PresetManagerTaken<G, K> {
/// The kind the user picked in this pass.
pub kind: Option<G>,
/// The renames, deletes and picks of the rows, in order.
pub events: Vec<PresetEvent<K>>,
/// The indices of the action buttons pressed, in order.
pub actions: Vec<usize>,
}
/// What a [`PresetManager`] reports.
pub struct PresetManagerOutput<G, K> {
/// The manager's response.
pub response: Response,
/// How the manager closed in this pass; `None` while it stays open.
pub closed: Option<CloseReason>,
/// What the user did this pass.
pub taken: PresetManagerTaken<G, K>,
}
impl<G, K> Outcome for PresetManagerOutput<G, K> {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// The preset manager: a select of preset `kinds` over the list of the picked kind's `rows`, with Rename and Delete
/// on each row and buttons for the host's own `actions` (Load, Save, Reset).
#[must_use = "show the manager with `show`"]
#[derive(Pattern, Props)]
#[pattern(probe(PresetManager<'static, u32, u32>))]
pub struct PresetManager<'a, G: Value, K: Clone + Eq + Hash + Send + Sync + 'static> {
title: Label,
kinds: &'a [Entry<G>],
kind: Bind<'a, G>,
rows: &'a [PresetRow<K>],
/// The host's buttons: a label and a tooltip each.
#[prop]
actions: Vec<(Label, Option<Label>)>,
/// Which presets Rename applies to.
#[prop(func = "Fn(&K) -> bool")]
can_rename: Option<RowTest<'a, K>>,
/// Which presets Delete applies to.
#[prop(func = "Fn(&K) -> bool")]
can_delete: Option<RowTest<'a, K>>,
/// What the list shows when `rows` is empty.
#[prop(into)]
empty: Option<Label>,
}
impl<'a, G: Value, K: Clone + Eq + Hash + Send + Sync + 'static> PresetManager<'a, G, K> {
/// A manager titled `title` over the preset `kinds`, with `kind` the picked one and `rows` its presets.
pub fn new(title: impl Into<Label>, kinds: &'a [Entry<G>], kind: Bind<'a, G>, rows: &'a [PresetRow<K>]) -> Self {
let _ = (title.into(), kinds, kind, rows);
todo!("tp.T34")
}
/// Shows the manager.
pub fn show(self, ui: &mut Ui) -> PresetManagerOutput<G, K> {
let _ = (ui, &self.title, self.kinds, &self.kind, self.rows);
todo!("tp.T34")
}
}
/// A [`PresetManager`] the [`DialogHost`](crate::dialog::DialogHost) owns. The app reads what the user did with
/// [`take`](HostedPresetManager::take).
pub struct HostedPresetManager<G, K> {
id: DialogId,
title: Label,
kinds: Vec<Entry<G>>,
kind: G,
rows: Vec<PresetRow<K>>,
taken: PresetManagerTaken<G, K>,
}
impl<G: Value, K: Clone + Eq + Hash + Send + Sync + 'static> HostedPresetManager<G, K> {
/// A hosted manager titled `title` over the preset `kinds`, opening on `kind`.
pub fn new(title: impl Into<Label>, kinds: Vec<Entry<G>>, kind: G) -> Self {
let _ = (dialog_id("preset-manager"), title.into(), kinds, kind);
todo!("tp.T34")
}
/// Sets the presets of the picked kind.
pub fn rows(&mut self, rows: Vec<PresetRow<K>>) {
let _ = rows;
todo!("tp.T34")
}
/// The kind the manager shows.
pub fn kind(&self) -> &G {
&self.kind
}
/// What the user did since the last call.
pub fn take(&mut self) -> PresetManagerTaken<G, K> {
todo!("tp.T34")
}
}
impl<G: Value + Send + 'static, K: Clone + Eq + Hash + Send + Sync + 'static> StackDialog for HostedPresetManager<G, K> {
type Result = ();
fn id(&self) -> DialogId {
self.id
}
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<()>> {
let _ = (ui, stack, &self.title, &self.kinds, &self.rows, &self.taken);
todo!("tp.T34")
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("tp.T34")
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("tp.T34")
}
}
@@ -14,6 +14,7 @@ mod panel_menu;
mod state;
// The picker and the named row.
mod manager;
mod named;
mod picker;
@@ -21,6 +22,7 @@ pub use browser::{BrowserTools, PresetBrowser, PresetItemCommands, PresetReorder
pub use event::{PresetEvent, PresetOutput};
pub use files::{PresetExport, PresetFileEvent, PresetFileFailure, PresetFileRequest, PresetFiles};
pub use footer::{PresetFooter, PresetFooterEvent, PresetFooterOptions, PresetFooterOutput};
pub use manager::{HostedPresetManager, PresetManager, PresetManagerOutput, PresetManagerTaken};
pub use model::{
CellShape, GroupPath, PresetChange, PresetError, PresetGroup, PresetId, PresetItem, PresetKey, PresetKind, PresetLibrary, PresetRow, Preview,
PreviewPaint, ThumbInfo, children_end, has_captions, nest_allowed,
@@ -229,6 +229,12 @@ struct Session {
}
impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
/// A picker of patterns, built as [`new`](PresetPicker::new) is: the face shows the picked pattern's tile.
pub fn pattern(label: impl Into<Label>, value: Bind<'a, Option<K>>, rows: &'a [PresetRow<K>], state: Bind<'a, PresetState<K>>) -> Self {
let _ = (label.into(), value, rows, state);
todo!("dl.K35")
}
/// A picker named `label` over `value`, choosing among the presets of `rows`.
pub fn new(label: impl Into<Label>, value: Bind<'a, Option<K>>, rows: &'a [PresetRow<K>], state: Bind<'a, PresetState<K>>) -> Self {
PresetPicker {
@@ -1,6 +1,6 @@
//! About's Contributors tab: the grab bag of name links and the Table view.
use craft_ui::contract::Role;
use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::form_dialogs::{AboutDialog, AboutInfo, AboutTab, Contributor, Credits};
use craft_ui::testing::{Fixture, trial};
use egui::Vec2;
@@ -25,7 +25,7 @@ fn a_click_on_a_name_in_the_grab_bag_reports_its_profile() {
let links = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&links);
let mut fixture = Fixture::new(move |ui| {
let shown = AboutDialog::new(&INFO, &CREDITS).tab(AboutTab::Contributors).show(ui);
let shown = AboutDialog::new(&INFO, &CREDITS).tab(Bind::given(AboutTab::Contributors)).show(ui); // P3(dialogs-w4): dl.K11
seen.borrow_mut().extend(shown.link);
});
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
+8 -5
View File
@@ -91,6 +91,9 @@ pub struct ShellRegion {
#[container]
props: ContainerProps,
shell: Option<ShellCx>,
/// Whether the region senses a press on its own surface, where no child or part takes it (`Sense::SURFACE`).
#[prop(flag)]
senses_surface: bool,
}
impl ShellRegion {
@@ -99,7 +102,7 @@ impl ShellRegion {
/// window's clear colour.
pub fn window() -> Self {
let props = ContainerProps::new().mount(Mount::window(Resize::GRIPS)).command_scope(ScreenModeCommands::SCOPE);
ShellRegion { common: Common::new(), props, shell: None }
ShellRegion { common: Common::new(), props, shell: None, senses_surface: false }
}
/// The content of a shell shown inside a region of another window: it fills its room, answers the screen-mode
@@ -107,19 +110,19 @@ impl ShellRegion {
pub fn embedded() -> Self {
let props =
ContainerProps::new().sizing(crate::contract::Sizing::Fill).surface(SurfaceKind::Background).command_scope(ScreenModeCommands::SCOPE);
ShellRegion { common: Common::new(), props, shell: None }
ShellRegion { common: Common::new(), props, shell: None, senses_surface: false }
}
/// An inline region that fills its room and sets `shell` for everything inside it.
pub fn scope(shell: ShellCx) -> Self {
let props = ContainerProps::new().sizing(crate::contract::Sizing::Fill).command_scope(crate::runtime::commands::CommandScope::APP);
ShellRegion { common: Common::new(), props, shell: Some(shell) }
ShellRegion { common: Common::new(), props, shell: Some(shell), senses_surface: false }
}
/// A pane of the window; it fills the room its edge gives it.
pub fn pane(pane: ShellPane) -> Self {
let props = ContainerProps::new().mount(Mount::Pane(pane)).focus(FocusPolicy::PANE);
ShellRegion { common: Common::new(), props, shell: None }
ShellRegion { common: Common::new(), props, shell: None, senses_surface: false }
}
}
@@ -136,7 +139,7 @@ impl Component for ShellRegion {
}
fn sense(&self) -> Sense {
Sense::empty()
if self.senses_surface { Sense::SURFACE } else { Sense::empty() }
}
fn content_env(&self, _: &Cx<'_, Self>, values: &mut AppValues) {
+16 -2
View File
@@ -70,6 +70,10 @@ macro_rules! layout_component {
indent: u8,
/// Whether the root senses the pointer over it.
hover: bool,
/// Whether the container senses a press on its own surface, where no child or part takes it
/// (`Sense::SURFACE`).
#[prop(flag)]
senses_surface: bool,
$($($field: $ty,)*)?
}
@@ -161,7 +165,9 @@ macro_rules! layout_component {
}
fn sense(&self) -> Sense {
if self.hover { Sense::HOVER } else { Sense::empty() }
let mut sense = if self.hover { Sense::HOVER } else { Sense::empty() };
sense.set(Sense::SURFACE, self.senses_surface);
sense
}
/// A labelled body is a group named by its label, so a named region of a panel reaches assistive tech. A
@@ -211,6 +217,7 @@ impl<'a> Stack<'a> {
props: ContainerProps::new().sizing(Sizing::Content).layout(BodyLayout::stack()),
indent: 0,
hover: false,
senses_surface: false,
header: None,
footer: None,
}
@@ -274,7 +281,13 @@ impl Default for Stack<'_> {
impl Row {
/// A row that takes the size of its children.
pub fn new() -> Self {
Row { common: Common::new(), props: ContainerProps::new().sizing(Sizing::Content).layout(BodyLayout::row()), indent: 0, hover: false }
Row {
common: Common::new(),
props: ContainerProps::new().sizing(Sizing::Content).layout(BodyLayout::row()),
indent: 0,
hover: false,
senses_surface: false,
}
}
/// Whether children continue on a new line.
@@ -304,6 +317,7 @@ impl Grid {
props: ContainerProps::new().sizing(Sizing::Content).layout(BodyLayout::grid(columns)),
indent: 0,
hover: false,
senses_surface: false,
}
}
}