merge-fwe: FW16 E6: PathSetting, a Preferences path row over the settings draft (Browse through the host's file service, keys naming list entries); PathRow files host picks itself, PathField uses it

This commit is contained in:
aiongg
2026-11-16 12:44:56 +00:00
parent 6c8a1861bd
commit 6e7c1d4e7c
8 changed files with 318 additions and 48 deletions
+6 -23
View File
@@ -3,7 +3,7 @@
use craft_behavior::{EditEvent, Mixed};
use craft_host::target::Caps;
use craft_host::{PickId, PickRequest};
use craft_ui::contract::{Bind, Held, NoValue, Outcome, Remember as _, ShowContainer as _, Validity};
use craft_ui::contract::{Bind, Held, NoValue, Outcome, Props as _, ShowContainer as _, Validity};
use craft_ui::form::Field;
use craft_ui::patterns::form_dialogs::PathRow;
use craft_ui::runtime::env::{Env, Label, Message};
@@ -17,10 +17,6 @@ craft_ui::words! {
}
}
/// The pick the field is waiting for, kept in the field's container while it is shown.
#[derive(Clone, Copy, Default)]
struct Ticket(Option<PickId>);
/// What the path field reports.
#[derive(Debug)]
#[non_exhaustive]
@@ -44,8 +40,8 @@ impl Outcome for PathFieldOutput {
}
/// A label, then the path row (a text field with the path and a Browse button) over the bound path. Typing commits on
/// Enter or focus loss; Browse queues `request` through `host.files()` and the answer fills the field on a later pass
/// (the field matches tickets, so several fields can browse in turn). Tab order: field, then Browse. With `must_exist`
/// Enter or focus loss; Browse queues `request` through `host.files()` ([`PathRow::pick`]) and the answer fills the
/// field on a later pass (rows match tickets, so several fields can browse in turn). Tab order: field, then Browse. With `must_exist`
/// set, a path that does not exist shows the not-found message under the field.
#[must_use = "show the field with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
@@ -74,27 +70,14 @@ impl<'a> PathField<'a> {
let mut browsing = None;
let shown = Field::new(label.clone()).show(ui, |ui, cx| {
let before = held.read(cx).unwrap_or_default();
let host = cx.env.host().cloned();
let looks = must_exist && cx.env.shell().caps.contains(Caps::FILE_SYSTEM);
let not_found = words.not_found.clone();
let check = move |path: &String| {
if looks && path_is_missing(path) { Validity::Warn(Message::new(not_found.clone())) } else { Validity::Ok }
};
let mut answered = None;
if let Some(ticket) = cx.memory::<Ticket>().0
&& let Some(picked) = cx.take_pick_answer(ticket)
{
cx.memory::<Ticket>().0 = None;
answered = picked.first_path().map(|path| path.to_string_lossy().into_owned());
}
let row = PathRow::new(label.clone(), Bind::given(before.clone()).check(check)).show(ui);
if row.browse
&& let Some(host) = &host
{
let id = host.files().pick(request.clone());
cx.memory::<Ticket>().0 = Some(id);
browsing = Some(id);
}
let row = PathRow::new(label.clone(), Bind::given(before.clone()).check(check)).pick(request.clone()).show(ui);
browsing = row.browsing;
let answered = row.picked;
let typed = row
.edit
.into_iter()
@@ -4,11 +4,12 @@
mod stories;
use crate::buttons::Button;
use crate::contract::{Bind, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing, clicked};
use crate::contract::{Bind, NoValue, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _, Sizing, clicked};
use crate::layout_components::Row;
use crate::runtime::env::{Env, Label};
use crate::text::TextField;
use craft_behavior::EditEvents;
use craft_host::{PickId, PickRequest};
use egui::{Response, Ui};
craft_ui::words! {
@@ -27,7 +28,13 @@ pub struct PathRowOutput {
/// The text field's edits of the path in this pass; a given value is applied by the caller.
pub edit: EditEvents<String>,
/// Browse was pressed this pass: the host asks for a path by its own route and writes the answer into the value.
/// With [`PathRow::pick`] the row has asked the host's file service itself.
pub browse: bool,
/// With [`PathRow::pick`]: Browse filed this pick through the host's file service this pass.
pub browsing: Option<PickId>,
/// With [`PathRow::pick`]: the path the host's file service answered, on the pass the answer arrived. The caller
/// writes it into the value as a set.
pub picked: Option<String>,
}
impl Outcome for PathRowOutput {
@@ -40,8 +47,10 @@ impl Outcome for PathRowOutput {
/// A text field with the path, taking the row's room, and a Browse button after it, for a row whose enclosing `Field`
/// shows the label. Typing edits the bound path; the binding's check shows under the field (a file that is not there).
/// A press on Browse is reported, and the host files its pick request: a `PathRequest` in a form dialog, or a pick from
/// the host's file service. Tab order: the field, then Browse.
/// A press on Browse is reported, and the host files its pick request: a `PathRequest` in a form dialog. With
/// [`pick`](Self::pick) the row files the pick through the host's file service itself, keeps the ticket while it is shown
/// and reports the answer in [`PathRowOutput::picked`] (rows match tickets, so several can browse in turn). Tab order:
/// the field, then Browse.
#[must_use = "show the row with `show`"]
#[derive(crate::contract::Pattern, crate::contract::Props)]
pub struct PathRow<'a> {
@@ -53,28 +62,52 @@ pub struct PathRow<'a> {
/// Shown in the empty field.
#[prop(into)]
placeholder: Option<Label>,
/// What Browse asks the host's file service to pick; without it the caller files the request.
#[prop(into)]
pick: Option<PickRequest>,
}
/// The pick the row is waiting for, kept in the row's container while it is shown.
#[derive(Clone, Copy, Default)]
struct Ticket(Option<PickId>);
impl<'a> PathRow<'a> {
/// A row over the path `value`, its field named `name`.
pub fn new(name: impl Into<Label>, value: Bind<'a, String>) -> Self {
PathRow { name: name.into(), value, button: None, placeholder: None }
PathRow { name: name.into(), value, button: None, placeholder: None, pick: None }
}
/// Shows the row.
pub fn show(self, ui: &mut Ui) -> PathRowOutput {
let PathRow { name, mut value, button, placeholder } = self;
let PathRow { name, mut value, button, placeholder, pick } = self;
let button = button.unwrap_or_else(|| Env::of(ui).words::<PathRowWords>().browse.clone());
let mut edit = EditEvents::new();
let mut browse = false;
let shown = Row::new().show(ui, |ui, _| {
let mut browsing = None;
let mut picked = None;
let shown = Row::new().show(ui, |ui, cx| {
if pick.is_some()
&& let Some(ticket) = cx.memory::<Ticket>().0
&& let Some(answer) = cx.take_pick_answer(ticket)
{
cx.memory::<Ticket>().0 = None;
picked = answer.first_path().map(|path| path.to_string_lossy().into_owned());
}
let mut field = TextField::new(name.clone(), value.reborrowed()).limit(None).sizing(Sizing::FillWidth).id_salt("path");
if let Some(placeholder) = placeholder.clone() {
field = field.placeholder(placeholder);
}
edit = field.show(ui).events;
browse = clicked(&Button::new(button.clone()).id_salt("browse").show(ui));
if browse
&& let Some(request) = &pick
&& let Some(host) = cx.env.host().cloned()
{
let id = host.files().pick(request.clone());
cx.memory::<Ticket>().0 = Some(id);
browsing = Some(id);
}
});
PathRowOutput { response: shown.output, edit, browse }
PathRowOutput { response: shown.output, edit, browse, browsing, picked }
}
}
@@ -13,12 +13,13 @@ pub struct SettingsDraft {
}
impl SettingsDraft {
/// The value at `key` (`"tools.pressureCurve"`), when it is there and fits `V`.
/// The value at `key` (`"tools.pressureCurve"`), when it is there and fits `V`. A part of the key may name a list
/// entry: `"performance.scratchDisks[1].path"`.
pub fn get<V: DeserializeOwned>(&self, key: &str) -> Option<V> {
lookup(&self.table, key)?.clone().try_into().ok()
}
/// Writes `value` at `key`; a value that doesn't serialize is ignored.
/// Writes `value` at `key`; a value that doesn't serialize, or a list entry that is not there, is ignored.
pub fn set<V: Serialize>(&mut self, key: &str, value: &V) {
if let Ok(value) = toml::Value::try_from(value) {
insert(&mut self.table, key, value);
@@ -38,42 +39,102 @@ impl SettingsDraft {
}
}
/// The value at the dotted `key` of `table`.
/// One part of a dotted key: a table entry, then the list indices after it (`disks[2]`). `None` for a malformed part.
fn part(text: &str) -> Option<(&str, Vec<usize>)> {
let Some(open) = text.find('[') else { return Some((text, Vec::new())) };
let (name, mut rest) = text.split_at(open);
let mut indices = Vec::new();
while let Some(inner) = rest.strip_prefix('[') {
let close = inner.find(']')?;
indices.push(inner[..close].parse().ok()?);
rest = &inner[close + 1..];
}
rest.is_empty().then_some((name, indices))
}
/// The entry of `value` at the list `indices`, one list deep per index.
fn entry_mut<'v>(mut value: &'v mut toml::Value, indices: &[usize]) -> Option<&'v mut toml::Value> {
for &i in indices {
value = value.as_array_mut()?.get_mut(i)?;
}
Some(value)
}
/// The value at the dotted `key` of `table`; a part may name a list entry (`scratchDisks.disks[2].path`).
pub(super) fn lookup<'t>(table: &'t toml::Table, key: &str) -> Option<&'t toml::Value> {
let (head, rest) = match key.split_once('.') {
Some((head, rest)) => (head, Some(rest)),
None => (key, None),
};
let value = table.get(head)?;
let (name, indices) = part(head)?;
let mut value = table.get(name)?;
for i in indices {
value = value.as_array()?.get(i)?;
}
match rest {
None => Some(value),
Some(rest) => lookup(value.as_table()?, rest),
}
}
/// Writes `value` at the dotted `key`, creating missing tables on the way; a path through a value that is not a table
/// writes nothing.
/// Writes `value` at the dotted `key`, creating missing tables on the way; a path through a value that is not a table,
/// or to a list entry that is not there, writes nothing.
pub(super) fn insert(table: &mut toml::Table, key: &str, value: toml::Value) {
match key.split_once('.') {
None => {
table.insert(key.to_owned(), value);
}
Some((head, rest)) => {
if let toml::Value::Table(inner) = table.entry(head).or_insert_with(|| toml::Value::Table(toml::Table::new())) {
let (head, rest) = match key.split_once('.') {
Some((head, rest)) => (head, Some(rest)),
None => (key, None),
};
let Some((name, indices)) = part(head) else { return };
if indices.is_empty() && rest.is_none() {
table.insert(name.to_owned(), value);
return;
}
let slot = if indices.is_empty() {
table.entry(name).or_insert_with(|| toml::Value::Table(toml::Table::new()))
} else {
let Some(list) = table.get_mut(name) else { return };
let Some(entry) = entry_mut(list, &indices) else { return };
entry
};
match rest {
None => *slot = value,
Some(rest) => {
if let toml::Value::Table(inner) = slot {
insert(inner, rest, value);
}
}
}
}
/// Removes the value at the dotted `key`; a missing path removes nothing.
/// Removes the value at the dotted `key`; a key ending in a list entry removes that entry. A missing path removes
/// nothing.
pub(super) fn remove(table: &mut toml::Table, key: &str) {
match key.split_once('.') {
None => {
table.remove(key);
let (head, rest) = match key.split_once('.') {
Some((head, rest)) => (head, Some(rest)),
None => (key, None),
};
let Some((name, indices)) = part(head) else { return };
let Some((&last, outer)) = indices.split_last() else {
match rest {
None => {
table.remove(name);
}
Some(rest) => {
if let Some(toml::Value::Table(inner)) = table.get_mut(name) {
remove(inner, rest);
}
}
}
Some((head, rest)) => {
if let Some(toml::Value::Table(inner)) = table.get_mut(head) {
return;
};
let Some(list) = table.get_mut(name).and_then(|list| entry_mut(list, outer)).and_then(toml::Value::as_array_mut) else { return };
match rest {
None if last < list.len() => {
list.remove(last);
}
None => {}
Some(rest) => {
if let Some(toml::Value::Table(inner)) = list.get_mut(last) {
remove(inner, rest);
}
}
@@ -5,6 +5,7 @@
//! from its settings and its draft. The library keeps no copy of the values.
//! - [`PreferencesModel`]: what the app implements: pages, draft, apply, cancel, reset, custom rows and nested dialogs.
//! - [`PreferencesWords`]: every caption of the window.
//! - [`PathSetting`]: a path setting for a custom row or page, typed or picked through the host's file service.
//! - [`SettingsDocument`]: a [`PreferencesModel`] built from the app's settings struct, one row per setting by type,
//! labels from the key, with [`SettingRule`]s and the [`StandardPage`]s.
//! - [`matches`](fn@matches), [`list_pages`], [`row_shown`], [`shown_position`]: the search rule on the shared matcher,
@@ -24,7 +25,10 @@ pub use words::{PreferencesWords, SettingsDocumentWords};
// The window, its body and its rows.
mod body;
mod path_setting;
mod rows;
mod window;
pub use path_setting::{PathSetting, PathSettingOutput};
pub use window::{DEFAULT_SIZE, MIN_SIZE, PreferencesState, PreferencesWindow};
@@ -0,0 +1,89 @@
//! `PathSetting`: a path setting of Preferences, typed or picked through the host's file service, kept in the draft.
#[cfg(feature = "testing")]
mod stories;
use super::SettingsDraft;
use crate::contract::{Bind, NoValue, Outcome, Props as _, ShowContainer as _};
use crate::form::Field;
use crate::patterns::form_dialogs::PathRow;
use crate::runtime::env::Label;
use craft_behavior::EditEvent;
use craft_host::{PickId, PickRequest};
use egui::{Response, Ui};
/// What a path setting reports.
#[derive(Debug)]
#[non_exhaustive]
pub struct PathSettingOutput {
/// The row's response.
pub response: Response,
/// The draft value changed this pass: a typed path was committed or the host's answer arrived.
pub changed: bool,
/// Browse filed this pick through the host's file service this pass.
pub browsing: Option<PickId>,
}
impl Outcome for PathSettingOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// A path setting for a custom row or page of Preferences ([`CustomSettings`](super::CustomSettings)): the label, then a
/// text field with the path and a Browse… button, over the draft value at `key`. A part of the key may name a list
/// entry (`performance.scratchDisks[1].path`), so each entry of a list setting gets its own row. A typed path is
/// written into the draft when it is committed (Enter or focus loss); Browse asks the host's file service for
/// `request` ([`PathRow::pick`]) and the answer is written into the draft on the pass it arrives. Only `key` changes,
/// so Apply writes just that setting. Tab order: the field, then Browse.
#[must_use = "show the setting with `show`"]
#[derive(crate::contract::Pattern, crate::contract::Props)]
pub struct PathSetting<'a> {
label: Label,
key: &'a str,
draft: &'a mut SettingsDraft,
request: PickRequest,
/// Shown in the empty field.
#[prop(into)]
placeholder: Option<Label>,
}
impl<'a> PathSetting<'a> {
/// The setting at `key` of `draft`, labelled `label`; Browse asks the host to pick `request`.
pub fn new(label: impl Into<Label>, key: &'a str, draft: &'a mut SettingsDraft, request: PickRequest) -> Self {
PathSetting { label: label.into(), key, draft, request, placeholder: None }
}
/// Shows the setting.
pub fn show(self, ui: &mut Ui) -> PathSettingOutput {
let PathSetting { label, key, draft, request, placeholder } = self;
let mut changed = false;
let mut browsing = None;
let shown = Field::new(label.clone()).id_salt(key).show(ui, |ui, _| {
let before: String = draft.get(key).unwrap_or_default();
let mut row = PathRow::new(label.clone(), Bind::given(before.clone())).pick(request.clone());
if let Some(placeholder) = placeholder.clone() {
row = row.placeholder(placeholder);
}
let row = row.show(ui);
browsing = browsing.or(row.browsing);
let typed = row
.edit
.into_iter()
.filter_map(|event| match event {
EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } => Some(after),
_ => None,
})
.next_back();
if let Some(after) = typed.or(row.picked)
&& after != before
{
draft.set(key, &after);
changed = true;
}
});
PathSettingOutput { response: shown.output, changed, browsing }
}
}
@@ -0,0 +1,25 @@
//! Stories of the path setting.
use super::PathSetting;
use crate::patterns::preferences::SettingsDraft;
use craft_host::PickRequest;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
fn draft(path: &str) -> SettingsDraft {
let mut draft = SettingsDraft::default();
draft.set("integrations.readRoot", &path);
draft
}
#[story(PathSetting<'static>, covers = [Default], drive = Drive::Never)]
fn path_setting_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let draft = data.value("empty", draft(""));
PathSetting::new("Folder agents can open from", "integrations.readRoot", draft, PickRequest::folder("agents")).placeholder("None").show(ui).into()
}
#[story(PathSetting<'static>, covers = [], drive = Drive::Never)]
fn path_setting_filled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let draft = data.value("filled", draft("/photos/agents"));
PathSetting::new("Folder agents can open from", "integrations.readRoot", draft, PickRequest::folder("agents")).show(ui).into()
}
@@ -2,3 +2,4 @@
//! window's answers and the hex codec.
mod model;
mod path_setting;
@@ -0,0 +1,74 @@
//! `PathSetting` over the settings draft, and draft keys that name a list entry.
use craft_host::{AppInfo, Host, PickId, PickRequest, Picked, ScriptedFiles};
use craft_ui::contract::Role;
use craft_ui::patterns::preferences::{PathSetting, SettingsDraft};
use craft_ui::testing::{Fixture, trial};
use serde::{Deserialize, Serialize};
use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
struct Disk {
enabled: bool,
path: String,
}
fn disks(paths: &[&str]) -> Vec<Disk> {
paths.iter().map(|path| Disk { enabled: true, path: (*path).to_owned() }).collect()
}
/// A key part may name a list entry: reads and writes reach that entry only, a write to an entry that is not there
/// changes nothing, and removing an entry removes it from the list.
#[trial]
fn draft_keys_name_list_entries() {
let mut draft = SettingsDraft::default();
draft.set("performance.scratchDisks", &disks(&["/a", "/b"]));
assert_eq!(draft.get::<String>("performance.scratchDisks[1].path").as_deref(), Some("/b"));
draft.set("performance.scratchDisks[1].path", &"/c");
assert_eq!(draft.get::<Vec<Disk>>("performance.scratchDisks"), Some(disks(&["/a", "/c"])));
draft.set("performance.scratchDisks[5].path", &"/x");
assert_eq!(draft.get::<Vec<Disk>>("performance.scratchDisks"), Some(disks(&["/a", "/c"])), "no entry 5");
assert_eq!(draft.get::<String>("performance.scratchDisks[x].path"), None, "a malformed index names nothing");
draft.remove("performance.scratchDisks[0]");
assert_eq!(draft.get::<Vec<Disk>>("performance.scratchDisks"), Some(disks(&["/c"])));
}
/// Browse on one entry's row asks the host's file service; the answer lands in that entry of the draft and nowhere else,
/// once, and a typed path commits into the draft too.
#[trial]
fn a_path_setting_writes_the_picked_folder_into_its_draft_entry() {
let files = Arc::new(ScriptedFiles::held());
let draft = Rc::new(RefCell::new(SettingsDraft::default()));
draft.borrow_mut().set("performance.scratchDisks", &disks(&["/a", "/b"]));
let changes = Rc::new(Cell::new(0usize));
let ticket = Rc::new(Cell::new(None::<PickId>));
let (held, counted, issued) = (Rc::clone(&draft), Rc::clone(&changes), Rc::clone(&ticket));
let mut fixture = Fixture::new(move |ui| {
let mut draft = held.borrow_mut();
for (i, label) in ["Disk 1", "Disk 2"].into_iter().enumerate() {
let key = format!("performance.scratchDisks[{i}].path");
let out = PathSetting::new(label, &key, &mut draft, PickRequest::folder("scratch")).show(ui);
if out.browsing.is_some() {
issued.set(out.browsing);
}
if out.changed {
counted.set(counted.get() + 1);
}
}
});
fixture.host(Arc::new(Host::builder(AppInfo { id: "test", name: "Test", version: "1.0" }).files(files.clone()).build()));
fixture.settle();
let browse: Vec<_> =
fixture.by_role(Role::BUTTON).into_iter().filter(|button| fixture.tree().name_of(button.node) == Some("Browse…")).collect();
assert_eq!(browse.len(), 2, "one Browse per entry");
fixture.click(&browse[1]);
fixture.settle();
let id = ticket.get().expect("Browse filed a pick");
assert!(files.answer_to(id, Picked::Paths(vec![PathBuf::from("/scratch")])), "the pick is open");
fixture.idle(3);
assert_eq!(draft.borrow().get::<Vec<Disk>>("performance.scratchDisks"), Some(disks(&["/a", "/scratch"])));
assert_eq!(changes.get(), 1, "the answer is written once");
}