mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 00:34:25 +00:00
dialogs-w2: net change of 3 commits
- dialogs-w2: written by an agent - Integration: ParamRows keeps dialogs-w1's preview_colors beside the patterns rows (dialogs-w1 7a195af4a) - dialogs-w2: review fixes (review-1)
This commit is contained in:
@@ -7,10 +7,8 @@ is any `raw-window-handle` 0.6 window, and the app passes a closure that wakes i
|
||||
|
||||
## egui parts (feature `ui`)
|
||||
|
||||
`craft_dialogs::ui` holds the egui widgets over `host.files()`: `PathField` (a path text field with a
|
||||
Browse button) and `FileListPicker` with `FileList` (Photoshop's Load Files into Stack list:
|
||||
Files or Folder mode, Browse…, Remove, Add Open Files, Sort By Name; a 300 × 160 list box and
|
||||
120-wide buttons from the `file_list.*` tokens).
|
||||
`craft_dialogs::ui` holds the egui widget over `host.files()`: `PathField` (a path text field with a
|
||||
Browse button).
|
||||
|
||||
## Save flow
|
||||
|
||||
|
||||
@@ -9,3 +9,29 @@ fn file_uris_become_local_paths() {
|
||||
assert_eq!(file_uri_path("sftp://host/x.png"), None);
|
||||
assert_eq!(file_uri_path("file://host/x.png"), None);
|
||||
}
|
||||
|
||||
/// The name the Save dialog's answer ends up with: the picked type (`picked`, an index into `filters`) decides the
|
||||
/// extension a bare name takes, and an extension the user typed wins unless it is the one the dialog opened with.
|
||||
#[trial]
|
||||
fn the_picked_file_type_gives_a_bare_name_its_extension_and_a_typed_extension_wins() {
|
||||
let two = [Filter::new("Photoshop", &["psd", "psb"]), Filter::new("PNG", &["png"])];
|
||||
let only = [Filter::new("Swatches", &["aco"])];
|
||||
// (path, opened with, filters, picked type, expected path)
|
||||
let table: [(&str, Option<&str>, &[Filter], Option<usize>, &str); 8] = [
|
||||
("/s/Untitled", Some("Untitled.psd"), &two, Some(1), "/s/Untitled.png"),
|
||||
("/s/Untitled.psd", Some("Untitled.psd"), &two, Some(1), "/s/Untitled.png"),
|
||||
("/s/art.png", Some("art.psd"), &two, Some(0), "/s/art.png"),
|
||||
("/s/art.PSB", Some("art.psd"), &two, Some(0), "/s/art.PSB"),
|
||||
("/s/scan.2024", None, &two, Some(1), "/s/scan.2024.png"),
|
||||
("/s/Swatches", None, &only, None, "/s/Swatches.aco"),
|
||||
("/s/Swatches.aco", None, &only, None, "/s/Swatches.aco"),
|
||||
("/s/free", None, &two, None, "/s/free"),
|
||||
];
|
||||
for (path, opened, filters, picked, expected) in table {
|
||||
let chosen: &[String] = match chosen_type(filters, picked) {
|
||||
Some(at) => &filters[at].extensions,
|
||||
None => &[],
|
||||
};
|
||||
assert_eq!(with_chosen_type(Path::new(path), opened, chosen, filters), PathBuf::from(expected), "{path} with type {picked:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,3 +184,6 @@ fn classify_error(e: &zbus::Error) -> Option<bool> {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
use super::*;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
fn findings(libdbus: Option<bool>, file_chooser_portal: Option<bool>, zenity: bool) -> Findings {
|
||||
Findings { libdbus, file_chooser_portal, zenity }
|
||||
}
|
||||
|
||||
/// The probe speaks only when no backend can show a dialog: anything it could not tell counts as present, so a
|
||||
/// working system stays silent.
|
||||
#[trial]
|
||||
fn a_dialog_is_explained_only_when_no_backend_can_show_one() {
|
||||
let silent = [
|
||||
findings(Some(true), Some(true), false),
|
||||
findings(Some(false), Some(true), true),
|
||||
findings(Some(true), Some(false), true),
|
||||
findings(None, None, false),
|
||||
findings(Some(true), None, false),
|
||||
findings(None, Some(true), false),
|
||||
];
|
||||
for found in silent {
|
||||
assert_eq!(problem(found), None, "{found:?}");
|
||||
}
|
||||
assert_eq!(problem(findings(Some(false), Some(true), false)).as_deref(), Some("libdbus is missing"));
|
||||
assert_eq!(problem(findings(Some(true), Some(false), false)).as_deref(), Some("no desktop portal offers a file chooser"));
|
||||
assert_eq!(problem(findings(None, Some(false), false)).as_deref(), Some("no desktop portal offers a file chooser"));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[trial]
|
||||
fn the_interface_list_says_whether_a_file_chooser_is_offered() {
|
||||
let xml = |name: &str, quote: char| format!("<node><interface name={quote}{name}{quote}><method name=\"OpenFile\"/></interface></node>");
|
||||
assert!(interface_listed(&xml("org.freedesktop.portal.FileChooser", '"')));
|
||||
assert!(interface_listed(&xml("org.freedesktop.portal.FileChooser", '\'')));
|
||||
assert!(!interface_listed(&xml("org.freedesktop.portal.FileChooser2", '"')), "a longer name is another interface");
|
||||
assert!(!interface_listed(&xml("org.freedesktop.portal.Settings", '"')));
|
||||
assert!(!interface_listed(""));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[trial]
|
||||
fn dbus_errors_for_a_missing_interface_mean_absent() {
|
||||
use zbus::fdo::Error as Fdo;
|
||||
let absent = [
|
||||
zbus::Error::FDO(Box::new(Fdo::ServiceUnknown("gone".into()))),
|
||||
zbus::Error::FDO(Box::new(Fdo::NameHasNoOwner("gone".into()))),
|
||||
zbus::Error::FDO(Box::new(Fdo::UnknownObject("gone".into()))),
|
||||
zbus::Error::FDO(Box::new(Fdo::InvalidArgs("No such interface".into()))),
|
||||
];
|
||||
for error in &absent {
|
||||
assert_eq!(classify_error(error), Some(false), "{error}");
|
||||
}
|
||||
let method = |name: &'static str| {
|
||||
let name = zbus::names::OwnedErrorName::try_from(name).expect("a valid error name");
|
||||
zbus::Error::MethodError(name, None, zbus::message::Message::method_call("/", "Ping").expect("a call").build(&()).expect("a message"))
|
||||
};
|
||||
assert_eq!(classify_error(&method("org.freedesktop.DBus.Error.UnknownInterface")), Some(false));
|
||||
// Anything else says nothing about the interface, so the probe counts it as present.
|
||||
assert_eq!(classify_error(&zbus::Error::FDO(Box::new(Fdo::AccessDenied("no".into())))), None);
|
||||
assert_eq!(classify_error(&method("org.freedesktop.DBus.Error.AccessDenied")), None);
|
||||
}
|
||||
@@ -1,399 +0,0 @@
|
||||
//! [`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};
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
//! The file service's UI parts: [`PathField`] and [`FileListPicker`], and the words of the service's native boxes.
|
||||
//! The file service's UI part: [`PathField`], and the words of the service's native boxes.
|
||||
|
||||
mod file_list;
|
||||
mod path_field;
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
pub use file_list::{FileList, FileListMode, FileListPicker, FileListPickerOutput, FileListWords};
|
||||
pub use path_field::{PathField, PathFieldOutput, PathFieldWords};
|
||||
|
||||
craft_ui::words! {
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
//! Stories of the path field and the file list picker.
|
||||
//! Stories of the path field.
|
||||
|
||||
use super::{FileList, FileListMode, FileListPicker, PathField};
|
||||
use super::PathField;
|
||||
use craft_host::PickRequest;
|
||||
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(PathField<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn path_field_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
@@ -31,28 +23,3 @@ fn path_field_missing_file(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[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()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The file list, the path field and the picker tickets they keep, against a file service that records its requests.
|
||||
//! The path field and the picker ticket it keeps, against a file service that records its requests.
|
||||
|
||||
use craft_dialogs::ui::{FileList, FileListPicker, PathField};
|
||||
use craft_dialogs::ui::PathField;
|
||||
use craft_host::{AppInfo, FileError, Files, Host, PickAnswer, PickId, PickRequest, Picked};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
@@ -72,42 +72,6 @@ fn paths(names: &[&str]) -> Vec<PathBuf> {
|
||||
names.iter().map(|n| PathBuf::from(format!("/photos/{n}"))).collect()
|
||||
}
|
||||
|
||||
fn names(list: &FileList) -> Vec<String> {
|
||||
list.files.iter().map(|p| p.file_name().expect("a file name").to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
/// An answer arriving while the list shows lands in the list once and is written to the binding once: the footer's
|
||||
/// sizing pass takes and writes nothing.
|
||||
#[trial]
|
||||
fn browse_answer_is_taken_and_written_once() {
|
||||
let files = Arc::new(StubFiles::default());
|
||||
let list = Rc::new(RefCell::new(FileList::default()));
|
||||
let changes = Rc::new(Cell::new(0usize));
|
||||
let ticket = Rc::new(Cell::new(None::<PickId>));
|
||||
let (held, counted, issued) = (Rc::clone(&list), Rc::clone(&changes), Rc::clone(&ticket));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut list = held.borrow_mut();
|
||||
let out = FileListPicker::new("Files to load", Bind::bound(&mut *list)).show(ui);
|
||||
if out.browsing.is_some() {
|
||||
issued.set(out.browsing);
|
||||
}
|
||||
if out.changed {
|
||||
counted.set(counted.get() + 1);
|
||||
}
|
||||
});
|
||||
fixture.host(host_with(&files));
|
||||
fixture.settle();
|
||||
let browse = fixture.by_label("Browse…").expect("the Browse button");
|
||||
fixture.click(&browse);
|
||||
fixture.settle();
|
||||
changes.set(0);
|
||||
|
||||
files.answer(ticket.get().expect("Browse issued a ticket"), Picked::Paths(paths(&["a.png", "b.png"])));
|
||||
fixture.idle(3);
|
||||
assert_eq!(names(&list.borrow()), ["a.png", "b.png"]);
|
||||
assert_eq!(changes.get(), 1, "the answer is written to the binding once");
|
||||
}
|
||||
|
||||
/// The path field's Browse queues a pick through the file service, and the answer lands in the field's path once.
|
||||
#[trial]
|
||||
fn path_field_browse_fills_the_path() {
|
||||
|
||||
@@ -23,6 +23,9 @@ use std::path::{Path, PathBuf};
|
||||
#[cfg(feature = "testing")]
|
||||
mod stories;
|
||||
|
||||
/// The list shows this many rows, then scrolls.
|
||||
const LIST_ROWS: u16 = 6;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of the file list picker.
|
||||
pub struct FileListWords {
|
||||
@@ -133,6 +136,8 @@ impl Outcome for FileListPickerOutput {
|
||||
///
|
||||
/// 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`].
|
||||
///
|
||||
/// The list shows six rows and scrolls the rest.
|
||||
#[must_use = "show the picker with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
|
||||
pub struct FileListPicker<'a> {
|
||||
@@ -249,7 +254,7 @@ impl<'a> FileListPicker<'a> {
|
||||
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 = List::new(words.files.clone()).id_salt("files").surface(SurfaceKind::Sunken).pad(Pad::Control).max_rows(LIST_ROWS);
|
||||
let list = if folder {
|
||||
list.select(SelectMode::None)
|
||||
} else {
|
||||
|
||||
@@ -7,7 +7,7 @@ mod parse;
|
||||
use super::fields::{DialogFields, FieldValue};
|
||||
use crate::patterns::blend_keys::BlendKeyEntry;
|
||||
use crate::runtime::env::{Label, UnitKind};
|
||||
use crate::runtime::requests::{ColorRequest, EyedropperRequest, PathKind};
|
||||
use crate::runtime::requests::{ColorRequest, EyedropperRequest, ListingRequest, PathKind};
|
||||
use crate::value_drag::SliderScale;
|
||||
use craft_host::PickRequest;
|
||||
use craft_theme::Srgba;
|
||||
@@ -243,14 +243,12 @@ impl ParamKind {
|
||||
|
||||
/// 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")
|
||||
ParamKind::Blend { modes, default }
|
||||
}
|
||||
|
||||
/// 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")
|
||||
ParamKind::Pattern { default }
|
||||
}
|
||||
|
||||
/// Fields per row of a [`ParamKind::Grid`] of `cells`: `round(sqrt(cells))`, at least 1.
|
||||
@@ -284,9 +282,12 @@ 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::Blend { modes, default } => {
|
||||
let initial = default.as_deref().or_else(|| modes.first().map(|(entry, _)| entry.key.as_str()));
|
||||
FieldValue::Text(initial.unwrap_or_default().to_owned())
|
||||
}
|
||||
ParamKind::Pattern { default } => FieldValue::Text(default.clone()?),
|
||||
ParamKind::Files { open_files, .. } => path_list(open_files),
|
||||
ParamKind::ReadOnlyText { .. } | ParamKind::Custom(_) | ParamKind::Section => return None,
|
||||
})
|
||||
}
|
||||
@@ -316,9 +317,9 @@ impl ParamKind {
|
||||
(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"),
|
||||
(ParamKind::Blend { modes, .. }, FieldValue::Text(id)) => modes.iter().any(|(entry, _)| entry.key == *id),
|
||||
(ParamKind::Pattern { .. }, FieldValue::Text(_)) => true,
|
||||
(ParamKind::Files { .. }, v) => is_path_list(v),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -363,30 +364,29 @@ pub struct CustomContext {
|
||||
colors: DialogFields,
|
||||
request: Option<ColorRequest>,
|
||||
canvas: Option<egui::Id>,
|
||||
eyedropper: Option<EyedropperRequest>,
|
||||
sampling: bool,
|
||||
}
|
||||
|
||||
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, canvas: Option<egui::Id>) -> Self {
|
||||
CustomContext { title, colors, request: None, canvas }
|
||||
CustomContext { title, colors, request: None, canvas, eyedropper: None, sampling: false }
|
||||
}
|
||||
|
||||
/// 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")
|
||||
self.eyedropper = Some(request);
|
||||
}
|
||||
|
||||
/// 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")
|
||||
self.sampling = on;
|
||||
}
|
||||
|
||||
/// 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")
|
||||
self.canvas
|
||||
}
|
||||
|
||||
/// Asks the host for its colour picker for the value under `key`, which needs no row of its own. The picker opens
|
||||
@@ -398,6 +398,16 @@ impl CustomContext {
|
||||
self.request = Some(ColorRequest::new(key, color).title(self.title.clone()));
|
||||
}
|
||||
|
||||
/// The dropper the row armed, once.
|
||||
pub(crate) fn take_eyedropper(&mut self) -> Option<EyedropperRequest> {
|
||||
self.eyedropper.take()
|
||||
}
|
||||
|
||||
/// Whether the row asked for canvas presses to pick colours.
|
||||
pub(crate) fn is_sampling(&self) -> bool {
|
||||
self.sampling
|
||||
}
|
||||
|
||||
/// The colour request the row made, once.
|
||||
pub(crate) fn take_request(&mut self) -> Option<ColorRequest> {
|
||||
self.request.take()
|
||||
@@ -453,6 +463,20 @@ pub(crate) struct UnitChoices {
|
||||
initial: usize,
|
||||
}
|
||||
|
||||
/// The value that holds `paths`: a list of text, the shape a [`Param::files`] row keeps its files in.
|
||||
pub(crate) fn path_list(paths: &[PathBuf]) -> FieldValue {
|
||||
FieldValue::List(paths.iter().map(|path| FieldValue::Text(path.to_string_lossy().into_owned())).collect())
|
||||
}
|
||||
|
||||
/// Whether `value` is a list of paths. An empty list stored and read back is a `Grid` of no cells.
|
||||
fn is_path_list(value: &FieldValue) -> bool {
|
||||
match value {
|
||||
FieldValue::List(items) => items.iter().all(|item| matches!(item, FieldValue::Text(_))),
|
||||
FieldValue::Grid(cells) => cells.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Texts a row may carry beyond its label.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct RowTexts {
|
||||
@@ -472,8 +496,8 @@ pub struct Param {
|
||||
pub kind: ParamKind,
|
||||
/// Shown after the number (`px`, `%`, `°`); formats through the locale.
|
||||
pub unit: Option<UnitKind>,
|
||||
/// The row takes input only while `fields[key]` equals the value.
|
||||
pub enabled_when: Option<(String, FieldValue)>,
|
||||
/// The row takes input only while `fields[key]` equals one of the values.
|
||||
pub enabled_when: Option<(String, Vec<FieldValue>)>,
|
||||
/// The row is shown only while `fields[key]` equals the value ([`Param::visible_when`]). A hidden row takes no
|
||||
/// space; its value stays in the fields and in the result.
|
||||
pub visible_when: Option<(String, FieldValue)>,
|
||||
@@ -503,50 +527,53 @@ 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")
|
||||
let key = key.into();
|
||||
let kind = ParamKind::Files { folder_mode: false, request: PickRequest::open_many(key.clone()), open_files: Vec::new() };
|
||||
Self::new(key, label, kind)
|
||||
}
|
||||
|
||||
/// 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")
|
||||
pub fn folder_mode(mut self, on: bool) -> Self {
|
||||
if let ParamKind::Files { folder_mode, .. } = &mut self.kind {
|
||||
*folder_mode = on;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// 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")
|
||||
pub fn open_files(mut self, paths: Vec<PathBuf>) -> Self {
|
||||
if let ParamKind::Files { open_files, .. } = &mut self.kind {
|
||||
*open_files = paths;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// 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")
|
||||
self.options.get_or_insert_default().disabled_options = ids.into_iter().map(Into::into).collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the option `id` of a choice row takes a pick.
|
||||
pub fn option_enabled(&self, id: &str) -> bool {
|
||||
let _ = id;
|
||||
todo!("cw.C39")
|
||||
self.options.as_deref().is_none_or(|options| !options.disabled_options.iter().any(|disabled| disabled == id))
|
||||
}
|
||||
|
||||
/// Gives a choice row's select a search field.
|
||||
#[must_use]
|
||||
pub fn searchable(mut self) -> Self {
|
||||
let _ = &mut self;
|
||||
todo!("pn.C51")
|
||||
self.options.get_or_insert_default().searchable = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// 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")
|
||||
pub fn enabled_when_in(mut self, key: impl Into<String>, values: impl IntoIterator<Item = impl Into<FieldValue>>) -> Self {
|
||||
self.enabled_when = Some((key.into(), values.into_iter().map(Into::into).collect()));
|
||||
self
|
||||
}
|
||||
|
||||
/// A bare number row: a [`ParamKind::Number`] open on both sides. Bound it with [`Param::bounds`].
|
||||
@@ -627,10 +654,11 @@ impl Param {
|
||||
self
|
||||
}
|
||||
|
||||
/// The row takes input only while `fields[key]` equals `value`; otherwise it is shown disabled.
|
||||
/// The row takes input only while `fields[key]` equals `value`; otherwise it is shown disabled. The one-value case
|
||||
/// of [`enabled_when_in`](Param::enabled_when_in).
|
||||
#[must_use]
|
||||
pub fn enabled_when(mut self, key: impl Into<String>, value: impl Into<FieldValue>) -> Self {
|
||||
self.enabled_when = Some((key.into(), value.into()));
|
||||
self.enabled_when = Some((key.into(), vec![value.into()]));
|
||||
self
|
||||
}
|
||||
|
||||
@@ -768,7 +796,14 @@ impl Param {
|
||||
/// units.
|
||||
pub fn accepts(&self, key: &str, value: &FieldValue) -> bool {
|
||||
if self.key == key {
|
||||
return self.kind.fits(value);
|
||||
return self.kind.fits(value) && self.option_allowed(value);
|
||||
}
|
||||
if matches!(self.kind, ParamKind::Files { .. }) {
|
||||
return match value {
|
||||
FieldValue::Text(_) => key == self.folder_key(),
|
||||
FieldValue::Bool(_) => key == self.use_folder_key(),
|
||||
other => key == self.folder_files_key() && is_path_list(other),
|
||||
};
|
||||
}
|
||||
match (self.options.as_deref().and_then(|o| o.units.as_ref()), value) {
|
||||
(Some(units), FieldValue::Text(id)) => units.key == key && units.units.iter().any(|u| &u.id == id),
|
||||
@@ -776,6 +811,39 @@ impl Param {
|
||||
}
|
||||
}
|
||||
|
||||
/// The key a [`Param::files`] row stores its folder under: `"{key}.folder"`.
|
||||
pub(crate) fn folder_key(&self) -> String {
|
||||
format!("{}.folder", self.key)
|
||||
}
|
||||
|
||||
/// The key a [`Param::files`] row stores whether the folder is used under: `"{key}.useFolder"`.
|
||||
pub(crate) fn use_folder_key(&self) -> String {
|
||||
format!("{}.useFolder", self.key)
|
||||
}
|
||||
|
||||
/// The listing a [`Param::files`] row asks for when `before` becomes `after`: one of the folder in `after` when
|
||||
/// that folder is in use and the folder or the use of it differs from `before`.
|
||||
pub(crate) fn listing_after(&self, before: &DialogFields, after: &DialogFields) -> Option<ListingRequest> {
|
||||
let (folder_key, use_key) = (self.folder_key(), self.use_folder_key());
|
||||
let uses = |fields: &DialogFields| fields.bool(&use_key).unwrap_or(false);
|
||||
let folder = after.text(&folder_key).filter(|_| uses(after))?;
|
||||
let changed = before.text(&folder_key) != Some(folder) || !uses(before);
|
||||
changed.then(|| ListingRequest::new(&self.key, PathBuf::from(folder)))
|
||||
}
|
||||
|
||||
/// The key the host's listing of a [`Param::files`] row's folder is written under: `"{key}.folderFiles"`.
|
||||
pub(crate) fn folder_files_key(&self) -> String {
|
||||
format!("{}.folderFiles", self.key)
|
||||
}
|
||||
|
||||
/// Whether `value` names no disabled option of a Radio, Choice or Blend row.
|
||||
fn option_allowed(&self, value: &FieldValue) -> bool {
|
||||
match (&self.kind, value) {
|
||||
(ParamKind::Radio { .. } | ParamKind::Choice { .. } | ParamKind::Blend { .. }, FieldValue::Text(id)) => self.option_enabled(id),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the row is shown with `fields`.
|
||||
pub fn visible(&self, fields: &DialogFields) -> bool {
|
||||
self.visible_when.as_ref().is_none_or(|(key, value)| fields.get(key) == Some(value))
|
||||
@@ -783,7 +851,7 @@ impl Param {
|
||||
|
||||
/// Whether the row takes input with `fields`.
|
||||
pub fn enabled(&self, fields: &DialogFields) -> bool {
|
||||
self.enabled_when.as_ref().is_none_or(|(key, value)| fields.get(key) == Some(value))
|
||||
self.enabled_when.as_ref().is_none_or(|(key, values)| fields.get(key).is_some_and(|held| values.contains(held)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -818,6 +886,11 @@ impl RowOptions {
|
||||
self.lines
|
||||
}
|
||||
|
||||
/// Whether a choice row's select has a search field.
|
||||
pub(crate) fn searchable(&self) -> bool {
|
||||
self.searchable
|
||||
}
|
||||
|
||||
/// The units of a number row.
|
||||
pub(crate) fn units(&self) -> Option<&UnitChoices> {
|
||||
self.units.as_ref()
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
//! `ParamRows`: a form with one `Field` per visible parameter of a [`Param`] list, over a [`DialogFields`] value.
|
||||
|
||||
use super::fields::{DialogFields, FieldValue};
|
||||
use crate::patterns::presets::PresetRow;
|
||||
use super::file_list::{FileList, FileListMode, FileListPicker};
|
||||
use crate::patterns::blend_keys::{BlendKeyEntry, BlendKeys, BlendShortcut, BlendStep, blend_entries};
|
||||
use crate::patterns::presets::{PresetKind, PresetPicker, PresetRow};
|
||||
use crate::runtime::commands::{CommandState, Commands as _};
|
||||
use crate::runtime::requests::{ColorRequest, EyedropperRequest, ListingRequest, PathRequest};
|
||||
|
||||
use super::param::{CustomContext, Param, ParamKind, fill_defaults, rounded};
|
||||
use super::param::{CustomContext, Param, ParamKind, fill_defaults, path_list, rounded};
|
||||
use super::path_row::PathRow;
|
||||
use super::words::ParamWords;
|
||||
use crate::buttons::{Button, ToggleButton};
|
||||
use crate::choice::{Checkbox, Radio, RadioGroup, Swatch};
|
||||
use crate::contract::{
|
||||
Bind, CanvasGesture, Entry, NoValue, Outcome, Props as _, Remember as _, Sampler as _, Show as _, ShowContainer as _, clicked,
|
||||
Bind, BodyCx, CanvasGesture, Entry, NoValue, Outcome, Props as _, Remember as _, Sampler as _, Show as _, ShowContainer as _, clicked,
|
||||
};
|
||||
use crate::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
|
||||
|
||||
@@ -26,11 +29,13 @@ use crate::text::{NumberField, SelectableText, TextField};
|
||||
use crate::value_drag::{AngleDial, PointPicker, SliderScale};
|
||||
|
||||
use craft_behavior::{EditEvent, IconId, Mixed, NumberCodec};
|
||||
use craft_host::PickRequest;
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use egui::{Id, Response, Ui};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::RangeInclusive;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "testing")]
|
||||
@@ -100,13 +105,14 @@ pub struct ParamRows<'a> {
|
||||
seed: Option<Bind<'a, u64>>,
|
||||
read_only: bool,
|
||||
canvas: Option<Id>,
|
||||
patterns: &'a [PresetRow<String>],
|
||||
preview_colors: &'a [(String, Srgba)],
|
||||
}
|
||||
|
||||
impl<'a> ParamRows<'a> {
|
||||
/// Rows for `params` over `fields`, the group named `label`.
|
||||
pub fn new(label: impl Into<Label>, params: &'a [Param], fields: Bind<'a, DialogFields>) -> Self {
|
||||
ParamRows { label: label.into(), params, fields, seed: None, read_only: false, canvas: None, preview_colors: &[] }
|
||||
ParamRows { label: label.into(), params, fields, seed: None, read_only: false, canvas: None, patterns: &[], preview_colors: &[] }
|
||||
}
|
||||
|
||||
/// The colours child pickers preview, by colour row key: each such row draws its colour for the pass in place of
|
||||
@@ -132,8 +138,8 @@ impl<'a> ParamRows<'a> {
|
||||
|
||||
/// 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")
|
||||
self.patterns = rows;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the rows only show their values.
|
||||
@@ -144,12 +150,12 @@ impl<'a> ParamRows<'a> {
|
||||
|
||||
/// Shows the rows across the width offered.
|
||||
pub fn show(self, ui: &mut Ui) -> ParamRowsOutput {
|
||||
let ParamRows { label, params, mut fields, mut seed, read_only, canvas, preview_colors } = self;
|
||||
let ParamRows { label, params, mut fields, mut seed, read_only, canvas, patterns, preview_colors } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<ParamWords>();
|
||||
let units = env.units();
|
||||
let name: Arc<str> = label.as_str().into();
|
||||
let mut pass = Pass::new(&words, &units);
|
||||
let mut pass = Pass::new(&words, &units, patterns, canvas);
|
||||
pass.previews = preview_colors;
|
||||
let mut changed = false;
|
||||
let mut values = None;
|
||||
@@ -166,6 +172,9 @@ impl<'a> ParamRows<'a> {
|
||||
_ => None,
|
||||
};
|
||||
pass.begin(&filled, state, cx.keep::<Memo>().clone());
|
||||
if !read_only {
|
||||
pass.blend_keys(cx, params);
|
||||
}
|
||||
pass.rows(ui, params);
|
||||
if let Some(canvas) = canvas.filter(|_| pass.sampling && !read_only) {
|
||||
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
|
||||
@@ -184,8 +193,9 @@ 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, listing: None }
|
||||
let (pick_color, path, eyedropper, listing) =
|
||||
if read_only { Default::default() } else { (pass.color, pass.path, pass.eyedropper, pass.listing) };
|
||||
ParamRowsOutput { response: shown.output, changed, values, pick_color, path, eyedropper, listing }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,6 +210,8 @@ struct Memo {
|
||||
declared: BTreeMap<String, bool>,
|
||||
last: BTreeMap<String, f64>,
|
||||
sequence: Option<u64>,
|
||||
/// The selected file of each files row: the selection belongs to the list's view, not to the row's values.
|
||||
selected: BTreeMap<String, PathBuf>,
|
||||
}
|
||||
|
||||
/// One pass over the rows: the working values, what the rows ask of the host, and what the pass reads.
|
||||
@@ -215,8 +227,14 @@ struct Pass<'p> {
|
||||
color: Option<ColorRequest>,
|
||||
path: Option<PathRequest>,
|
||||
eyedropper: Option<EyedropperRequest>,
|
||||
/// The folder a files row asked the host to list.
|
||||
listing: Option<ListingRequest>,
|
||||
/// An eyedropper row is armed.
|
||||
sampling: bool,
|
||||
/// The patterns a pattern row offers.
|
||||
patterns: &'p [PresetRow<String>],
|
||||
/// The canvas a custom row can ask about.
|
||||
canvas: Option<Id>,
|
||||
/// The colours shown in colour rows in place of their values (`ParamRows::preview_colors`).
|
||||
previews: &'p [(String, Srgba)],
|
||||
}
|
||||
@@ -250,7 +268,7 @@ impl Line<'_> {
|
||||
}
|
||||
|
||||
impl<'p> Pass<'p> {
|
||||
fn new(words: &'p ParamWords, units: &'p Units) -> Self {
|
||||
fn new(words: &'p ParamWords, units: &'p Units, patterns: &'p [PresetRow<String>], canvas: Option<Id>) -> Self {
|
||||
Pass {
|
||||
words,
|
||||
units,
|
||||
@@ -261,7 +279,10 @@ impl<'p> Pass<'p> {
|
||||
color: None,
|
||||
path: None,
|
||||
eyedropper: None,
|
||||
listing: None,
|
||||
sampling: false,
|
||||
patterns,
|
||||
canvas,
|
||||
previews: &[],
|
||||
}
|
||||
}
|
||||
@@ -275,9 +296,46 @@ impl<'p> Pass<'p> {
|
||||
self.color = None;
|
||||
self.path = None;
|
||||
self.eyedropper = None;
|
||||
self.listing = None;
|
||||
self.sampling = false;
|
||||
}
|
||||
|
||||
/// The blend keys of the first visible Blend row: Shift+= and Shift+- step its mode, Shift+Alt and a letter pick
|
||||
/// one. The commands are taken from the board once, so a second pass in the same frame applies none: a pass
|
||||
/// applies only its own input. Later Blend rows publish nothing, so one key press never moves two rows.
|
||||
fn blend_keys(&mut self, cx: &mut BodyCx<'_>, params: &[Param]) {
|
||||
let Some(param) = params.iter().find(|param| matches!(param.kind, ParamKind::Blend { .. }) && param.visible(&self.work)) else {
|
||||
return;
|
||||
};
|
||||
let ParamKind::Blend { modes, .. } = ¶m.kind else { return };
|
||||
let enabled = param.enabled(&self.work);
|
||||
let state = || CommandState::new().enabled(enabled);
|
||||
let entries = blend_key_entries(modes);
|
||||
for step in [BlendStep::Next, BlendStep::Previous] {
|
||||
cx.publish(step, state());
|
||||
}
|
||||
for shortcut in entries.iter().filter_map(|entry| entry.shortcut) {
|
||||
cx.publish(shortcut, state());
|
||||
}
|
||||
let mut fired = Vec::new();
|
||||
while let Some((_, step)) = cx.take_command::<BlendStep>() {
|
||||
fired.push(step);
|
||||
}
|
||||
while let Some((_, letter)) = cx.take_command::<BlendShortcut>() {
|
||||
fired.push(letter);
|
||||
}
|
||||
let mut current = self.work.text(¶m.key).map(str::to_owned).or_else(|| param.kind.default_value().and_then(text_of)).unwrap_or_default();
|
||||
for fired in fired {
|
||||
if let Some(pick) = BlendKeys::new(&entries).current(¤t).fired(&fired) {
|
||||
let id = pick.into_key();
|
||||
if param.option_enabled(&id) {
|
||||
self.work.set(param.key.as_str(), FieldValue::Text(id.clone()));
|
||||
current = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of `params`: those before the first section, then each section with the rows up to the next.
|
||||
fn rows(&mut self, ui: &mut Ui, params: &[Param]) {
|
||||
let is_section = |param: &Param| matches!(param.kind, ParamKind::Section);
|
||||
@@ -322,7 +380,9 @@ 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::Blend { modes, .. } => self.blend(ui, &line, modes),
|
||||
ParamKind::Pattern { .. } => self.pattern(ui, &line),
|
||||
ParamKind::Files { folder_mode, request, open_files } => self.files(ui, &line, *folder_mode, request, open_files),
|
||||
ParamKind::Section => {}
|
||||
}
|
||||
}
|
||||
@@ -424,7 +484,33 @@ impl<'p> Pass<'p> {
|
||||
|
||||
fn choice(&mut self, ui: &mut Ui, line: &Line<'_>, options: &[(String, Label)]) {
|
||||
let value = self.work.text(line.key).map(str::to_owned).or_else(|| line.param.kind.default_value().and_then(text_of)).unwrap_or_default();
|
||||
let entries: Vec<Entry<String>> = options.iter().map(|(id, label)| Entry::new(id.clone(), label.clone())).collect();
|
||||
let entries: Vec<Entry<String>> =
|
||||
options.iter().map(|(id, label)| Entry::new(id.clone(), label.clone()).enabled(line.param.option_enabled(id))).collect();
|
||||
let searchable = line.param.option().searchable();
|
||||
line.show(ui, |ui| {
|
||||
let mut select = Select::new(line.name.clone(), Bind::given(value.clone()), &entries);
|
||||
if searchable {
|
||||
select = select.searchable();
|
||||
}
|
||||
if let Some(v) = select.show(ui).value().cloned() {
|
||||
self.work.set(line.key, FieldValue::Text(v));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A select of blend modes. The separators between the mode groups come from the entries' keys, not from the caller.
|
||||
fn blend(&mut self, ui: &mut Ui, line: &Line<'_>, modes: &[(BlendKeyEntry<String>, Label)]) {
|
||||
let value = self.work.text(line.key).map(str::to_owned).or_else(|| line.param.kind.default_value().and_then(text_of)).unwrap_or_default();
|
||||
let keys = blend_key_entries(modes);
|
||||
let entries: Vec<Entry<String>> = blend_entries(&keys, |entry| {
|
||||
modes.iter().find(|(mode, _)| mode.key == entry.key).map_or(Label::Empty, |(_, label)| label.clone())
|
||||
})
|
||||
.into_iter()
|
||||
.map(|entry| {
|
||||
let enabled = entry.value().is_none_or(|id| line.param.option_enabled(id));
|
||||
entry.enabled(enabled)
|
||||
})
|
||||
.collect();
|
||||
line.show(ui, |ui| {
|
||||
if let Some(v) = Select::new(line.name.clone(), Bind::given(value.clone()), &entries).show(ui).value().cloned() {
|
||||
self.work.set(line.key, FieldValue::Text(v));
|
||||
@@ -432,6 +518,79 @@ impl<'p> Pass<'p> {
|
||||
});
|
||||
}
|
||||
|
||||
/// A pattern row: the stored id when the rows have it as a pattern, else the first pattern is shown. A pick writes
|
||||
/// the pattern's id; the group headers of the list take no pick.
|
||||
fn pattern(&mut self, ui: &mut Ui, line: &Line<'_>) {
|
||||
let rows = self.patterns;
|
||||
let is_pattern = |row: &&PresetRow<String>| matches!(row.kind, PresetKind::Item);
|
||||
let stored = self.work.text(line.key);
|
||||
let current = rows
|
||||
.iter()
|
||||
.filter(is_pattern)
|
||||
.find(|row| Some(row.key.as_str()) == stored)
|
||||
.or_else(|| rows.iter().find(is_pattern))
|
||||
.map(|row| row.key.clone());
|
||||
// With no pattern to offer the row is disabled and writes nothing.
|
||||
let line = Line { param: line.param, key: line.key, name: line.name.clone(), enabled: line.enabled && current.is_some() };
|
||||
line.show(ui, |ui| {
|
||||
let picked = PresetPicker::pattern(line.name.clone(), Bind::given(current.clone()), rows, Bind::kept()).show(ui).picked;
|
||||
if let Some(id) = picked.filter(|id| rows.iter().filter(is_pattern).any(|row| row.key == *id)) {
|
||||
self.work.set(line.key, FieldValue::Text(id));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A files row: a `FileListPicker` over the row's keys. A change of folder, or Folder mode turned on with a folder
|
||||
/// set, drops the old listing and files a request for the new one in the same edit, so the rows keep no memo of it.
|
||||
fn files(&mut self, ui: &mut Ui, line: &Line<'_>, folder_mode: bool, request: &PickRequest, open_files: &[PathBuf]) {
|
||||
let param = line.param;
|
||||
let (folder_key, use_key, listed_key) = (param.folder_key(), param.use_folder_key(), param.folder_files_key());
|
||||
let files = paths_at(&self.work, line.key);
|
||||
let folder = self.work.text(&folder_key).map(PathBuf::from);
|
||||
let use_folder = folder_mode && self.work.bool(&use_key).unwrap_or(false);
|
||||
let listed = paths_at(&self.work, &listed_key);
|
||||
let before_work = self.work.clone();
|
||||
let mut list = FileList {
|
||||
mode: if use_folder { FileListMode::Folder } else { FileListMode::Files },
|
||||
files: files.clone(),
|
||||
folder: folder.clone(),
|
||||
selected: self.memo.selected.get(line.key).filter(|path| files.contains(path)).cloned(),
|
||||
};
|
||||
line.show(ui, |ui| {
|
||||
let shown = FileListPicker::new(line.name.clone(), Bind::bound(&mut list))
|
||||
.folder_mode(folder_mode)
|
||||
.open_files(open_files)
|
||||
.folder_files(&listed)
|
||||
.request(request.clone())
|
||||
.show(ui);
|
||||
if !shown.changed {
|
||||
return;
|
||||
}
|
||||
if list.files != files {
|
||||
self.work.set(line.key, path_list(&list.files));
|
||||
}
|
||||
let now_folder = list.mode == FileListMode::Folder;
|
||||
if now_folder != use_folder {
|
||||
self.work.set(use_key.as_str(), FieldValue::Bool(now_folder));
|
||||
}
|
||||
if list.folder != folder
|
||||
&& let Some(path) = &list.folder
|
||||
{
|
||||
self.work.set(folder_key.as_str(), FieldValue::Text(path.to_string_lossy().into_owned()));
|
||||
}
|
||||
if (list.folder != folder || now_folder != use_folder) && !listed.is_empty() {
|
||||
self.work.remove(&listed_key);
|
||||
}
|
||||
if let Some(request) = param.listing_after(&before_work, &self.work) {
|
||||
self.listing = Some(request);
|
||||
}
|
||||
});
|
||||
match list.selected {
|
||||
Some(path) => self.memo.selected.insert(line.key.to_owned(), path),
|
||||
None => self.memo.selected.remove(line.key),
|
||||
};
|
||||
}
|
||||
|
||||
/// A radio row is its own section: the title shows the row's name once, and the group it names follows.
|
||||
fn radio_options(&mut self, ui: &mut Ui, line: &Line<'_>, options: &[(String, Label)]) {
|
||||
let value = self.work.text(line.key).map(str::to_owned).or_else(|| line.param.kind.default_value().and_then(text_of)).unwrap_or_default();
|
||||
@@ -443,7 +602,7 @@ impl<'p> Pass<'p> {
|
||||
let group = group.show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for (id, label) in options {
|
||||
Radio::new(id.clone()).label(label.clone()).show(ui);
|
||||
Radio::new(id.clone()).label(label.clone()).enabled(line.param.option_enabled(id) && line.enabled).show(ui);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -641,24 +800,47 @@ 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(), None); // P3(dialogs-w2): dl.K30, the rows' canvas
|
||||
let mut context = CustomContext::new(line.name.clone(), self.work.clone(), self.canvas);
|
||||
line.show_body(ui, |ui| {
|
||||
let _ = row.draw(ui, &mut self.work, &mut context);
|
||||
});
|
||||
if let Some(request) = context.take_request() {
|
||||
self.color = Some(request);
|
||||
}
|
||||
if let Some(request) = context.take_eyedropper() {
|
||||
self.memo.armed = Some(request.key.clone());
|
||||
self.eyedropper = Some(request);
|
||||
}
|
||||
self.sampling |= context.is_sampling();
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only text beside the row's label, or across the form for a full-width row.
|
||||
/// Read-only text beside the row's label, or across the form for a full-width row, inset like a field's text.
|
||||
fn read_only_text(ui: &mut Ui, line: &Line<'_>, text: &Label) {
|
||||
let shown = Env::of(ui).view().resolve(text);
|
||||
line.show_body(ui, |ui| {
|
||||
SelectableText::new(line.name.clone(), shown.as_str()).multiline().show(ui);
|
||||
SelectableText::new(line.name.clone(), shown.as_str()).multiline().field_inset().show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// The mode entries of a Blend row's `modes`, in menu order.
|
||||
fn blend_key_entries(modes: &[(BlendKeyEntry<String>, Label)]) -> Vec<BlendKeyEntry<String>> {
|
||||
modes.iter().map(|(entry, _)| entry.clone()).collect()
|
||||
}
|
||||
|
||||
/// The paths a files row keeps under `key`.
|
||||
fn paths_at(fields: &DialogFields, key: &str) -> Vec<PathBuf> {
|
||||
let items = fields.list(key);
|
||||
items
|
||||
.iter()
|
||||
.flat_map(|items| items.iter())
|
||||
.filter_map(|item| match item {
|
||||
FieldValue::Text(text) => Some(PathBuf::from(text)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Shows `body` as one row of controls side by side.
|
||||
fn beside(ui: &mut Ui, mut body: impl FnMut(&mut Ui)) {
|
||||
Row::new().show(ui, |ui, _| body(ui));
|
||||
|
||||
@@ -4,7 +4,9 @@ use super::{DialogFields, ParamRows};
|
||||
use crate::runtime::requests::PathKind;
|
||||
|
||||
use crate::contract::Bind;
|
||||
use crate::patterns::blend_keys::{BlendKeyEntry, BlendShortcut};
|
||||
use crate::patterns::form_dialogs::{NumberUnit, Param, ParamKind};
|
||||
use crate::patterns::presets::PresetRow;
|
||||
use crate::runtime::env::UnitKind;
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
|
||||
@@ -12,10 +14,31 @@ use egui::Ui;
|
||||
|
||||
const SPEC: &str = r#"{"radius":0.1..1000=1,"method":"spin|zoom","smooth":bool,"seed":u32=0,"tint":color=#336699}"#;
|
||||
|
||||
/// The patterns the pattern row offers: a group and two patterns in it.
|
||||
fn patterns() -> Vec<PresetRow<String>> {
|
||||
vec![
|
||||
PresetRow::group("nature".to_owned(), "Nature", 0),
|
||||
PresetRow::item("grass".to_owned(), "Grass", 1),
|
||||
PresetRow::item("sand".to_owned(), "Sand", 1),
|
||||
]
|
||||
}
|
||||
|
||||
/// One row of every kind the rows show, a section, a row that waits for a check box, a row with a unit menu, a
|
||||
/// multi-line text row and a section of read-only rows.
|
||||
/// multi-line text row, a searchable choice, a radio row with a disabled option, a blend row, a pattern row, a files
|
||||
/// row in folder mode and a section of read-only rows.
|
||||
fn params() -> Vec<Param> {
|
||||
let mut params = Param::parse_list(SPEC);
|
||||
let blend = vec![
|
||||
(BlendKeyEntry::new("normal".to_owned(), BlendShortcut::Normal), "Normal".into()),
|
||||
(BlendKeyEntry::new("dissolve".to_owned(), BlendShortcut::Dissolve), "Dissolve".into()),
|
||||
(BlendKeyEntry::new("multiply".to_owned(), BlendShortcut::Multiply), "Multiply".into()),
|
||||
];
|
||||
let sizes = || vec![("small".to_owned(), "Small".into()), ("medium".to_owned(), "Medium".into()), ("large".to_owned(), "Large".into())];
|
||||
params.push(Param::new("blend", "Blend", ParamKind::blend(blend, None)));
|
||||
params.push(Param::new("pattern", "Pattern", ParamKind::pattern(Some("grass".to_owned()))));
|
||||
params.push(Param::files("files", "Files").folder_mode(true));
|
||||
params.push(Param::new("size", "Size", ParamKind::choice(sizes(), None)).searchable());
|
||||
params.push(Param::new("scale", "Scale", ParamKind::radio(sizes(), None)).disabled_options(["large"]));
|
||||
params.push(Param::new("angle", "Angle", ParamKind::angle(30.0)));
|
||||
params.push(Param::new("centre", "Centre", ParamKind::point([50.0, 50.0])));
|
||||
params.push(Param::section("Output"));
|
||||
@@ -46,13 +69,15 @@ fn params() -> Vec<Param> {
|
||||
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
|
||||
fn param_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let params = params();
|
||||
let patterns = patterns();
|
||||
let fields = data.value("fields", DialogFields::new());
|
||||
ParamRows::new("Filter", ¶ms, Bind::bound(fields)).show(ui).into()
|
||||
ParamRows::new("Filter", ¶ms, Bind::bound(fields)).patterns(&patterns).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
|
||||
fn param_rows_read_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let params = params();
|
||||
let patterns = patterns();
|
||||
let fields = data.value("fields", DialogFields::new());
|
||||
ParamRows::new("Filter", ¶ms, Bind::bound(fields)).read_only(true).show(ui).into()
|
||||
ParamRows::new("Filter", ¶ms, Bind::bound(fields)).patterns(&patterns).read_only(true).show(ui).into()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! `FileListPicker` and the Files row of `ParamRows`, against a file service that holds its picks until the test
|
||||
//! answers them.
|
||||
|
||||
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, FileList, FileListPicker, Param, ParamRows};
|
||||
use craft_ui::runtime::requests::ListingRequest;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn host_with(files: &Arc<ScriptedFiles>) -> Arc<Host> {
|
||||
Arc::new(Host::builder(AppInfo { id: "test", name: "Test", version: "1.0" }).files(files.clone()).build())
|
||||
}
|
||||
|
||||
fn paths(names: &[&str]) -> Vec<PathBuf> {
|
||||
names.iter().map(|n| PathBuf::from(format!("/photos/{n}"))).collect()
|
||||
}
|
||||
|
||||
fn names(list: &FileList) -> Vec<String> {
|
||||
list.files.iter().map(|p| p.file_name().expect("a file name").to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
/// An answer arriving while the list shows lands in the list once and is written to the binding once: the footer's
|
||||
/// sizing pass takes and writes nothing.
|
||||
#[trial]
|
||||
fn browse_answer_is_taken_and_written_once() {
|
||||
let files = Arc::new(ScriptedFiles::held());
|
||||
let list = Rc::new(RefCell::new(FileList::default()));
|
||||
let changes = Rc::new(Cell::new(0usize));
|
||||
let ticket = Rc::new(Cell::new(None::<PickId>));
|
||||
let (held, counted, issued) = (Rc::clone(&list), Rc::clone(&changes), Rc::clone(&ticket));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut list = held.borrow_mut();
|
||||
let out = FileListPicker::new("Files to load", Bind::bound(&mut *list)).show(ui);
|
||||
if out.browsing.is_some() {
|
||||
issued.set(out.browsing);
|
||||
}
|
||||
if out.changed {
|
||||
counted.set(counted.get() + 1);
|
||||
}
|
||||
});
|
||||
fixture.host(host_with(&files));
|
||||
fixture.settle();
|
||||
let browse = fixture.by_label("Browse…").expect("the Browse button");
|
||||
fixture.click(&browse);
|
||||
fixture.settle();
|
||||
changes.set(0);
|
||||
|
||||
let id = ticket.get().expect("Browse issued a ticket");
|
||||
assert!(files.answer_to(id, Picked::Paths(paths(&["a.png", "b.png"]))), "the pick is open");
|
||||
fixture.idle(3);
|
||||
assert_eq!(names(&list.borrow()), ["a.png", "b.png"]);
|
||||
assert_eq!(changes.get(), 1, "the answer is written to the binding once");
|
||||
}
|
||||
|
||||
/// A files row in folder mode asks for the listing of a folder once, when the folder changes; later passes ask for
|
||||
/// nothing, and the files the host answers under `"{key}.folderFiles"` are shown.
|
||||
#[trial]
|
||||
fn a_folder_row_asks_for_its_listing_once_per_folder_and_shows_the_answer() {
|
||||
let files = Arc::new(ScriptedFiles::held());
|
||||
let values = Rc::new(RefCell::new(DialogFields::from_pairs([("photos.useFolder", true)])));
|
||||
let asked = Rc::new(RefCell::new(Vec::<ListingRequest>::new()));
|
||||
let (shown, seen) = (values.clone(), asked.clone());
|
||||
let params = vec![Param::files("photos", "Photos").folder_mode(true)];
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = ParamRows::new("Form", ¶ms, Bind::bound(&mut *shown.borrow_mut())).show(ui);
|
||||
seen.borrow_mut().extend(out.listing);
|
||||
});
|
||||
fixture.host(host_with(&files));
|
||||
fixture.settle();
|
||||
assert!(asked.borrow().is_empty(), "no folder, no request");
|
||||
|
||||
let browse = fixture.by_label("Browse…").expect("the Browse button");
|
||||
fixture.click(&browse);
|
||||
fixture.settle();
|
||||
assert!(files.answer(Picked::Paths(vec![PathBuf::from("/shots")])).is_some(), "Browse opened a folder pick");
|
||||
fixture.idle(3);
|
||||
let requests: Vec<(String, PathBuf)> = asked.borrow().iter().map(|r| (r.key.clone(), r.folder.clone())).collect();
|
||||
assert_eq!(requests, [("photos".to_owned(), PathBuf::from("/shots"))], "one request for the new folder");
|
||||
assert_eq!(values.borrow().text("photos.folder"), Some("/shots"));
|
||||
|
||||
// The host's answer, written as the dialog does.
|
||||
let listed = ["dawn.png", "dusk.png"].map(|name| FieldValue::Text(format!("/shots/{name}")));
|
||||
values.borrow_mut().set("photos.folderFiles", FieldValue::List(listed.to_vec()));
|
||||
fixture.idle(4);
|
||||
assert_eq!(asked.borrow().len(), 1, "later passes ask for nothing");
|
||||
assert!(fixture.by_label("dawn.png").is_some() && fixture.by_label("dusk.png").is_some(), "the answered files are listed");
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
//! The parameter model: the spec-string parser, kinds, defaults and fit rules, and the rows' predicates, read-only
|
||||
//! text and tooltips.
|
||||
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind, ParamRows};
|
||||
use craft_ui::contract::{Bind, Role};
|
||||
use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut};
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamRows};
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::value_drag::SliderScale;
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
@@ -33,6 +37,25 @@ fn the_registry_notation_parses_into_params() {
|
||||
assert!(params[6].kind.fits(&kernel));
|
||||
assert!(!params[0].kind.fits(&FieldValue::Number(5000.0)));
|
||||
assert!(!params[1].kind.fits(&FieldValue::Text("wobble".into())));
|
||||
|
||||
// Bounds with a unit after them, keys with a space, fixed labels, colours with and without a default, the log
|
||||
// slider's threshold and a fractional default.
|
||||
let spec = r#"{"amount":0..100 %=50,"width":1..4096 px=100,"ratio":1..500,"wide":1..501,"zero":0..5000,"Black Point":bool,"bpc":bool,"plain":color,"tint":color=#ff0000,"centerX":0..1=0.5} (a note about the result)"#;
|
||||
let params = Param::parse_list(spec);
|
||||
let by = |key: &str| params.iter().find(|p| p.key == key).unwrap_or_else(|| panic!("a row {key}"));
|
||||
assert_eq!(params.len(), 10, "the note after the object adds no row");
|
||||
assert_eq!(by("amount").kind, ParamKind::range(0.0, 100.0, 50.0, SliderScale::Linear));
|
||||
assert_eq!(by("width").kind, ParamKind::range(1.0, 4096.0, 100.0, SliderScale::Log));
|
||||
assert_eq!(by("ratio").kind, ParamKind::range(1.0, 500.0, 1.0, SliderScale::Linear), "a ratio of exactly 500 stays linear");
|
||||
assert_eq!(by("wide").kind, ParamKind::range(1.0, 501.0, 1.0, SliderScale::Log));
|
||||
assert_eq!(by("zero").kind, ParamKind::range(0.0, 5000.0, 0.0, SliderScale::Linear), "a minimum of 0 stays linear");
|
||||
assert_eq!(by("Black Point").label.as_str(), "Black Point", "a key with a space is kept");
|
||||
assert_eq!(by("bpc").label.as_str(), "Black Point Compensation");
|
||||
assert_eq!(by("plain").kind.default_value(), None, "a colour without a default is unset");
|
||||
assert_eq!(by("tint").kind.default_value(), Some(FieldValue::Color([1.0, 0.0, 0.0])));
|
||||
let centre = by("centerX");
|
||||
assert_eq!(centre.kind, ParamKind::range(0.0, 1.0, 0.5, SliderScale::Linear), "a 0..1 range keeps its fractional default");
|
||||
assert_eq!(centre.kind.default_value(), Some(FieldValue::Number(0.5)));
|
||||
}
|
||||
|
||||
/// A fixture showing `params` as rows over `values`.
|
||||
@@ -49,9 +72,10 @@ fn rows(params: Vec<Param>, values: &Rc<RefCell<DialogFields>>) -> Fixture {
|
||||
// while its condition holds; a tooltip is the description of its row.
|
||||
#[trial]
|
||||
fn rows_follow_their_predicates_and_carry_their_tooltip() {
|
||||
let source = ParamKind::choice(vec![("file".into(), "File".into()), ("folder".into(), "Folder".into())], None);
|
||||
let source = ParamKind::choice(vec![("file".into(), "File".into()), ("folder".into(), "Folder".into()), ("url".into(), "Link".into())], None);
|
||||
let params = vec![
|
||||
Param::new("source", "Source", source),
|
||||
Param::new("detail", "Detail", ParamKind::int(Some(0), Some(9), 1)).enabled_when_in("source", ["file", "folder"]),
|
||||
Param::new("input", "Input Folder", ParamKind::text("")).visible_when("source", "folder"),
|
||||
Param::new("custom", "Custom", ParamKind::bool(false)).tooltip("Use your own quality"),
|
||||
Param::new("quality", "Quality", ParamKind::int(Some(0), Some(12), 8)).enabled_when("custom", true),
|
||||
@@ -70,6 +94,14 @@ fn rows_follow_their_predicates_and_carry_their_tooltip() {
|
||||
values.borrow_mut().set("source", FieldValue::Text("folder".into()));
|
||||
fixture.settle();
|
||||
assert!(fixture.by_label("Input Folder").is_some(), "shown once the source is a folder");
|
||||
|
||||
// A row enabled for two of three values takes input for both and greys out for the third.
|
||||
let detail = fixture.by_label("Detail").expect("the detail row");
|
||||
assert!(!fixture.tree().is_disabled_key(detail.node), "enabled for the folder source");
|
||||
values.borrow_mut().set("source", FieldValue::Text("url".into()));
|
||||
fixture.settle();
|
||||
let detail = fixture.by_label("Detail").expect("the detail row");
|
||||
assert!(fixture.tree().is_disabled_key(detail.node), "disabled for the third value");
|
||||
}
|
||||
|
||||
// A read-only row shows its text, selectable, and keeps no value.
|
||||
@@ -83,3 +115,76 @@ fn a_read_only_row_shows_its_text_and_keeps_no_value() {
|
||||
assert!(shown, "the text is the value of a node");
|
||||
assert!(!values.borrow().contains("make"), "the row keeps no value");
|
||||
}
|
||||
|
||||
/// The blend keys work inside the dialog's modal layer, on the first Blend row only: Shift+= steps to the next mode,
|
||||
/// Shift+Alt+M picks Multiply, and a second Blend row does not move.
|
||||
#[trial]
|
||||
fn a_blend_row_steps_and_picks_by_its_keys_inside_the_dialog() {
|
||||
let modes = || -> Vec<(BlendKeyEntry<String>, Label)> {
|
||||
vec![
|
||||
(BlendKeyEntry::new("normal".to_owned(), BlendShortcut::Normal), "Normal".into()),
|
||||
(BlendKeyEntry::new("dissolve".to_owned(), BlendShortcut::Dissolve), "Dissolve".into()),
|
||||
(BlendKeyEntry::new("multiply".to_owned(), BlendShortcut::Multiply), "Multiply".into()),
|
||||
]
|
||||
};
|
||||
let values = Rc::new(RefCell::new(DialogFields::new()));
|
||||
let shown = values.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
// Every frame runs a second pass: a key press steps the mode once, because the pass that takes the press is
|
||||
// the only one that applies it.
|
||||
if ui.ctx().current_pass_index() == 0 {
|
||||
ui.ctx().request_discard("a second pass in the frame");
|
||||
}
|
||||
let params = vec![
|
||||
Param::new("mode", "Mode", ParamKind::blend(modes(), None)),
|
||||
Param::new("other", "Other Mode", ParamKind::blend(modes(), None)),
|
||||
];
|
||||
let _ = ParamDialog::new("blend", "Blend", params).values(Bind::bound(&mut *shown.borrow_mut())).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
let held = |key: &str| values.borrow().text(key).map(str::to_owned);
|
||||
assert_eq!(held("mode").as_deref(), Some("normal"), "a Blend row opens on its first mode");
|
||||
|
||||
fixture.key(Key::Equals, Modifiers::SHIFT).settle();
|
||||
assert_eq!(held("mode").as_deref(), Some("dissolve"), "Shift+= steps to the next mode");
|
||||
fixture.key(Key::M, Modifiers::SHIFT | Modifiers::ALT).settle();
|
||||
assert_eq!(held("mode").as_deref(), Some("multiply"), "Shift+Alt+M picks Multiply");
|
||||
assert_eq!(held("other").as_deref(), Some("normal"), "a second Blend row does not move");
|
||||
}
|
||||
|
||||
/// A pattern row shows the first pattern for a stored id the rows lack without writing it, a pick writes the pattern's
|
||||
/// id, and a group header takes no pick.
|
||||
#[trial]
|
||||
fn a_pattern_row_picks_its_pattern() {
|
||||
let rows = vec![
|
||||
PresetRow::group("nature".to_owned(), "Nature", 0),
|
||||
PresetRow::item("grass".to_owned(), "Grass", 1),
|
||||
PresetRow::item("sand".to_owned(), "Sand", 1),
|
||||
];
|
||||
let values = Rc::new(RefCell::new(DialogFields::from_pairs([("fill", "ghost")])));
|
||||
let shown = values.clone();
|
||||
let params = vec![Param::new("fill", "Fill", ParamKind::pattern(None))];
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = ParamRows::new("Form", ¶ms, Bind::bound(&mut *shown.borrow_mut())).patterns(&rows).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1200.0, 800.0));
|
||||
fixture.settle();
|
||||
let held = || values.borrow().text("fill").map(str::to_owned);
|
||||
assert_eq!(held().as_deref(), Some("ghost"), "showing the first pattern writes nothing");
|
||||
|
||||
let field = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the pattern field shows");
|
||||
assert_eq!(fixture.tree().value_of(field.node), Some("Grass"), "a stored id the rows lack shows the first pattern");
|
||||
fixture.click(&field);
|
||||
fixture.idle(3);
|
||||
let sand = fixture.by_label("Sand").expect("the popover lists the patterns");
|
||||
fixture.click(&sand);
|
||||
fixture.idle(3);
|
||||
assert_eq!(held().as_deref(), Some("sand"), "a pick writes the pattern's id");
|
||||
|
||||
fixture.click(&field);
|
||||
fixture.idle(3);
|
||||
let group = fixture.by_label("Nature").expect("the popover lists the group");
|
||||
fixture.click(&group);
|
||||
fixture.idle(3);
|
||||
assert_eq!(held().as_deref(), Some("sand"), "a group header writes nothing");
|
||||
}
|
||||
|
||||
@@ -14,8 +14,8 @@ use egui::{Rect, Response, Vec2};
|
||||
/// The selection part that shows the text.
|
||||
const TEXT: PartKey = PartKey::new("text");
|
||||
|
||||
/// The style of selectable text: padding from the control metrics, no surface, the body role in the normal text
|
||||
/// colour.
|
||||
/// The style of selectable text: padding from the control metrics when it is inset like a field's text, no surface,
|
||||
/// the body role in the normal text colour.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct SelectableStyle {
|
||||
@@ -27,19 +27,23 @@ pub struct SelectableStyle {
|
||||
|
||||
/// Read-only text the user focuses with a press to select and copy, which Tab passes over. Its node is a label named
|
||||
/// by `label`, with the text as its value.
|
||||
#[derive(crate::contract::Component)]
|
||||
#[derive(crate::contract::Component, crate::contract::Props)]
|
||||
pub struct SelectableText {
|
||||
#[common]
|
||||
common: Common,
|
||||
text: String,
|
||||
wrap: Wrap,
|
||||
mono: bool,
|
||||
/// The text is inset by the control padding, as the text of a field.
|
||||
#[style_key]
|
||||
#[prop(flag)]
|
||||
field_inset: bool,
|
||||
}
|
||||
|
||||
impl SelectableText {
|
||||
/// Selectable `text` named `label`.
|
||||
pub fn new(label: impl Into<Label>, text: &str) -> Self {
|
||||
SelectableText { common: Common::new(), text: text.to_owned(), wrap: Wrap::Line, mono: false }.label(label)
|
||||
SelectableText { common: Common::new(), text: text.to_owned(), wrap: Wrap::Line, mono: false, field_inset: false }.label(label)
|
||||
}
|
||||
|
||||
/// The text wraps over several lines.
|
||||
@@ -69,12 +73,13 @@ impl Component for SelectableText {
|
||||
type Style = SelectableStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: SelectableTextStyleKey) -> SelectableStyle {
|
||||
fn style(cx: &StyleCx<'_>, key: SelectableTextStyleKey) -> SelectableStyle {
|
||||
let text = &cx.tokens.color.text;
|
||||
let color = cx.color(text.normal);
|
||||
let off = States::new(color, color, color, cx.color(text.disabled));
|
||||
let metrics = if key.field_inset { Metrics::new().padding(Insets::horizontal(cx.control().pad_x)) } else { Metrics::new() };
|
||||
SelectableStyle {
|
||||
metrics: Metrics::new().padding(Insets::horizontal(cx.control().pad_x)),
|
||||
metrics,
|
||||
text: TextLook::new(TypeRole::Body, Stateful::new(color).off(off)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -591,8 +591,8 @@ Along a height its parent sizes from its content, a container that fills takes i
|
||||
|
||||
| Crate | Components |
|
||||
| --- | --- |
|
||||
| `craft-color` | ColorPicker, ColorArea, ColorWheel, ColorDisc, ColorRamp, ColorPopover, SwatchPair, SwatchPalette |
|
||||
| `craft-draw` | GradientSwatch, GradientEditor, GradientPalette, gradient line, TransformFields, transform box, bezier paths, crop frame, perspective crop quad, pen draft |
|
||||
| `craft-color` | ColorPicker, ColorArea, ColorWheel, ColorDisc, ColorRamp, ColorPopover, SwatchPair, SwatchPalette, GradientEditor, the gradient stop rules and the gradient model |
|
||||
| `craft-draw` | GradientSwatch, GradientPalette, gradient line, TransformFields, transform box, bezier paths, crop frame, perspective crop quad, pen draft |
|
||||
| `craft-imaging` | LevelsEditor, CurveEditor, Histogram, warp grid |
|
||||
| `craft-layers` | Layers panel, rows, filter bar, thumbnails |
|
||||
| `craft-browse` | Tile grid, media bin, places, thumbnails, relink |
|
||||
@@ -1187,6 +1187,7 @@ Colour for apps: picker, wells, swatch tables, ramps, hex field. New on the bran
|
||||
| `ui::choice` | Colour choice: named colours plus Custom | exists |
|
||||
| `ui::disc`, `ui::wheel`, `ui::ramp` | Colour disc, wheel and ramp | exists |
|
||||
| `ui::droppers`, `ui::eyedropper`, `ui::samplers`, `ui::screen_picker` | Dialog droppers, eyedropper tool, sample points, screen picker | exists |
|
||||
| `ui::gradient` | `GradientEditor`, the stop rules and the gradient model | exists |
|
||||
| `ui::harmony` | Harmony wheel | exists |
|
||||
| `ui::hex`, `ui::readout` | Hex field and channel readout | exists |
|
||||
| `ui::lut_picker` | LUT picker | exists |
|
||||
@@ -1229,7 +1230,7 @@ Native file and message dialogs that never block the event loop.
|
||||
| `native` | Native dialogs on a worker thread | exists |
|
||||
| `save` | Save and Save As flow with guards | exists |
|
||||
| `service` | File dialog service behind the host's files | exists |
|
||||
| `ui::file_list`, `ui::path_field` | File list picker; path field with Browse | exists |
|
||||
| `ui::path_field` | Path field with Browse | exists |
|
||||
|
||||
#### craft-docpath
|
||||
|
||||
@@ -1251,7 +1252,7 @@ Vector and shape tools, pen, stroke, gradient, crop, measure, symmetry, brush pr
|
||||
| `ui::connector` | Connector tool, overlay and bar | exists |
|
||||
| `ui::corner` | Corner radius widgets | exists |
|
||||
| `ui::crop` | Crop frame and crop tool | exists |
|
||||
| `ui::gradient` | Gradient swatch, editor, palette and on-canvas gradient line | exists |
|
||||
| `ui::gradient` | Gradient swatch, palette and on-canvas gradient line | exists |
|
||||
| `ui::measure` | Ruler tool, bar and box distances | exists |
|
||||
| `ui::pattern`, `ui::picture_fill` | Pattern fill picker; picture fill options | exists |
|
||||
| `ui::pen` | Pen draft and bezier paths | exists |
|
||||
@@ -1368,7 +1369,6 @@ Raster image editing. New on the branch (step 1). Core at the root, widgets in `
|
||||
| `trace` | Mask outline tracing | exists |
|
||||
| `ui::adjust` | Levels editor and the colour adjustment editors | exists |
|
||||
| `ui::live_preview` | Live preview of an adjustment: keys, lanes, proxy plan |
|
||||
| `ui::blend_keys` | Blend-mode key picker | exists |
|
||||
| `ui::blur_pins` | Blur pins on the canvas | exists |
|
||||
| `ui::channels` | Channels panel | exists |
|
||||
| `ui::fill` | Fill-from-surroundings workspace | exists |
|
||||
@@ -1740,8 +1740,9 @@ The derives and macros of the UI library: `Component`, `Props`, `ComponentStyle`
|
||||
| Module | Holds | State |
|
||||
| --- | --- | --- |
|
||||
| `patterns::dock` | `DockArea`, `DockPanels`, `PaneArea`, `WorkspaceSwitcher` | exists |
|
||||
| `patterns::form_dialogs` | Form dialogs, among them `PdfExportDialog` over `craft-pdf`'s settings | exists |
|
||||
| `patterns::panels` | `Inspector`, `CommandPalette`, `Tour` | exists |
|
||||
| `patterns::blend_keys` | Blend-mode key picker | exists |
|
||||
| `patterns::form_dialogs` | Form dialogs, among them `PdfExportDialog` over `craft-pdf`'s settings; `FileListPicker`, `FileList`, `FileListMode`, `FileListPickerOutput`, `FileListWords` | exists |
|
||||
| `patterns::panels` | `Inspector`, `CommandPalette`, `Tour`, `HistoryPanel`, `ModifierKeysPanel` | exists |
|
||||
| `patterns::preferences` | `PreferencesWindow` and its pages | exists |
|
||||
| `patterns::presets` | The preset browser over a generic preset library model | exists |
|
||||
|
||||
|
||||
@@ -10,21 +10,21 @@ new_module = "craft_dialogs::ui"
|
||||
[[type]]
|
||||
name = "FileListPicker"
|
||||
old = "craft_dialogs::ui::FileListPicker"
|
||||
new = "craft_dialogs::ui::FileListPicker"
|
||||
new = "craft_ui::patterns::form_dialogs::FileListPicker"
|
||||
status = "same"
|
||||
note = "A pattern over one `List<usize>`: `FileListPicker::new(label, Bind<FileList>)` with `request`, `folder_mode`, `open_files`, `folder_files` and `info` as props. `show(ui) -> FileListPickerOutput`. The ticket of Browse is kept in the picker's container; Delete and Backspace remove the selected file and Alt+Up and Alt+Down move it (the list's contract keys). Folder mode is the same list over the folder's files with no selection. The buttons sit under the list, not beside it."
|
||||
|
||||
[[type]]
|
||||
name = "FileList"
|
||||
old = "craft_dialogs::ui::FileList"
|
||||
new = "craft_dialogs::ui::FileList"
|
||||
new = "craft_ui::patterns::form_dialogs::FileList"
|
||||
status = "same"
|
||||
note = "`#[non_exhaustive]`: build it with `FileList::default()` and set the fields. `problem` takes `&FileListWords`."
|
||||
|
||||
[[type]]
|
||||
name = "FileListMode"
|
||||
old = "craft_dialogs::ui::FileListMode"
|
||||
new = "craft_dialogs::ui::FileListMode"
|
||||
new = "craft_ui::patterns::form_dialogs::FileListMode"
|
||||
status = "same"
|
||||
note = "`#[non_exhaustive]`."
|
||||
|
||||
@@ -38,7 +38,7 @@ note = "Replaced by `FileListPickerOutput { response, changed, browsing }`."
|
||||
[[type]]
|
||||
name = "FileListPickerOutput"
|
||||
old = ""
|
||||
new = "craft_dialogs::ui::FileListPickerOutput"
|
||||
new = "craft_ui::patterns::form_dialogs::FileListPickerOutput"
|
||||
status = "replaced"
|
||||
note = "`{ response, changed, browsing: Option<PickId> }`; the old response had no `response` field."
|
||||
|
||||
@@ -52,7 +52,7 @@ note = "Replaced by `FileListWords`. The word ids move from `fileList.*` to `fil
|
||||
[[type]]
|
||||
name = "FileListWords"
|
||||
old = ""
|
||||
new = "craft_dialogs::ui::FileListWords"
|
||||
new = "craft_ui::patterns::form_dialogs::FileListWords"
|
||||
status = "replaced"
|
||||
note = "The words of the file list picker (`fileListPicker.*`), read with `Env::of(ui).words::<FileListWords>()`."
|
||||
|
||||
|
||||
Reference in New Issue
Block a user