Merge branches 'tc/edit', 'tc/store' and 'tc/crate' into tc/wave1

This commit is contained in:
aiongg
2026-11-17 16:20:04 +00:00
31 changed files with 403 additions and 50 deletions
+1
View File
@@ -198,6 +198,7 @@ craft-tiff = { path = "crates/tiff" }
craft-metadata = { path = "crates/metadata" }
craft-table = { path = "crates/table" }
craft-theme = { path = "crates/theme" }
craft-theme-editor = { path = "crates/theme-editor" }
craft-theme-store = { path = "crates/theme-store" }
craft-ui = { path = "crates/ui" }
craft-ui-canvas = { path = "crates/ui-canvas" }
+4
View File
@@ -55,6 +55,7 @@ craft-review = { workspace = true, optional = true }
craft-table = { workspace = true, optional = true }
craft-text = { workspace = true, optional = true }
craft-timeline = { workspace = true, optional = true }
craft-theme-editor = { workspace = true, optional = true }
craft-theme-store = { workspace = true, optional = true }
craft-update = { workspace = true, optional = true }
craft-vectorcraft-format = { workspace = true, optional = true }
@@ -234,6 +235,7 @@ screen-testing = [
"craft-review?/screen-testing",
"craft-table?/screen-testing",
"craft-text?/screen-testing",
"craft-theme-editor?/screen-testing",
"craft-theme-store?/screen-testing",
"craft-timeline?/screen-testing",
"craft-update?/screen-testing",
@@ -759,6 +761,8 @@ texture-parallel = ["texture", "craft-texture/parallel"]
tga = ["dep:craft-tga"]
theme-editor = ["dep:craft-theme-editor"]
theme-store = ["dep:craft-theme-store"]
tiff = ["dep:craft-tiff"]
+2
View File
@@ -314,6 +314,8 @@ pub use craft_texture as texture;
#[cfg(feature = "tga")]
pub use craft_tga as tga;
pub use craft_theme as theme;
#[cfg(feature = "theme-editor")]
pub use craft_theme_editor as theme_editor;
#[cfg(feature = "theme-store")]
pub use craft_theme_store as theme_store;
#[cfg(feature = "tiff")]
+30
View File
@@ -0,0 +1,30 @@
[package]
name = "craft-theme-editor"
description = "The theme editor's panels: the token browser, token detail, problems list and app size overrides over an explained theme."
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
autotests = false
[lib]
# The lib's test target runs the stories registered by the crate.
harness = false
[features]
default = []
# The panels' stories.
screen-testing = ["craft-ui/testing"]
[dependencies]
craft-behavior = { workspace = true }
craft-theme = { workspace = true }
craft-ui = { workspace = true }
egui = { workspace = true }
[dev-dependencies]
craft-ui = { workspace = true, features = ["testing"] }
[lints]
workspace = true
@@ -2,12 +2,15 @@
//! refreshes it for the theme on show and passes what it holds to the panels. The panels edit the workspace's pick
//! and app sizes through bindings, and the Problems view reports the pick it makes.
#![warn(missing_docs)]
mod browser;
mod chip;
mod detail;
mod layer;
mod problems;
mod rows;
#[cfg(feature = "screen-testing")]
mod stories;
mod subject;
mod words;
@@ -19,3 +22,14 @@ pub use problems::{Problems, ProblemsOutput};
pub use rows::Row;
pub use subject::{Pick, ThemeSubject, ThemeWorkspace};
pub use words::summary;
/// The stories this crate registers for the integration binary.
#[cfg(feature = "screen-testing")]
pub mod testing {
craft_ui::testing_registered!();
}
#[cfg(test)]
fn main() {
craft_ui::testing::run(module_path!(), env!("CARGO_PKG_NAME"), &craft_ui::testing::registered_in(env!("CARGO_PKG_NAME")));
}
+3 -3
View File
@@ -30,13 +30,13 @@ match store.update(&base, SelectionChange::pick_theme(&picked)) {
| Item | What it is |
|---|---|
| `SuiteDir` | `CRAFT_SUITE_DIR` (empty: in memory), in memory for isolated apps, else `ArtCraft/themes` in the local config folder |
| `Store` | `load_selection`, `update`, `import`, `delete`, `export`, `library`, `load_theme`, `theme` (a `resolve` lookup) |
| `Store` | `load_selection`, `update`, `import`, `save_theme`, `delete`, `export`, `library`, `load_theme`, `theme` (a `resolve` lookup) |
| `SelectionChange` | the fields the user changed (`theme_light`, `theme_dark`, `mode`, `contrast`, `size`, `text_size`); only these are written, each merged on its own |
| `Accepted` | `suite` (craft-theme's `SuiteChoice`: each field `None` until a user chooses it), `revision`, `library_revision`; serde, for the copy apps keep in their preferences |
| `StoreError` | `Busy`, `Conflict { disk }`, `IdExists`, `InUse`, … ; nothing on disk changed |
| `StoreError` | `Busy`, `Conflict { disk }`, `Changed` (a library file another app saved over), `IdExists`, `InUse`, … ; nothing on disk changed |
| `Problem` | damaged, too new or unreadable files; the store keeps its last accepted state |
| `ThemeRecord`, `ThemeEntry`, `format` | a parsed user theme file (`craft-design-theme` v1, craft-theme's `format`) with its stored bytes, unknown keys included; the library skips files in another format, such as the pilot's `craft-theme` |
| `SuiteClient` | what an app calls: per-frame `sync`, the optimistic `shown` choice, `change`, conflict and failure notices with `apply_mine` and `retry`, the `theme` lookup, `preview` for any theme's picker card |
| `SuiteClient` | what an app calls: per-frame `sync`, the optimistic `shown` choice, `change`, conflict and failure notices with `apply_mine` and `retry`, the `theme` lookup, `preview` for any theme's picker card, `save_theme` and `take_saved` for a theme editor |
| `SuiteWatch`, `Snapshot`, `Op`, `OpOutput` | the store on a worker thread: snapshots by generation, queued operations with results |
| `ui` (feature `ui`) | the Preferences appearance page `AppearancePage` (modes, light and dark theme rows of `ThemeChip`s with favorites, Size and UI Font Size; tokens `theme_chip.*`); feature `screen-testing` adds egui_kittest input tests of the page |
| `FileStamp`, `library_files`, `selection_stamp`, `theme_stamp`, `parse_counts` | cheap change checks for a watcher |
+19 -2
View File
@@ -38,8 +38,8 @@ pub struct LibraryFile {
// Only the disk backend fails these ways; web builds have none.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) enum WriteError {
/// `selection.json` changed between the read under the lock and the rename: another
/// writer ignored the lock (network file systems).
/// The file changed between the read under the lock and the rename: another writer ignored
/// the lock (network file systems). For a theme, also a file that isn't the expected one.
Raced,
Io(io::Error),
}
@@ -209,6 +209,23 @@ impl Backend {
}
}
/// Replaces a theme file whose stamp is `expected` and returns the new file's stamp;
/// [`WriteError::Raced`] when the file is missing or has another stamp.
pub fn replace_theme(&mut self, stem: &str, bytes: &[u8], expected: FileStamp) -> Result<FileStamp, WriteError> {
match self {
Backend::Memory(m) => {
if m.library.get(stem).is_none_or(|(b, s)| mem_stamp(b, *s) != expected) {
return Err(WriteError::Raced);
}
let serial = m.next();
m.library.insert(stem.to_owned(), (Arc::from(bytes), serial));
Ok(mem_stamp(bytes, serial))
}
#[cfg(not(target_arch = "wasm32"))]
Backend::Disk(d) => d.replace_theme(stem, bytes, expected),
}
}
/// Renames a theme to a hidden name that listings skip; `NotFound` when there is none.
pub fn hide_theme(&mut self, stem: &str) -> io::Result<()> {
match self {
+68 -2
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use craft_theme::{SuiteChoice, ThemeDef, ThemeId, ThemePair};
use crate::{Accepted, Op, Problem, SelectionChange, Snapshot, StoreError, SuiteWatch, watch::with_library_theme};
use crate::{Accepted, FileStamp, Op, OpOutput, Problem, SelectionChange, Snapshot, StoreError, SuiteWatch, watch::with_library_theme};
/// A change sent to the watch and not answered yet.
#[derive(Clone, Debug)]
@@ -24,6 +24,9 @@ struct Pending {
/// At most one change is in flight. Picks made meanwhile merge into one queued change (a later
/// pick of a field replaces the earlier one), which goes out with the new accepted state as
/// base when the first result arrives, so quick picks never conflict with each other.
///
/// A theme editor saves with [`save_theme`](Self::save_theme), one save at a time, and takes the
/// answer with [`take_saved`](Self::take_saved).
pub struct SuiteClient {
watch: SuiteWatch,
generation: Option<u64>,
@@ -32,6 +35,9 @@ pub struct SuiteClient {
queued: Option<SelectionChange>,
conflict: Option<(Accepted, SelectionChange)>,
failure: Option<(SelectionChange, StoreError)>,
/// The save in flight: its request id and theme.
saving: Option<(u64, ThemeId)>,
saved: Option<(ThemeId, Result<FileStamp, StoreError>)>,
app_theme: Option<ThemePair>,
/// Open couldn't read `selection.json`: changes wait in the queue for the worker's first
/// snapshot instead of merging against a state nobody read.
@@ -44,7 +50,19 @@ impl SuiteClient {
let snapshot = watch.snapshot();
let app_theme = watch.initial_app_theme().cloned();
let hold = !watch.selection_read();
SuiteClient { watch, generation: None, snapshot, pending: None, queued: None, conflict: None, failure: None, app_theme, hold }
SuiteClient {
watch,
generation: None,
snapshot,
pending: None,
queued: None,
conflict: None,
failure: None,
saving: None,
saved: None,
app_theme,
hold,
}
}
/// An in-memory suite, for app constructors, tests and web builds.
@@ -70,9 +88,57 @@ impl SuiteClient {
}
}
self.settle();
self.settle_save();
true
}
fn settle_save(&mut self) {
let Some((request, _)) = &self.saving else {
return;
};
let request = *request;
let result = match self.snapshot.result(request) {
Some(Ok(OpOutput::Saved(stamp))) => Ok(*stamp),
Some(Err(error)) => Err(error.clone()),
// A save's result is always `Saved`.
Some(Ok(_)) => Err(StoreError::Lost),
// Pushed out of the snapshot by newer results before this sync.
None if self.snapshot.results.first().is_some_and(|(id, _)| *id > request) => Err(StoreError::Lost),
None => return,
};
if let Some((_, id)) = self.saving.take() {
self.saved = Some((id, result));
}
}
/// Saves `bytes` over library theme `id` ([`Store::save_theme`](crate::Store::save_theme)).
/// `expected` is the file's stamp when the app loaded it, or the stamp the last save of it
/// returned. One save at a time: while one is in flight this sends nothing and returns false.
/// The answer of an earlier save not yet taken is dropped.
pub fn save_theme(&mut self, id: ThemeId, bytes: Arc<[u8]>, expected: FileStamp) -> bool {
if self.saving.is_some() {
return false;
}
self.saved = None;
let request = self.watch.request(Op::Save { id: id.clone(), bytes, expected });
self.saving = Some((request, id));
true
}
/// True while a save is in flight.
pub fn is_saving(&self) -> bool {
self.saving.is_some()
}
/// The answer to the last save, once [`sync`](Self::sync) has seen it: the theme and the new
/// file's stamp, the `expected` stamp for its next save. [`StoreError::Changed`] means
/// another app saved over the theme since it was loaded; [`StoreError::Lost`] that the answer
/// was gone before the client looked, and the theme's entry in the snapshot's index shows
/// what is on disk.
pub fn take_saved(&mut self) -> Option<(ThemeId, Result<FileStamp, StoreError>)> {
self.saved.take()
}
fn settle(&mut self) {
let Some(pending) = &self.pending else {
return;
+29 -1
View File
@@ -10,7 +10,7 @@ use craft_theme::{ContrastChoice, ModeChoice, SuiteChoice, TextSize, ThemeId, Th
use super::SuiteClient;
use crate::{
Op, SelectionChange, StoreOptions, SuiteDir, SuiteWatch,
Op, SelectionChange, StoreError, StoreOptions, SuiteDir, SuiteWatch,
testing::{SAMPLE_THEME_ID, SAMPLE_THEME_JSON},
};
@@ -127,3 +127,31 @@ fn a_library_theme_on_its_way_never_shows_the_app_default() {
own.sync();
assert!(!own.is_loading(&id("gone")));
}
#[trial]
fn a_save_through_the_client_reports_the_new_stamp() {
let mut client = SuiteClient::memory();
client.sync();
client.watch().request(Op::Import { bytes: Arc::from(SAMPLE_THEME_JSON.as_bytes()), as_copy: false });
client.sync();
let sample = id(SAMPLE_THEME_ID);
let entry = |client: &SuiteClient| client.snapshot().index.iter().find(|e| e.id == sample).cloned().unwrap();
let loaded = entry(&client).stamp;
let edited: Arc<[u8]> = Arc::from(SAMPLE_THEME_JSON.replace("\"version\": 3", "\"version\": 4").as_bytes());
assert!(client.save_theme(sample.clone(), Arc::clone(&edited), loaded));
// One save at a time.
assert!(!client.save_theme(sample.clone(), Arc::clone(&edited), loaded));
assert!(client.is_saving());
client.sync();
assert!(!client.is_saving());
let (saved, stamp) = client.take_saved().unwrap();
let stamp = stamp.unwrap();
assert_eq!(saved, sample);
assert_eq!((entry(&client).stamp, entry(&client).version), (stamp, 4));
// The stamp from before the save is stale now.
assert!(client.save_theme(sample.clone(), edited, loaded));
client.sync();
assert!(matches!(client.take_saved(), Some((_, Err(StoreError::Changed(_))))));
}
+57 -16
View File
@@ -77,8 +77,24 @@ impl Disk {
pub fn write_selection(&self, bytes: &[u8], expected: Option<&[u8]>) -> Result<(), WriteError> {
let path = self.selection_path();
let guard = Guarded { inner: &*self.fs, path: &path, expected, raced: Cell::new(false) };
match private().atomic_write_custom(&guard, RenameRetry::platform(), &path, bytes) {
self.write_guarded(&path, bytes, Expected::Bytes(expected))
}
pub fn replace_theme(&self, stem: &str, bytes: &[u8], expected: FileStamp) -> Result<FileStamp, WriteError> {
let path = self.theme_path(stem);
self.write_guarded(&path, bytes, Expected::Stamp(expected))?;
match self.stamp(&path) {
Ok(Some(stamp)) => Ok(stamp),
Ok(None) => Err(WriteError::Io(io::ErrorKind::NotFound.into())),
Err(e) => Err(WriteError::Io(e)),
}
}
/// Replaces `path` atomically, unless it no longer is what `expected` says just before the
/// rename.
fn write_guarded(&self, path: &Path, bytes: &[u8], expected: Expected<'_>) -> Result<(), WriteError> {
let guard = Guarded { inner: &*self.fs, path, expected, raced: Cell::new(false) };
match private().atomic_write_custom(&guard, RenameRetry::platform(), path, bytes) {
Ok(()) => Ok(()),
Err(_) if guard.raced.get() => Err(WriteError::Raced),
Err(e) => Err(WriteError::Io(e)),
@@ -172,9 +188,10 @@ fn locking_unsupported(e: &io::Error) -> bool {
e.kind() == io::ErrorKind::Unsupported || e.raw_os_error() == Some(ENOLCK)
}
/// Library files are written once (an import creates one, a delete removes it), so their stamps
/// are the only change check: a hand edit in place that keeps length and modification time goes
/// unnoticed. `selection.json`, which is replaced on every write, also gets byte comparisons.
/// Library files change only by whole-file writes (an import creates one, a save replaces it, a
/// delete removes it), each a new file, so their stamps are the only change check: a hand edit in
/// place that keeps length and modification time goes unnoticed. `selection.json`, which is
/// replaced on every write, also gets byte comparisons.
fn stamp_of(meta: &fs::Metadata) -> FileStamp {
let modified_nanos = meta.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_nanos());
#[cfg(unix)]
@@ -184,16 +201,45 @@ fn stamp_of(meta: &fs::Metadata) -> FileStamp {
FileStamp { len: meta.len(), modified_nanos, identity }
}
/// Checks `selection.json` once more just before the rename that replaces it. Advisory locks
/// can be unreliable on network file systems; a file that changed under the lock means another
/// writer, and the write is abandoned instead of overwriting its change.
/// What a guarded write expects to replace.
#[derive(Clone, Copy)]
enum Expected<'a> {
/// `selection.json`'s bytes as read under the lock; `None` for a missing file.
Bytes(Option<&'a [u8]>),
/// A library file's stamp when the caller loaded it.
Stamp(FileStamp),
}
/// Checks the file once more just before the rename that replaces it. Advisory locks can be
/// unreliable on network file systems; a file that changed under the lock means another writer,
/// and the write is abandoned instead of overwriting its change.
struct Guarded<'a> {
inner: &'a dyn AtomicFs,
path: &'a Path,
expected: Option<&'a [u8]>,
expected: Expected<'a>,
raced: Cell<bool>,
}
impl Guarded<'_> {
fn unchanged(&self) -> io::Result<bool> {
match self.expected {
Expected::Bytes(expected) => {
let now = match fs::read(self.path) {
Ok(bytes) => Some(bytes),
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(e),
};
Ok(now.as_deref() == expected)
}
Expected::Stamp(expected) => match fs::metadata(self.path) {
Ok(meta) => Ok(stamp_of(&meta) == expected),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e),
},
}
}
}
impl AtomicFs for Guarded<'_> {
fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result<File> {
self.inner.create_new(path, permissions)
@@ -204,14 +250,9 @@ impl AtomicFs for Guarded<'_> {
}
fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
let now = match fs::read(self.path) {
Ok(bytes) => Some(bytes),
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(e),
};
if now.as_deref() != self.expected {
if !self.unchanged()? {
self.raced.set(true);
return Err(io::Error::other("selection.json changed while it was being written"));
return Err(io::Error::other(format!("{} changed while it was being written", self.path.display())));
}
self.inner.rename(from, to)
}
+1 -1
View File
@@ -57,7 +57,7 @@ pub use craft_theme::format;
pub use craft_theme::format::{FormatError, FormatErrors, MAX_THEME_BYTES};
pub use dir::{DirSource, SUITE_DIR_ENV, SuiteDir};
pub use selection::{Accepted, MAX_SELECTION_BYTES, SELECTION_SCHEMA_VERSION, SelectionChange, SelectionError};
pub use store::{Imported, LOCK_TIMEOUT, Library, ParseCounts, Problem, Store, StoreError, StoreOptions, ThemeEntry, ThemeRecord};
pub use store::{Imported, LOCK_TIMEOUT, Library, ParseCounts, Problem, Saved, Store, StoreError, StoreOptions, ThemeEntry, ThemeRecord};
pub use watch::{Op, OpOutput, RESULTS_KEPT, STAT_INTERVAL, Snapshot, SuiteWatch, VERIFY_INTERVAL};
#[cfg(test)]
+59 -2
View File
@@ -112,7 +112,10 @@ pub enum StoreError {
InUse(ThemeId),
/// No library theme has this id.
NotFound(ThemeId),
/// Built-in themes can't be deleted.
/// The library theme's file changed since the caller loaded it: another app saved over it.
/// Offer to reload it, to overwrite it, or to save as a new theme.
Changed(ThemeId),
/// Built-in themes can't be changed or deleted.
BuiltIn(ThemeId),
/// The watch no longer had the result of this change when the client looked, and the
/// suite's state doesn't show it. Retry.
@@ -260,6 +263,17 @@ pub struct Imported {
pub accepted: Accepted,
}
/// A successful save.
#[derive(Clone, Debug)]
pub struct Saved {
/// The stored theme.
pub record: ThemeRecord,
/// The new file's stamp: the `expected` stamp for the next save.
pub stamp: FileStamp,
/// The selection after the save.
pub accepted: Accepted,
}
/// How many times the store has parsed each kind of file, for tests that check work is not
/// repeated.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -457,6 +471,48 @@ impl Store {
Err(StoreError::IdExists(id))
}
/// Replaces library theme `id` with `bytes`, keeping them exactly, when its file still has
/// the stamp `expected` it had when the caller loaded it; otherwise [`StoreError::Changed`]
/// and the file stays as it is. The file's `id` must be `id`. Built-ins are refused. Like an
/// import, a save bumps `library_revision`, so watchers list the new file.
pub fn save_theme(&mut self, id: &ThemeId, bytes: &[u8], expected: FileStamp) -> Result<Saved, StoreError> {
if id.is_builtin() {
return Err(StoreError::BuiltIn(id.clone()));
}
let stem = user_stem(id)?;
let record = self.parse_theme_counted(bytes).map_err(StoreError::Format)?;
if record.theme.id != *id {
return Err(StoreError::FileName { id: record.theme.id });
}
let _lock = self.lock()?;
let base = self.accepted.clone();
let disk = self.read_for_write(&base)?;
match self.backend.theme_stamp(stem)? {
None => return Err(StoreError::NotFound(id.clone())),
Some(stamp) if stamp != expected => return Err(StoreError::Changed(id.clone())),
Some(_) => {}
}
let old = self.backend.read_theme(stem, MAX_THEME_BYTES)?.ok_or_else(|| StoreError::NotFound(id.clone()))?;
// The file goes first, so a watcher that sees the new library revision lists it.
let stamp = match self.backend.replace_theme(stem, &record.bytes, expected) {
Ok(stamp) => stamp,
Err(WriteError::Raced) => return Err(StoreError::Changed(id.clone())),
Err(WriteError::Io(e)) => return Err(e.into()),
};
match self.commit(&disk, library_bump(&disk.accepted)) {
Ok(accepted) => Ok(Saved { record, stamp, accepted }),
Err(e) => {
// The old bytes go back as a new file, so on disk its stamp is not `expected`
// any more (it includes the inode): a retry with that stamp gets `Changed`. A
// file over the size limit was read only in part and is left replaced.
if old.len() <= MAX_THEME_BYTES {
let _ = self.backend.replace_theme(stem, &old, stamp);
}
Err(e)
}
}
}
/// Removes a library theme. A theme in either slot of the suite selection can't be deleted;
/// per-app choices that name it fall back to the app default when they resolve.
///
@@ -681,7 +737,8 @@ impl fmt::Display for StoreError {
StoreError::IdExists(id) => write!(f, "a theme with the id {id} is already installed"),
StoreError::InUse(id) => write!(f, "{id} is a suite theme; choose another theme before deleting it"),
StoreError::NotFound(id) => write!(f, "there is no theme {id}"),
StoreError::BuiltIn(id) => write!(f, "{id} is a built-in theme and can't be deleted"),
StoreError::Changed(id) => write!(f, "{id} was changed in another Craft app since it was opened"),
StoreError::BuiltIn(id) => write!(f, "{id} is a built-in theme; it can't be changed or deleted"),
StoreError::Lost => f.write_str("the result of this change was lost; it may not have been saved"),
}
}
+62 -1
View File
@@ -6,7 +6,7 @@ use std::{fs, path::Path, time::Duration};
use craft_theme::{ContrastChoice, ModeChoice, MotionChoice, Selection, Size, TextSize, ThemeId, ThemePair};
use crate::{
Accepted, Problem, SelectionChange, SelectionError, Store, StoreError, StoreOptions, SuiteDir,
Accepted, FileStamp, Problem, SelectionChange, SelectionError, Store, StoreError, StoreOptions, SuiteDir,
testing::{FailAt, FailingFs, SAMPLE_THEME_JSON},
};
@@ -117,9 +117,70 @@ fn ids_users_cant_create_never_reach_the_file_system() {
assert!(matches!(store.export(&con), Err(StoreError::NotFound(_))));
assert!(matches!(store.delete(&con), Err(StoreError::NotFound(_))));
assert!(store.theme(&con).is_none());
let listed = store.library_files().unwrap()[0].stamp;
assert!(matches!(store.save_theme(&con, theme_json("con", "").as_bytes(), listed), Err(StoreError::NotFound(_))));
let graphite = id("craft.graphite");
assert!(matches!(store.save_theme(&graphite, theme_json("con", "").as_bytes(), listed), Err(StoreError::BuiltIn(_))));
// A library theme that doesn't exist is never written as the suite's, in either slot.
assert!(matches!(store.update(&Accepted::default(), theme("con")), Err(StoreError::NotFound(_))));
assert!(matches!(store.update(&Accepted::default(), SelectionChange::theme_dark(id("gone"))), Err(StoreError::NotFound(_))));
assert!(library.join("con.json").exists());
assert!(!tmp.path().join("selection.json").exists());
}
#[trial]
fn a_save_replaces_the_library_file_and_moves_the_library_revision() {
let tmp = tempfile::tempdir().unwrap();
for dir in [SuiteDir::at(tmp.path()), SuiteDir::memory()] {
let mut store = Store::open(&dir, options());
let imported = store.import(theme_json("one", "").as_bytes(), false).unwrap().accepted;
let loaded = store.theme_stamp(&id("one")).unwrap().unwrap();
let second = theme_json("one", r#","version":2"#);
let saved = store.save_theme(&id("one"), second.as_bytes(), loaded).unwrap();
assert_eq!(&*store.load_theme(&id("one")).unwrap().bytes, second.as_bytes());
assert_eq!(store.theme_stamp(&id("one")).unwrap(), Some(saved.stamp));
assert_ne!(saved.stamp, loaded);
let moved = (saved.accepted.revision, saved.accepted.library_revision);
assert_eq!(moved, (imported.revision + 1, imported.library_revision + 1));
// The next save goes from the stamp the last one returned.
store.save_theme(&id("one"), theme_json("one", r#","version":3"#).as_bytes(), saved.stamp).unwrap();
assert_eq!(store.load_theme(&id("one")).unwrap().theme.version, 3);
}
}
#[trial]
fn a_save_over_a_changed_file_is_refused_and_leaves_it() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("library").join("one.json");
let mut mine = open(tmp.path());
let mut other = open(tmp.path());
mine.import(theme_json("one", "").as_bytes(), false).unwrap();
let loaded = mine.theme_stamp(&id("one")).unwrap().unwrap();
let save = |store: &mut Store, stamp: FileStamp, version: u32| {
store.save_theme(&id("one"), theme_json("one", &format!(r#","version":{version}"#)).as_bytes(), stamp)
};
assert!(matches!(mine.save_theme(&id("one"), theme_json("two", "").as_bytes(), loaded), Err(StoreError::FileName { .. })));
// Another app saved over it.
other.save_theme(&id("one"), theme_json("one", r#","version":2"#).as_bytes(), loaded).unwrap();
let theirs = fs::read_to_string(&path).unwrap();
mine.load_selection().unwrap();
let before = mine.accepted().clone();
assert!(matches!(save(&mut mine, loaded, 3), Err(StoreError::Changed(_))));
assert_eq!(fs::read_to_string(&path).unwrap(), theirs);
mine.load_selection().unwrap();
assert_eq!(mine.accepted(), &before);
// Edited by hand (another length, so the stamp moves however coarse the clock).
let now = mine.theme_stamp(&id("one")).unwrap().unwrap();
let hand = theme_json("one", r#","version":40"#);
fs::write(&path, &hand).unwrap();
assert!(matches!(save(&mut mine, now, 5), Err(StoreError::Changed(_))));
assert_eq!(fs::read_to_string(&path).unwrap(), hand);
// Deleted.
let now = mine.theme_stamp(&id("one")).unwrap().unwrap();
mine.delete(&id("one")).unwrap();
assert!(matches!(save(&mut mine, now, 6), Err(StoreError::NotFound(_))));
assert!(!path.exists());
}
+12
View File
@@ -49,6 +49,15 @@ pub enum Op {
/// Give the theme a new id when its id is already in the library, instead of failing.
as_copy: bool,
},
/// Replaces a library theme ([`Store::save_theme`]); the result is [`OpOutput::Saved`].
Save {
/// The library theme to replace.
id: ThemeId,
/// The new theme file's contents.
bytes: Arc<[u8]>,
/// The file's stamp when the app loaded it, or from its last save.
expected: FileStamp,
},
/// Removes a library theme ([`Store::delete`]).
Delete(ThemeId),
/// A theme file for sharing ([`Store::export`]); the result is [`OpOutput::Exported`].
@@ -71,6 +80,8 @@ pub enum OpOutput {
Exported(Arc<[u8]>),
/// The stored id; for an import as copy, the new one.
Imported(ThemeId),
/// The saved file's stamp: the `expected` stamp for the next save.
Saved(FileStamp),
}
/// The state of the suite folder at one generation. Snapshots never change; a new one replaces
@@ -694,6 +705,7 @@ impl Engine {
let result = match op {
Op::Update { base, change } => self.store.update(&base, change).map(|_| OpOutput::Done),
Op::Import { bytes, as_copy } => self.store.import(&bytes, as_copy).map(|i| OpOutput::Imported(i.record.theme.id)),
Op::Save { id, bytes, expected } => self.store.save_theme(&id, &bytes, expected).map(|s| OpOutput::Saved(s.stamp)),
Op::Delete(theme) => self.store.delete(&theme).map(|_| OpOutput::Done),
Op::Export(theme) => self.store.export(&theme).map(OpOutput::Exported),
Op::Rescan => {
+30 -12
View File
@@ -1,5 +1,7 @@
//! Two processes updating different fields of the suite selection at once: every update lands
//! and neither overwrites the other's field. The test binary runs itself as the two children.
//! Three processes writing the suite folder at once, two updating different fields of the suite
//! selection and one saving over a library theme: every write lands, neither update overwrites
//! the other's field, and another process reads the last save. The test binary runs itself as
//! the three children.
#![cfg(not(target_arch = "wasm32"))]
use craft_ui::testing::trial;
@@ -13,11 +15,20 @@ const DIR: &str = "CRAFT_THEME_STORE_TEST_DIR";
const UPDATES: u64 = 200;
const THEMES: [&str; 2] = ["craft.graphite", "craft.studio"];
const MODES: [ModeChoice; 2] = [ModeChoice::Light, ModeChoice::Dark];
const SAVED: &str = "saved";
fn both(theme: &str) -> SelectionChange {
SelectionChange::themes(ThemePair::same(ThemeId::parse(theme).unwrap()))
}
/// The library theme the save child writes, at `version`.
fn saved_file(version: u64) -> String {
format!(
r##"{{"schema":"craft-design-theme","schema_version":1,"id":"{SAVED}","name":"Saved","version":{version},"variants":"dark",
"seeds":{{"accent":"#4b8bf5","neutral":"#26262a","status":{{"good":"#3fd6b8","warn":"#ffc14d","bad":"#ff6259","info":"#4b8bf5"}}}}}}"##
)
}
#[trial]
fn two_processes_keep_every_update() {
if let (Ok(role), Ok(dir)) = (std::env::var(ROLE), std::env::var(DIR)) {
@@ -28,9 +39,10 @@ fn two_processes_keep_every_update() {
// Both children start from an existing selection, so neither takes the no-base path.
let mut store = Store::open(&SuiteDir::at(tmp.path()), StoreOptions::new("parent"));
store.update(&Accepted::default(), both("craft.artcraft").then(SelectionChange::mode(ModeChoice::System))).unwrap();
store.import(saved_file(1).as_bytes(), false).unwrap();
let exe = std::env::current_exe().unwrap();
let children: Vec<_> = ["theme", "mode"]
let children: Vec<_> = ["theme", "mode", "save"]
.into_iter()
.map(|role| {
Command::new(&exe)
@@ -50,30 +62,36 @@ fn two_processes_keep_every_update() {
store.load_selection().unwrap();
let last = (UPDATES - 1) as usize % 2;
let accepted = store.accepted();
assert_eq!(accepted.revision, 1 + 2 * UPDATES);
assert_eq!((accepted.revision, accepted.library_revision), (2 + 3 * UPDATES, 1 + UPDATES));
let theme = Some(ThemeId::parse(THEMES[last]).unwrap());
assert_eq!(accepted.suite, SuiteChoice { theme_light: theme.clone(), theme_dark: theme, mode: Some(MODES[last]), ..SuiteChoice::default() });
let saved = store.load_theme(&ThemeId::parse(SAVED).unwrap()).unwrap();
assert_eq!(&*saved.bytes, saved_file(1 + UPDATES).as_bytes());
}
/// Each update changes one field relative to this child's own last write, which is stale for
/// the other child's field: the merge has to keep the disk value there.
/// the other child's field: the merge has to keep the disk value there. Each save goes from the
/// stamp of the child's own last save.
fn child(role: &str, dir: &Path) {
let mut store = Store::open(&SuiteDir::at(dir), StoreOptions::new(format!("child {role}")));
store.load_selection().unwrap();
let saved = ThemeId::parse(SAVED).unwrap();
let mut stamp = store.theme_stamp(&saved).unwrap().unwrap();
while !dir.join("go").exists() {
std::thread::yield_now();
}
for i in 0..UPDATES as usize {
let base = store.accepted().clone();
let mine = match role {
"theme" => both(THEMES[i % 2]),
_ => SelectionChange::mode(MODES[i % 2]),
};
loop {
match store.update(&base, mine.clone()) {
Ok(_) => break,
let written = match role {
"theme" => store.update(&base, both(THEMES[i % 2])).map(drop),
"mode" => store.update(&base, SelectionChange::mode(MODES[i % 2])).map(drop),
_ => store.save_theme(&saved, saved_file(i as u64 + 2).as_bytes(), stamp).map(|s| stamp = s.stamp),
};
match written {
Ok(()) => break,
Err(StoreError::Busy) => continue,
Err(e) => panic!("{role} update {i}: {e}"),
Err(e) => panic!("{role} write {i}: {e}"),
}
}
}
+1
View File
@@ -65,6 +65,7 @@ workspace = true
craft-ui = { workspace = true, features = ["app", "testing"] }
craft-i18n = { workspace = true }
craft-theme = { workspace = true }
craft-theme-editor = { workspace = true, features = ["screen-testing"] }
craft-window = { workspace = true }
egui = { workspace = true }
eframe = { version = "0.37", default-features = false }
+2 -2
View File
@@ -4,12 +4,12 @@
use super::describe;
use super::inspect::{self, Inspect};
use super::overview;
use crate::theme::{AppLayerEditor, Problems, ThemeSubject, ThemeWorkspace, TokenBrowser, TokenDetail};
use crate::viewer::{self, CardState, Catalog, Cells, ComponentInfo, PanelId, TreeKey, TreeRow, TreeRows};
use craft_behavior::IconId;
use craft_behavior::{Selection, keyed};
use craft_theme::Explained;
use craft_theme::report::ContrastReport;
use craft_theme_editor::{AppLayerEditor, Problems, ThemeSubject, ThemeWorkspace, TokenBrowser, TokenDetail};
use craft_ui::buttons::IconButton;
use craft_ui::contract::{Bind, CollectionEvent, Props as _, RowAlign, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft_ui::display::{Shade, Text};
@@ -60,7 +60,7 @@ pub struct Panels<'a> {
/// The root values; a Variants card that is used sets its value.
pub env: &'a mut craft_ui::runtime::env::RootEnv,
/// The row the Problems view picked in this pass, which the token browser brings into view.
pub revealed: Option<crate::theme::Pick>,
pub revealed: Option<craft_theme_editor::Pick>,
/// What the inspector shows.
pub inspect: Inspect<'a>,
}
+1 -1
View File
@@ -5,10 +5,10 @@ use super::inspect::Inspect;
use super::options::options_bar;
use super::panels::Panels;
use super::persist::Persisted;
use crate::theme::{ThemeSubject, parse_sizes};
use crate::viewer::{Browser, Catalog, GalleryCommands, GallerySettings, PanelId, TreeKey, Viewer, Workspace, theme_of};
use craft_behavior::dock::{PanelState, Workspace as Dock};
use craft_theme::AppSizes;
use craft_theme_editor::{ThemeSubject, parse_sizes};
use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _};
use craft_ui::docking::DockConfig;
use craft_ui::patterns::dock::DockArea;
+1 -3
View File
@@ -7,9 +7,6 @@ pub mod viewer;
// The Foundations cards.
pub mod foundations;
// The theme workspace.
pub mod theme;
// The mock editor window.
pub mod mock;
@@ -49,6 +46,7 @@ fn crates() -> Vec<(&'static str, Registered)> {
crates.push(("craft-table", craft_table::ui::testing::registered));
#[cfg(feature = "text")]
crates.push(("craft-text", craft_text::testing::registered));
crates.push(("craft-theme-editor", craft_theme_editor::testing::registered));
#[cfg(feature = "theme-store")]
crates.push(("craft-theme-store", craft_theme_store::ui::registered));
#[cfg(feature = "timeline")]
+1 -1
View File
@@ -9,9 +9,9 @@ use super::picks::CardState;
use super::settings::GallerySettings;
use super::tree::{self, TreeKey};
use crate::mock::MockState;
use crate::theme::ThemeWorkspace;
use craft_behavior::Selection;
use craft_behavior::dock::Workspace as Dock;
use craft_theme_editor::ThemeWorkspace;
use craft_ui::contract::Level;
use craft_ui::display::InspectLayers;
use craft_ui::list::OpenSet;
+1 -1
View File
@@ -1,5 +1,5 @@
[lint]
paths = ["crates/behavior", "crates/ui", "crates/ui-contract", "crates/ui-widgets", "crates/ui-panels", "crates/ui-canvas", "crates/ui-patterns", "crates/ui-shell", "crates/ui-macros", "crates/ui-gallery", "crates/update/src/stack_dialogs.rs", "crates/update/src/updater.rs", "crates/update/tests/it", "crates/dialogs/src/ui", "crates/dialogs/tests/it", "crates/print/src/ui", "crates/print/tests/it", "crates/theme-store/src/ui", "crates/theme-store/tests/it", "crates/browse/src/ui", "crates/browse/src/thumbs/source.rs", "crates/browse/tests/it", "crates/layers/src/ui", "crates/layers/tests/it", "crates/table/src/ui", "crates/table/tests/it", "crates/timeline/src/ui", "crates/timeline/src/rates.rs", "crates/timeline/tests/it", "crates/menu/src", "crates/menu/tests/it", "crates/automation/src/ui", "crates/automation/src/control.rs", "crates/automation/src/screenshot.rs", "crates/automation/src/server.rs", "crates/automation/src/synthetic.rs", "crates/automation/tests/it", "crates/pages/src/ui", "crates/pages/tests/it", "crates/review/src/ui", "crates/review/tests/it", "crates/font-manager/src", "crates/font-manager/tests/it", "crates/text/src/ui", "crates/text/tests/it", "crates/imaging/src/ui", "crates/imaging/tests/it", "crates/color-ui/src/ui", "crates/color-ui/tests/it", "crates/draw/src/ui", "crates/draw/tests/it"]
paths = ["crates/behavior", "crates/ui", "crates/ui-contract", "crates/ui-widgets", "crates/ui-panels", "crates/ui-canvas", "crates/ui-patterns", "crates/ui-shell", "crates/ui-macros", "crates/ui-gallery", "crates/update/src/stack_dialogs.rs", "crates/update/src/updater.rs", "crates/update/tests/it", "crates/dialogs/src/ui", "crates/dialogs/tests/it", "crates/print/src/ui", "crates/print/tests/it", "crates/theme-editor/src", "crates/theme-store/src/ui", "crates/theme-store/tests/it", "crates/browse/src/ui", "crates/browse/src/thumbs/source.rs", "crates/browse/tests/it", "crates/layers/src/ui", "crates/layers/tests/it", "crates/table/src/ui", "crates/table/tests/it", "crates/timeline/src/ui", "crates/timeline/src/rates.rs", "crates/timeline/tests/it", "crates/menu/src", "crates/menu/tests/it", "crates/automation/src/ui", "crates/automation/src/control.rs", "crates/automation/src/screenshot.rs", "crates/automation/src/server.rs", "crates/automation/src/synthetic.rs", "crates/automation/tests/it", "crates/pages/src/ui", "crates/pages/tests/it", "crates/review/src/ui", "crates/review/tests/it", "crates/font-manager/src", "crates/font-manager/tests/it", "crates/text/src/ui", "crates/text/tests/it", "crates/imaging/src/ui", "crates/imaging/tests/it", "crates/color-ui/src/ui", "crates/color-ui/tests/it", "crates/draw/src/ui", "crates/draw/tests/it"]
include-tests = false
deny-unused = true
+5 -2
View File
@@ -227,6 +227,9 @@ Library operations take the same lock and bump `library_revision`:
- **Import** validates the file and writes its original bytes to `library/<id>.json`, never
replacing a file (`IdExists`); "import as copy" picks the first free `<id>-2`, `<id>-3` ...
- **Save** replaces a library theme with new bytes when its file still has the stamp the caller
loaded it with; a file another app replaced since is `Changed` and stays as it is. Built-ins
are refused (`BuiltIn`).
- **Delete** refuses built-ins and a theme in either suite slot (`InUse`).
- **Export** returns a library theme's stored bytes, or a built-in written as a theme file.
@@ -242,8 +245,8 @@ use every 500 ms, compares bytes every 10 s, and lists the library only when `li
changes or on `Op::Rescan`. Each change publishes a snapshot and calls `wake` once.
Each frame the app compares `generation()` (one atomic load) with its cache key and rebuilds its
styles only when it changed. Changes go through `request(Op)`: `Update`, `Import`, `Delete`,
`Export`, `Rescan` and `AppTheme`; the result appears in `snapshot().result(id)`. `SuiteWatch::memory()`
styles only when it changed. Changes go through `request(Op)`: `Update`, `Import`, `Save`,
`Delete`, `Export`, `Rescan` and `AppTheme`; the result appears in `snapshot().result(id)`. `SuiteWatch::memory()`
runs without a thread, applying each request before it returns.
The lock file and revision protocol follow