mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
craft-tracked: Tracked<T>, PlainData and its derive, field! and Bind::tracked
Tracked<T> owns its value, a process-unique source id and a write count. Deref reads; DerefMut, edit and a Field's writes move the count, and a clone is a new source. T must be PlainData, a marker with no implementation for interior mutability, raw pointers, dyn objects or closures, so no write can bypass the count. #[derive(PlainData)] in ui-macros checks every field through a field-check helper the plain-data derives share; #[plain_data(assume = "reason")] skips one field of a foreign plain type. field!(a.b) builds a read and a write projection from a field path only. Bind::tracked(&mut t, field!(a.b)) reads through the read projection and moves the revision only when an edit changes the field.
This commit is contained in:
Generated
+9
@@ -1914,6 +1914,7 @@ dependencies = [
|
||||
"craft-tiff",
|
||||
"craft-time",
|
||||
"craft-timeline",
|
||||
"craft-tracked",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"craft-usd",
|
||||
@@ -4128,6 +4129,13 @@ dependencies = [
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-ui-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -4193,6 +4201,7 @@ dependencies = [
|
||||
"craft-settings",
|
||||
"craft-svg",
|
||||
"craft-theme",
|
||||
"craft-tracked",
|
||||
"craft-ui-contract",
|
||||
"craft-ui-macros",
|
||||
"craft-ui-test-kit",
|
||||
|
||||
@@ -219,6 +219,7 @@ 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-tracked = { path = "crates/tracked" }
|
||||
craft-ui = { path = "crates/ui" }
|
||||
craft-ui-canvas = { path = "crates/ui-canvas" }
|
||||
craft-ui-contract = { path = "crates/ui-contract" }
|
||||
|
||||
@@ -143,6 +143,7 @@ craft-stream-codecs = { workspace = true, optional = true }
|
||||
craft-svg = { workspace = true, optional = true }
|
||||
craft-tga = { workspace = true, optional = true }
|
||||
craft-tiff = { workspace = true, optional = true }
|
||||
craft-tracked = { workspace = true, optional = true }
|
||||
craft-time = { workspace = true, optional = true }
|
||||
craft-vcard = { workspace = true, optional = true }
|
||||
craft-vectordrawable = { workspace = true, optional = true }
|
||||
@@ -217,6 +218,8 @@ craft-xfa = { workspace = true, optional = true }
|
||||
[features]
|
||||
ui = [
|
||||
"dep:craft-ui",
|
||||
# The framework's memoized views key app models by their `Tracked` revision.
|
||||
"tracked",
|
||||
"dep:egui",
|
||||
"craft-automation?/ui",
|
||||
"craft-browse?/ui",
|
||||
@@ -839,6 +842,8 @@ theme-store = ["dep:craft-theme-store"]
|
||||
|
||||
tiff = ["dep:craft-tiff"]
|
||||
|
||||
tracked = ["dep:craft-tracked"]
|
||||
|
||||
time = ["dep:craft-time"]
|
||||
|
||||
timeline = ["dep:craft-timeline", "keymap"]
|
||||
|
||||
@@ -356,6 +356,8 @@ pub use craft_tiff as tiff;
|
||||
pub use craft_time as time;
|
||||
#[cfg(feature = "timeline")]
|
||||
pub use craft_timeline as timeline;
|
||||
#[cfg(feature = "tracked")]
|
||||
pub use craft_tracked as tracked;
|
||||
#[cfg(feature = "ui")]
|
||||
pub use craft_ui as ui;
|
||||
#[cfg(feature = "update")]
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "craft-tracked"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
description = "Tracked<T>: app data whose every write moves a revision, so a reader compares two integers instead of the data"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
# No dependencies, so engine crates can hold and move a revision without the UI.
|
||||
|
||||
[dev-dependencies]
|
||||
# `#[derive(PlainData)]` in the doc tests.
|
||||
craft-ui-macros = { workspace = true }
|
||||
@@ -0,0 +1,443 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
//! `Tracked<T>`: app data whose every write moves a revision.
|
||||
//!
|
||||
//! A reader that only needs to know whether the data changed compares the [`Revision`] (two integers) instead of the
|
||||
//! data. The revision is complete because the compiler sees every write:
|
||||
//!
|
||||
//! - Every way to change the data goes through `&mut Tracked<T>`: [`DerefMut`], [`Tracked::edit`] and a
|
||||
//! [`Field`]'s writes, and each moves the revision.
|
||||
//! - `T` is [`PlainData`], so a shared reference can't change it: interior mutability, raw pointers, `dyn` objects
|
||||
//! and closures have no implementation, and a `Tracked` holding one does not compile.
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_tracked::Tracked;
|
||||
//! let mut names = Tracked::new(vec!["a".to_owned()]);
|
||||
//! let before = names.revision();
|
||||
//! assert_eq!(names.len(), 1);
|
||||
//! assert_eq!(names.revision(), before, "reading leaves the revision");
|
||||
//! names.push("b".to_owned());
|
||||
//! assert_ne!(names.revision(), before, "a write moves it");
|
||||
//! ```
|
||||
//!
|
||||
//! # App types
|
||||
//!
|
||||
//! App types derive the marker with `#[derive(PlainData)]` (craft-ui-macros, re-exported by craft-ui and the
|
||||
//! `craft` facade), which requires it of every field and names the field whose type has none:
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_tracked::Tracked;
|
||||
//! use craft_ui_macros::PlainData;
|
||||
//!
|
||||
//! #[derive(PlainData)]
|
||||
//! enum Node {
|
||||
//! Leaf(String),
|
||||
//! Group { name: String, children: Vec<Node> },
|
||||
//! }
|
||||
//!
|
||||
//! let tree = Tracked::new(Node::Group { name: "root".into(), children: vec![Node::Leaf("a".into())] });
|
||||
//! # let _ = tree;
|
||||
//! ```
|
||||
//!
|
||||
//! Two kinds of type have no derived implementation and take one of two escapes, each a stated promise that a shared
|
||||
//! reference can't change what readers see:
|
||||
//!
|
||||
//! - **A foreign plain type** used as a field (an egui `Rect`, a `serde_json::Value`): the field carries
|
||||
//! `#[plain_data(assume = "why the type is plain")]`, which skips the check for that field only. The reason is
|
||||
//! required; an empty one does not compile.
|
||||
//! - **A type that encapsulates interior mutability readers can't observe** (a tile whose bytes move between memory
|
||||
//! and disk while its pixels stay the same): the crate that owns the type implements the marker by hand,
|
||||
//! `impl PlainData for Tile {}`, with a comment saying why. UI crates have no such types and use the derive.
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_tracked::Tracked;
|
||||
//! use craft_ui_macros::PlainData;
|
||||
//!
|
||||
//! # mod egui { pub struct Rect; }
|
||||
//! #[derive(PlainData)]
|
||||
//! struct Panel {
|
||||
//! title: String,
|
||||
//! #[plain_data(assume = "egui geometry: plain numbers, no interior mutability")]
|
||||
//! rect: egui::Rect,
|
||||
//! }
|
||||
//! # let _ = Tracked::new(Panel { title: String::new(), rect: egui::Rect });
|
||||
//! ```
|
||||
//!
|
||||
//! # Threads
|
||||
//!
|
||||
//! The revision is a plain `u64`: every write needs `&mut Tracked<T>`, so the thread that owns the value is the one
|
||||
//! that moves it. An engine that runs jobs on worker threads and applies their results on the UI thread keeps its
|
||||
//! model in a `Tracked` there: a worker computes on a snapshot and sends its result back, and applying the result
|
||||
//! through `&mut` moves the revision on the owning side.
|
||||
//!
|
||||
//! # Rejected types
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! let _ = craft_tracked::Tracked::new(std::cell::Cell::new(1));
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! let _ = craft_tracked::Tracked::new(std::cell::RefCell::new(1));
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! let _ = craft_tracked::Tracked::new(std::sync::Mutex::new(1));
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! let _ = craft_tracked::Tracked::new(std::sync::RwLock::new(1));
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! let _ = craft_tracked::Tracked::new(std::sync::atomic::AtomicU32::new(1));
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! let _ = craft_tracked::Tracked::new(std::sync::OnceLock::<u32>::new());
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! let _ = craft_tracked::Tracked::new(std::ptr::null::<u8>());
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! let _ = craft_tracked::Tracked::new(Box::new(|| 1) as Box<dyn Fn() -> i32>);
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! let _ = craft_tracked::Tracked::new(std::sync::Arc::new(std::sync::Mutex::new(1)));
|
||||
//! ```
|
||||
//!
|
||||
//! A derived type with a rejected field:
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! #[derive(craft_ui_macros::PlainData)]
|
||||
//! struct Counter {
|
||||
//! hits: std::cell::Cell<u32>,
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! A generic derived type used with a rejected parameter:
|
||||
//!
|
||||
//! ```compile_fail,E0277
|
||||
//! #[derive(craft_ui_macros::PlainData)]
|
||||
//! struct Wrap<T>(T);
|
||||
//! let _ = craft_tracked::Tracked::new(Wrap(std::cell::Cell::new(1)));
|
||||
//! ```
|
||||
//!
|
||||
//! An `assume` without a reason:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! #[derive(craft_ui_macros::PlainData)]
|
||||
//! struct Panel {
|
||||
//! #[plain_data(assume = "")]
|
||||
//! rect: std::cell::Cell<u32>,
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
// The derive reaches this crate as `::craft_tracked`, here too.
|
||||
extern crate self as craft_tracked;
|
||||
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Data that a shared reference can't change: no interior mutability, no raw pointers, no `dyn` objects, no
|
||||
/// closures. Implemented for plain std types and their containers; app types derive it.
|
||||
///
|
||||
/// A hand implementation is a promise the compiler can't check. It belongs only in this crate and in the crate that
|
||||
/// owns a type whose interior mutability readers can't observe; see the crate docs.
|
||||
#[diagnostic::on_unimplemented(
|
||||
message = "`{Self}` is not plain data",
|
||||
label = "`{Self}` can change behind a shared reference, or has no `PlainData` implementation",
|
||||
note = "`Cell`, `RefCell`, `Mutex`, `RwLock`, `OnceLock`, atomics, raw pointers, `dyn` objects and closures are rejected, because a write through them would not move the revision",
|
||||
note = "app types use `#[derive(PlainData)]`; a field of a foreign plain type takes `#[plain_data(assume = \"why the type is plain\")]`"
|
||||
)]
|
||||
pub trait PlainData {}
|
||||
|
||||
macro_rules! plain {
|
||||
($($t:ty),* $(,)?) => { $(impl PlainData for $t {})* };
|
||||
}
|
||||
|
||||
plain!(bool, char, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64, str, String, ());
|
||||
plain!(std::num::NonZeroU8, std::num::NonZeroU16, std::num::NonZeroU32, std::num::NonZeroU64, std::num::NonZeroUsize);
|
||||
plain!(std::num::NonZeroI8, std::num::NonZeroI16, std::num::NonZeroI32, std::num::NonZeroI64, std::num::NonZeroIsize);
|
||||
plain!(std::cmp::Ordering, std::time::Duration, std::time::Instant, std::time::SystemTime);
|
||||
plain!(std::path::PathBuf, std::path::Path, std::ffi::OsString, std::ffi::OsStr);
|
||||
plain!(std::collections::hash_map::RandomState);
|
||||
|
||||
impl<T: PlainData + ?Sized> PlainData for &T {}
|
||||
impl<T: PlainData + ?Sized> PlainData for Box<T> {}
|
||||
impl<T: PlainData + ?Sized> PlainData for std::sync::Arc<T> {}
|
||||
impl<T: PlainData + ?Sized> PlainData for std::rc::Rc<T> {}
|
||||
impl<B: PlainData + ToOwned + ?Sized> PlainData for std::borrow::Cow<'_, B> where B::Owned: PlainData {}
|
||||
impl<T: PlainData> PlainData for Option<T> {}
|
||||
impl<T: PlainData, E: PlainData> PlainData for Result<T, E> {}
|
||||
impl<T: PlainData> PlainData for Vec<T> {}
|
||||
impl<T: PlainData> PlainData for [T] {}
|
||||
impl<T: PlainData, const N: usize> PlainData for [T; N] {}
|
||||
impl<T: PlainData> PlainData for std::ops::Range<T> {}
|
||||
impl<T: PlainData> PlainData for std::ops::RangeInclusive<T> {}
|
||||
impl<T: PlainData> PlainData for std::collections::VecDeque<T> {}
|
||||
impl<T: PlainData> PlainData for std::collections::BinaryHeap<T> {}
|
||||
impl<K: PlainData, V: PlainData, S: PlainData> PlainData for std::collections::HashMap<K, V, S> {}
|
||||
impl<K: PlainData, S: PlainData> PlainData for std::collections::HashSet<K, S> {}
|
||||
impl<K: PlainData, V: PlainData> PlainData for std::collections::BTreeMap<K, V> {}
|
||||
impl<K: PlainData> PlainData for std::collections::BTreeSet<K> {}
|
||||
impl<H> PlainData for std::hash::BuildHasherDefault<H> {}
|
||||
impl<T: ?Sized> PlainData for std::marker::PhantomData<T> {}
|
||||
impl<T: PlainData> PlainData for Tracked<T> {}
|
||||
|
||||
macro_rules! tuples {
|
||||
($(($($n:ident),+)),* $(,)?) => { $(impl<$($n: PlainData),+> PlainData for ($($n,)+) {})* };
|
||||
}
|
||||
|
||||
tuples!(
|
||||
(A),
|
||||
(A, B),
|
||||
(A, B, C),
|
||||
(A, B, C, D),
|
||||
(A, B, C, D, E),
|
||||
(A, B, C, D, E, F),
|
||||
(A, B, C, D, E, F, G),
|
||||
(A, B, C, D, E, F, G, H),
|
||||
(A, B, C, D, E, F, G, H, I),
|
||||
(A, B, C, D, E, F, G, H, I, J),
|
||||
(A, B, C, D, E, F, G, H, I, J, K),
|
||||
(A, B, C, D, E, F, G, H, I, J, K, L),
|
||||
);
|
||||
|
||||
/// The next source id. Ids start at 1 and are never reused in a process.
|
||||
static NEXT_SOURCE: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
fn next_source() -> u64 {
|
||||
NEXT_SOURCE.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Which tracked value, and which state of it: equal revisions mean equal data.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Revision {
|
||||
/// The value's source: unique in the process, and new for every clone.
|
||||
pub source: u64,
|
||||
/// How many writes the value has had.
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
/// `T` with a revision that every write moves.
|
||||
///
|
||||
/// `Deref` reads; `DerefMut`, [`edit`](Self::edit) and a [`Field`]'s writes move the revision whether or not the
|
||||
/// write changes the data (a write with no change costs a reader one needless run, never a stale one). A clone is a
|
||||
/// new source: two clones written apart never share a revision.
|
||||
#[derive(Debug)]
|
||||
pub struct Tracked<T: PlainData> {
|
||||
value: T,
|
||||
revision: Revision,
|
||||
}
|
||||
|
||||
impl<T: PlainData + Default> Default for Tracked<T> {
|
||||
fn default() -> Tracked<T> {
|
||||
Tracked::new(T::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PlainData> Tracked<T> {
|
||||
/// `value`, as a new source at count 0.
|
||||
pub fn new(value: T) -> Tracked<T> {
|
||||
Tracked { value, revision: Revision { source: next_source(), count: 0 } }
|
||||
}
|
||||
|
||||
/// The current revision.
|
||||
pub fn revision(&self) -> Revision {
|
||||
self.revision
|
||||
}
|
||||
|
||||
/// The value's source id: unique in the process, new for every clone.
|
||||
pub fn source(&self) -> u64 {
|
||||
self.revision.source
|
||||
}
|
||||
|
||||
/// Changes the value through `f` and moves the revision.
|
||||
pub fn edit<R>(&mut self, f: impl FnOnce(&mut T) -> R) -> R {
|
||||
f(&mut **self)
|
||||
}
|
||||
|
||||
/// One place inside the value, chosen with [`field!`]: reading it leaves the revision, writing it moves it.
|
||||
pub fn field<U>(&mut self, projection: Projection<T, U>) -> Field<'_, T, U> {
|
||||
Field { tracked: self, projection }
|
||||
}
|
||||
|
||||
/// The value, leaving the tracking.
|
||||
pub fn into_inner(self) -> T {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PlainData + Clone> Clone for Tracked<T> {
|
||||
fn clone(&self) -> Tracked<T> {
|
||||
Tracked::new(self.value.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PlainData> Deref for Tracked<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PlainData> DerefMut for Tracked<T> {
|
||||
fn deref_mut(&mut self) -> &mut T {
|
||||
self.revision.count = self.revision.count.wrapping_add(1);
|
||||
&mut self.value
|
||||
}
|
||||
}
|
||||
|
||||
/// The way to one field of an `M`, as a read and a write projection. Only [`field!`] builds one, from a field path,
|
||||
/// so neither projection can do anything but select the field: the read projection leaves the revision, and only a
|
||||
/// write runs the write projection.
|
||||
pub struct Projection<M, U> {
|
||||
read: fn(&M) -> &U,
|
||||
write: fn(&mut M) -> &mut U,
|
||||
}
|
||||
|
||||
impl<M, U> Clone for Projection<M, U> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<M, U> Copy for Projection<M, U> {}
|
||||
|
||||
impl<M, U> Projection<M, U> {
|
||||
/// Called by [`field!`] only: a hand-written projection could write the value while selecting a field, and that
|
||||
/// write would not move the revision.
|
||||
#[doc(hidden)]
|
||||
pub const fn __from_field_path(read: fn(&M) -> &U, write: fn(&mut M) -> &mut U) -> Self {
|
||||
Projection { read, write }
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`Projection`] to the field at `path` (`field!(name)`, `field!(style.size)`, `field!(0.title)`): field names
|
||||
/// and tuple indices only.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_tracked::{Tracked, field};
|
||||
/// # #[derive(craft_ui_macros::PlainData)] struct Style { size: f32 }
|
||||
/// # #[derive(craft_ui_macros::PlainData)] struct Doc { style: Style }
|
||||
/// let mut doc = Tracked::new(Doc { style: Style { size: 12.0 } });
|
||||
/// let before = doc.revision();
|
||||
/// let mut size = doc.field(field!(style.size));
|
||||
/// assert_eq!(*size.get(), 12.0);
|
||||
/// size.set(14.0);
|
||||
/// assert_ne!(doc.revision(), before);
|
||||
/// ```
|
||||
///
|
||||
/// A method call or an index is not a field path:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// use craft_tracked::{Tracked, field};
|
||||
/// let mut names = Tracked::new(vec![String::new()]);
|
||||
/// let _ = names.field(field!(first()));
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! field {
|
||||
($first:tt $(. $rest:tt)*) => {
|
||||
$crate::Projection::__from_field_path(|m| &m.$first $(.$rest)*, |m| &mut m.$first $(.$rest)*)
|
||||
};
|
||||
}
|
||||
|
||||
/// One field inside a [`Tracked`]: reading it leaves the revision, writing it moves it.
|
||||
pub struct Field<'a, M: PlainData, U> {
|
||||
tracked: &'a mut Tracked<M>,
|
||||
projection: Projection<M, U>,
|
||||
}
|
||||
|
||||
impl<M: PlainData, U> Field<'_, M, U> {
|
||||
/// The field's value.
|
||||
pub fn get(&self) -> &U {
|
||||
(self.projection.read)(&self.tracked.value)
|
||||
}
|
||||
|
||||
/// Replaces the field's value and moves the revision.
|
||||
pub fn set(&mut self, value: U) {
|
||||
self.edit(|field| *field = value);
|
||||
}
|
||||
|
||||
/// Changes the field through `f` and moves the revision.
|
||||
pub fn edit<R>(&mut self, f: impl FnOnce(&mut U) -> R) -> R {
|
||||
f((self.projection.write)(&mut **self.tracked))
|
||||
}
|
||||
|
||||
/// The same field, borrowed for a shorter time.
|
||||
pub fn reborrow(&mut self) -> Field<'_, M, U> {
|
||||
Field { tracked: &mut *self.tracked, projection: self.projection }
|
||||
}
|
||||
}
|
||||
|
||||
/// A field of some tracked value, for code that knows only the field's type (a value binding).
|
||||
pub trait Place<U> {
|
||||
/// The field's value.
|
||||
fn get(&self) -> &U;
|
||||
/// Replaces the field's value and moves the revision.
|
||||
fn set(&mut self, value: U);
|
||||
}
|
||||
|
||||
impl<M: PlainData, U> Place<U> for Field<'_, M, U> {
|
||||
fn get(&self) -> &U {
|
||||
Field::get(self)
|
||||
}
|
||||
|
||||
fn set(&mut self, value: U) {
|
||||
Field::set(self, value);
|
||||
}
|
||||
}
|
||||
|
||||
impl<U, P: Place<U> + ?Sized> Place<U> for &mut P {
|
||||
fn get(&self) -> &U {
|
||||
(**self).get()
|
||||
}
|
||||
|
||||
fn set(&mut self, value: U) {
|
||||
(**self).set(value);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Tracked;
|
||||
|
||||
struct Doc {
|
||||
name: String,
|
||||
size: (u32, u32),
|
||||
}
|
||||
|
||||
impl super::PlainData for Doc {}
|
||||
|
||||
#[test]
|
||||
fn the_revision_moves_on_writes_only_and_a_clone_is_a_new_source() {
|
||||
let mut doc = Tracked::new(Doc { name: "a".into(), size: (1, 2) });
|
||||
let start = doc.revision();
|
||||
assert_eq!(doc.name, "a");
|
||||
let size = doc.field(field!(size.1));
|
||||
assert_eq!(*size.get(), 2);
|
||||
assert_eq!(doc.revision(), start, "reads leave the revision");
|
||||
|
||||
doc.name.push('b');
|
||||
let after_deref = doc.revision();
|
||||
assert_eq!(after_deref.count, start.count + 1, "a `&mut` access moves it");
|
||||
doc.edit(|doc| doc.size.0 = 3);
|
||||
assert_eq!(doc.revision().count, start.count + 2, "an edit moves it");
|
||||
doc.field(field!(size.1)).set(4);
|
||||
doc.field(field!(name)).edit(|name| name.clear());
|
||||
assert_eq!(doc.revision().count, start.count + 4, "a field's set and edit move it");
|
||||
assert_eq!((doc.size, doc.name.as_str()), ((3, 4), ""));
|
||||
assert_eq!(doc.source(), start.source);
|
||||
|
||||
let mut a = Tracked::new(1_u32);
|
||||
let mut b = a.clone();
|
||||
assert_ne!(a.source(), b.source(), "a clone is a new source");
|
||||
*a += 1;
|
||||
*b += 2;
|
||||
assert_ne!(a.revision(), b.revision(), "two clones written apart never share a revision");
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,8 @@ accesskit = "0.25"
|
||||
craft-keymap = { workspace = true, features = ["egui"] }
|
||||
craft-theme = { workspace = true }
|
||||
craft-ui-macros = { workspace = true }
|
||||
# `Tracked`: app models whose revision keys memoized views and write-through bindings.
|
||||
craft-tracked = { workspace = true }
|
||||
craft-settings = { workspace = true }
|
||||
toml = { version = "1.1", default-features = false, features = ["std", "parse", "serde"] }
|
||||
egui = { workspace = true }
|
||||
|
||||
@@ -66,7 +66,8 @@ pub use container::{
|
||||
BandFill, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, LeastWidth,
|
||||
Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth,
|
||||
};
|
||||
pub use craft_ui_macros::{CommandSet, Component, Pattern, Props, register_contract};
|
||||
pub use craft_tracked::{Field, Place, PlainData, Projection, Revision, Tracked, field};
|
||||
pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract};
|
||||
#[doc(hidden)]
|
||||
pub use cx::THUMB;
|
||||
pub use cx::{
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::runtime::env::Message;
|
||||
use crate::runtime::memory::{MemoryStage, Savable, SaveKey, StageAccess};
|
||||
use crate::runtime::reads::{self, BindKey};
|
||||
use craft_behavior::{Applied, CanvasView, EditEvent, EditEvents, EditPolicy, Mixed, Value};
|
||||
use craft_tracked::{Place, PlainData, Projection, Tracked};
|
||||
use egui::Id;
|
||||
use egui::Response;
|
||||
use std::any::TypeId;
|
||||
@@ -106,6 +107,8 @@ enum Source<'a, T> {
|
||||
Mut(&'a mut T),
|
||||
/// Write-through for a multi-selection field.
|
||||
MutMixed(&'a mut Mixed<T>),
|
||||
/// Write-through to a field of a `Tracked`, whose revision moves only when an edit changes the field.
|
||||
Tracked(Box<dyn Place<T> + 'a>),
|
||||
/// No caller value: session memory under the component id, or the saved tier.
|
||||
Kept,
|
||||
}
|
||||
@@ -136,6 +139,13 @@ impl<'a, T: Value> Bind<'a, T> {
|
||||
Self::from_source(Source::MutMixed(v))
|
||||
}
|
||||
|
||||
/// Edits write through to one field of `tracked`, chosen with `craft_tracked::field!`
|
||||
/// (`Bind::tracked(&mut doc, field!(style.size))`). Making and reading the binding leaves the revision; only an
|
||||
/// edit that changes the field moves it, so a binding made every pass does not invalidate the value's readers.
|
||||
pub fn tracked<M: PlainData>(tracked: &'a mut Tracked<M>, field: Projection<M, T>) -> Self {
|
||||
Self::from_source(Source::Tracked(Box::new(tracked.field(field))))
|
||||
}
|
||||
|
||||
/// No caller value: the component keeps it in session memory under its id. Until something is stored, it reads
|
||||
/// as the [`reset`](Self::reset) value when one is given, else as nothing.
|
||||
pub fn kept() -> Self {
|
||||
@@ -188,6 +198,7 @@ impl<'a, T: Value> Bind<'a, T> {
|
||||
Source::Given(value) => Source::Given(value.clone()),
|
||||
Source::Mut(value) => Source::Mut(&mut **value),
|
||||
Source::MutMixed(value) => Source::MutMixed(&mut **value),
|
||||
Source::Tracked(place) => Source::Tracked(Box::new(&mut **place)),
|
||||
Source::Kept => Source::Kept,
|
||||
};
|
||||
let check = self.check.as_deref().map(|check| Box::new(move |value: &T| check(value)) as Box<Check<'_, T>>);
|
||||
@@ -211,6 +222,7 @@ impl<'a, T: Value> Bind<'a, T> {
|
||||
Source::Given(Mixed::Same(value)) => value == shown,
|
||||
Source::Mut(value) => **value == *shown,
|
||||
Source::MutMixed(Mixed::Same(value)) => value == shown,
|
||||
Source::Tracked(place) => place.get() == shown,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -221,6 +233,7 @@ impl<'a, T: Value> Bind<'a, T> {
|
||||
Source::Given(value) => SourceMut::Given(value),
|
||||
Source::Mut(value) => SourceMut::Mut(&mut **value),
|
||||
Source::MutMixed(value) => SourceMut::MutMixed(&mut **value),
|
||||
Source::Tracked(place) => SourceMut::Tracked(&mut **place),
|
||||
Source::Kept => SourceMut::Kept,
|
||||
};
|
||||
BindMut { source, policy: self.policy, check: self.check.as_deref(), save: self.save.as_ref(), reset: self.reset.as_ref() }
|
||||
@@ -237,6 +250,7 @@ enum SourceMut<'a, T> {
|
||||
Given(&'a Mixed<T>),
|
||||
Mut(&'a mut T),
|
||||
MutMixed(&'a mut Mixed<T>),
|
||||
Tracked(&'a mut dyn Place<T>),
|
||||
Kept,
|
||||
}
|
||||
|
||||
@@ -258,6 +272,7 @@ impl<T: Value> BindMut<'_, T> {
|
||||
SourceMut::Given(value) => Some((*value).clone()),
|
||||
SourceMut::Mut(value) => Some(Mixed::Same((**value).clone())),
|
||||
SourceMut::MutMixed(value) => Some((**value).clone()),
|
||||
SourceMut::Tracked(place) => Some(Mixed::Same(place.get().clone())),
|
||||
SourceMut::Kept => None,
|
||||
}
|
||||
}
|
||||
@@ -269,6 +284,7 @@ impl<T: Value> BindMut<'_, T> {
|
||||
SourceMut::Given(_) => None,
|
||||
SourceMut::Mut(value) => Some(BindKey::Place(std::ptr::from_ref::<T>(value) as usize, TypeId::of::<T>())),
|
||||
SourceMut::MutMixed(value) => Some(BindKey::Place(std::ptr::from_ref::<Mixed<T>>(value) as usize, TypeId::of::<Mixed<T>>())),
|
||||
SourceMut::Tracked(place) => Some(BindKey::Place(std::ptr::from_ref::<T>(place.get()) as usize, TypeId::of::<T>())),
|
||||
SourceMut::Kept => Some(match self.save {
|
||||
Some(save) => BindKey::Saved(Id::NULL.with(&save.key)),
|
||||
None => BindKey::Kept(id),
|
||||
@@ -290,6 +306,7 @@ impl<T: Value> BindMut<'_, T> {
|
||||
match &self.source {
|
||||
SourceMut::Given(Mixed::Same(value)) | SourceMut::MutMixed(Mixed::Same(value)) => value == shown,
|
||||
SourceMut::Mut(value) => **value == *shown,
|
||||
SourceMut::Tracked(place) => place.get() == shown,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -388,7 +405,9 @@ impl<T: Value> BindMut<'_, T> {
|
||||
pub(crate) fn writes(&self, event: &EditEvent<T>) -> bool {
|
||||
match self.source {
|
||||
SourceMut::Given(_) | SourceMut::Kept => false,
|
||||
SourceMut::Mut(_) | SourceMut::MutMixed(_) => self.policy == EditPolicy::WriteThrough || !matches!(event, EditEvent::Update { .. }),
|
||||
SourceMut::Mut(_) | SourceMut::MutMixed(_) | SourceMut::Tracked(_) => {
|
||||
self.policy == EditPolicy::WriteThrough || !matches!(event, EditEvent::Update { .. })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -401,6 +420,15 @@ impl<T: Value> BindMut<'_, T> {
|
||||
match &mut self.source {
|
||||
SourceMut::Mut(value) => event.apply(&mut **value),
|
||||
SourceMut::MutMixed(value) => event.apply_mixed(&mut **value),
|
||||
// Applied to a copy, so an event that leaves the field as it was does not move the revision.
|
||||
SourceMut::Tracked(place) => {
|
||||
let mut value = place.get().clone();
|
||||
let applied = event.apply(&mut value);
|
||||
if applied != Applied::Unchanged {
|
||||
place.set(value);
|
||||
}
|
||||
applied
|
||||
}
|
||||
SourceMut::Given(_) | SourceMut::Kept => Applied::Unchanged,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,4 +6,5 @@ mod hit_order;
|
||||
mod pages;
|
||||
mod pointer;
|
||||
mod style;
|
||||
mod tracked_bind;
|
||||
mod visited_type;
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
//! A write-through binding to a field of a `Tracked` value.
|
||||
|
||||
use craft_behavior::{EditEvent, Mixed};
|
||||
use craft_ui::contract::{Bind, PlainData, Tracked, field};
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
#[derive(PlainData)]
|
||||
struct Doc {
|
||||
title: String,
|
||||
size: f32,
|
||||
}
|
||||
|
||||
/// Making and reading the binding every pass leaves the revision, and so does an edit to the value the field already
|
||||
/// holds; an edit that changes the field moves it once and lands in the field.
|
||||
#[trial]
|
||||
fn a_tracked_binding_moves_the_revision_only_when_it_writes() {
|
||||
let mut doc = Tracked::new(Doc { title: "a".into(), size: 12.0 });
|
||||
let start = doc.revision();
|
||||
for _ in 0..3 {
|
||||
let mut bind = Bind::tracked(&mut doc, field!(size));
|
||||
assert_eq!(bind.reborrow().get(), Some(Mixed::Same(12.0)));
|
||||
}
|
||||
assert_eq!(doc.revision(), start, "bindings made and read every pass leave the revision");
|
||||
|
||||
let set = |after: f32| EditEvent::set(Mixed::Same(12.0), after, "Size".into(), None);
|
||||
Bind::tracked(&mut doc, field!(size)).reborrow().apply(&set(12.0));
|
||||
assert_eq!(doc.revision(), start, "an edit to the value the field holds leaves the revision");
|
||||
|
||||
Bind::tracked(&mut doc, field!(size)).reborrow().apply(&set(14.0));
|
||||
assert_eq!(doc.revision().count, start.count + 1, "a changing edit moves it once");
|
||||
assert_eq!((doc.size, doc.title.as_str()), (14.0, "a"));
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Macros of craft-ui: `#[derive(Component, Pattern, Props, ComponentStyle, TokenGroup, CommandSet, EnvValue)]`,
|
||||
//! Macros of craft-ui: `#[derive(Component, Pattern, Props, ComponentStyle, TokenGroup, CommandSet, EnvValue, PlainData)]`,
|
||||
//! `words!`, `#[story]`, `#[craft_ui::testing::trial]` and `register_contract!`.
|
||||
#![warn(missing_docs)]
|
||||
|
||||
@@ -6,6 +6,7 @@ mod command_set;
|
||||
mod component;
|
||||
mod env;
|
||||
mod pattern;
|
||||
mod plain;
|
||||
mod props;
|
||||
mod style;
|
||||
mod token_group;
|
||||
@@ -82,6 +83,16 @@ pub fn derive_props(input: TokenStream) -> TokenStream {
|
||||
expanded(props::derive(input.into()))
|
||||
}
|
||||
|
||||
/// Writes craft-tracked's `PlainData` marker and requires it of every field, so a field whose type can change behind
|
||||
/// a shared reference (interior mutability, raw pointers, `dyn` objects, closures) does not compile; the error names
|
||||
/// the field. Works on structs, tuple structs and enums. A field of a foreign plain type without an implementation
|
||||
/// carries `#[plain_data(assume = "why the type is plain")]`, which skips the check for that field; the reason is
|
||||
/// required.
|
||||
#[proc_macro_derive(PlainData, attributes(plain_data))]
|
||||
pub fn derive_plain_data(input: TokenStream) -> TokenStream {
|
||||
expanded(plain::derive(input.into()))
|
||||
}
|
||||
|
||||
/// Writes `ComponentStyle` from `#[style(surface)]`, `#[style(focus)]` and `#[style(metrics)]` fields (one each),
|
||||
/// any number of `#[style(text)]` (`TextLook`) and `#[style(icon)]` (`IconLook`) fields, and
|
||||
/// `#[style(variants = [..])]` on the type.
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
//! The field check the plain-data derives share, and `#[derive(PlainData)]`.
|
||||
//!
|
||||
//! A derive that must hold only plain data (`PlainData`, `MemoProps`) requires its trait of every field. The trait has
|
||||
//! no implementation for the types that can change behind a shared reference, so a field holding one is a compile
|
||||
//! error at that field. The rejected types, the one list both traits keep out:
|
||||
//!
|
||||
//! - `Cell`, `RefCell`, `OnceCell`, `LazyCell`, `UnsafeCell`
|
||||
//! - `Mutex`, `RwLock`, `OnceLock`, `LazyLock`, `Condvar` and every atomic
|
||||
//! - raw pointers (`*const T`, `*mut T`)
|
||||
//! - `dyn Trait` objects (`Box<dyn Fn()>` and every other) and closures
|
||||
//! - containers and smart pointers of any of these (`Arc<Mutex<T>>`, `Vec<Cell<u8>>`)
|
||||
//!
|
||||
//! A field of a foreign plain type that has no implementation (an egui `Rect`, a `serde_json::Value`) carries
|
||||
//! `#[plain_data(assume = "why the type is plain")]`, which skips the check for that field only. The reason is
|
||||
//! required.
|
||||
|
||||
use crate::util::ui_crate;
|
||||
use proc_macro_crate::{FoundCrate, crate_name};
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::{format_ident, quote, quote_spanned};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::visit::Visit;
|
||||
use syn::{Data, DeriveInput};
|
||||
|
||||
/// The impl generics, with a bound for every checked field whose type names a type parameter, and the item that
|
||||
/// checks every other checked field.
|
||||
pub(crate) struct FieldChecks {
|
||||
pub(crate) generics: syn::Generics,
|
||||
pub(crate) checks: TokenStream,
|
||||
}
|
||||
|
||||
/// Requires `trait_path` of every field of `input` (structs, tuple structs, enums; a union is an error). A field whose
|
||||
/// type names a type parameter gets a bound on the impl; a field of a concrete type is checked by a generated
|
||||
/// `check::<Field>()` spanned at the field's type, so the error points at the field, and a recursive type (a node
|
||||
/// holding `Vec<Self>`) does not make its impl require itself. With `assume` set to an attribute name, a field
|
||||
/// carrying `#[<assume>(assume = "reason")]` is not checked.
|
||||
pub(crate) fn field_checks(input: &DeriveInput, trait_path: &TokenStream, assume: Option<&str>) -> syn::Result<FieldChecks> {
|
||||
let fields: Vec<&syn::Field> = match &input.data {
|
||||
Data::Struct(data) => data.fields.iter().collect(),
|
||||
Data::Enum(data) => data.variants.iter().flat_map(|variant| variant.fields.iter()).collect(),
|
||||
Data::Union(data) => return Err(syn::Error::new(data.union_token.span(), "a union cannot hold only plain data")),
|
||||
};
|
||||
let mut generics = input.generics.clone();
|
||||
let params: Vec<syn::Ident> = input.generics.type_params().map(|param| param.ident.clone()).collect();
|
||||
let where_clause = generics.make_where_clause();
|
||||
let mut concrete = Vec::new();
|
||||
for field in fields {
|
||||
if let Some(name) = assume
|
||||
&& assumed(field, name)?
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let ty = &field.ty;
|
||||
if mentions(ty, ¶ms) {
|
||||
where_clause.predicates.push(syn::parse2(quote_spanned!(ty.span()=> #ty: #trait_path))?);
|
||||
} else {
|
||||
concrete.push(ty);
|
||||
}
|
||||
}
|
||||
let (impl_generics, _, where_clause) = generics.split_for_impl();
|
||||
let each = concrete.iter().map(|ty| quote_spanned!(ty.span()=> check::<#ty>();));
|
||||
let checks = quote! {
|
||||
const _: () = {
|
||||
#[allow(dead_code, clippy::extra_unused_type_parameters)]
|
||||
fn check<T: ?Sized + #trait_path>() {}
|
||||
#[allow(dead_code)]
|
||||
fn fields #impl_generics () #where_clause {
|
||||
#(#each)*
|
||||
}
|
||||
};
|
||||
};
|
||||
Ok(FieldChecks { generics, checks })
|
||||
}
|
||||
|
||||
/// Whether `field` carries `#[<name>(assume = "reason")]`. Any other content of the attribute, or an empty reason, is
|
||||
/// an error.
|
||||
fn assumed(field: &syn::Field, name: &str) -> syn::Result<bool> {
|
||||
let mut found = false;
|
||||
for attr in field.attrs.iter().filter(|attr| attr.path().is_ident(name)) {
|
||||
attr.parse_nested_meta(|meta| {
|
||||
if !meta.path.is_ident("assume") {
|
||||
return Err(meta.error(format!("expected `#[{name}(assume = \"why the type is plain\")]`")));
|
||||
}
|
||||
let reason: syn::LitStr = meta.value()?.parse()?;
|
||||
if reason.value().trim().is_empty() {
|
||||
return Err(syn::Error::new(reason.span(), "`assume` needs a reason: why this field's type is plain data"));
|
||||
}
|
||||
found = true;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// Whether `ty` names one of the type parameters `params`.
|
||||
fn mentions(ty: &syn::Type, params: &[syn::Ident]) -> bool {
|
||||
struct Finder<'p> {
|
||||
params: &'p [syn::Ident],
|
||||
found: bool,
|
||||
}
|
||||
impl<'ast> Visit<'ast> for Finder<'_> {
|
||||
fn visit_path(&mut self, path: &'ast syn::Path) {
|
||||
if path.leading_colon.is_none() && path.segments.first().is_some_and(|segment| self.params.contains(&segment.ident)) {
|
||||
self.found = true;
|
||||
}
|
||||
syn::visit::visit_path(self, path);
|
||||
}
|
||||
}
|
||||
let mut finder = Finder { params, found: false };
|
||||
finder.visit_type(ty);
|
||||
finder.found
|
||||
}
|
||||
|
||||
/// The path of craft-tracked as the crate being compiled reaches it: the facade's `tracked` module, a direct
|
||||
/// dependency (`::craft_tracked` in craft-tracked itself, which declares that name), or the framework's re-export in
|
||||
/// `contract`.
|
||||
fn tracked_crate() -> TokenStream {
|
||||
match crate_name("craft") {
|
||||
Ok(FoundCrate::Name(name)) => {
|
||||
let name = format_ident!("{name}");
|
||||
return quote!(::#name::tracked);
|
||||
}
|
||||
Ok(FoundCrate::Itself) => return quote!(::craft::tracked),
|
||||
Err(_) => {}
|
||||
}
|
||||
match crate_name("craft-tracked") {
|
||||
Ok(FoundCrate::Name(name)) => {
|
||||
let name = format_ident!("{name}");
|
||||
quote!(::#name)
|
||||
}
|
||||
Ok(FoundCrate::Itself) => quote!(::craft_tracked),
|
||||
Err(_) => {
|
||||
let k = ui_crate();
|
||||
quote!(#k::contract)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `#[derive(PlainData)]`: the marker, required of every field not marked `#[plain_data(assume = "..")]`.
|
||||
pub(crate) fn derive(input: TokenStream) -> syn::Result<TokenStream> {
|
||||
let input: DeriveInput = syn::parse2(input)?;
|
||||
let k = tracked_crate();
|
||||
let trait_path = quote!(#k::PlainData);
|
||||
let FieldChecks { generics, checks } = field_checks(&input, &trait_path, Some("plain_data"))?;
|
||||
let ident = &input.ident;
|
||||
let (impl_generics, _, where_clause) = generics.split_for_impl();
|
||||
let (_, type_generics, _) = input.generics.split_for_impl();
|
||||
Ok(quote! {
|
||||
#[automatically_derived]
|
||||
impl #impl_generics #trait_path for #ident #type_generics #where_clause {}
|
||||
|
||||
#checks
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user