mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-24 16:07:51 +00:00
dialogs-w5: net change of 3 commits
- dialogs-w5: written by an agent - dialogs-w5: Integration: a closed container ends its shown life at once (dialogs run round) - dialogs-w5: Integration: a closed dialog runs no pipeline; a hold opener's dwell is the opener's (dialogs run round)
This commit is contained in:
@@ -38,7 +38,7 @@ pub(super) fn open_now<C: Container>(comp: &mut C, stage: &mut MemoryStage, id:
|
||||
/// Whether the layer-like container `id` shows nothing this pass: closed, past its exit fade, with no close waiting
|
||||
/// for it. The read step and the mount host would decide the same; a peek stage decides it, so a container found open
|
||||
/// runs with nothing applied twice. A closed one writes what deciding changed (a hold's dwell, its slot's first value)
|
||||
/// as its read step would have, outside a sizing pass.
|
||||
/// as its read step would have, outside a sizing pass, and stamps no `Seen`: it is not shown.
|
||||
pub(crate) fn unshown<C: Container>(comp: &mut C, ctx: &Context, id: Id, props: &ContainerProps, sizing: bool) -> bool {
|
||||
if !matches!(props.mount, Mount::Layer(_) | Mount::FullWindow | Mount::Viewport { .. }) {
|
||||
return false;
|
||||
@@ -50,7 +50,7 @@ pub(crate) fn unshown<C: Container>(comp: &mut C, ctx: &Context, id: Id, props:
|
||||
return false;
|
||||
}
|
||||
if !sizing {
|
||||
let mut stage = MemoryStage::open(ctx, id);
|
||||
let mut stage = MemoryStage::open_after(ctx, id, id);
|
||||
let open = open_now(comp, &mut stage, id, props);
|
||||
debug_assert!(!open, "a peek and a real stage decide the same open state");
|
||||
stage.write_back();
|
||||
|
||||
@@ -24,7 +24,11 @@ pub(crate) fn opener_open(stage: &mut MemoryStage, first: &Opener) -> bool {
|
||||
let ctx = stage.ctx().clone();
|
||||
let frame = crate::runtime::egui::pass::root_frame_nr(&ctx);
|
||||
let held = first.all().find(|opener| opener.trigger == Trigger::Hold).map(|opener| {
|
||||
let started = dwell(&ctx, stage, opener.id, "dwell", opener.pressed, HOLD);
|
||||
// The dwell is the opener's: recorded under its id, it goes with the opener's eviction whether the container
|
||||
// shows or not.
|
||||
let mut own = if stage.is_peek() { MemoryStage::open_peek(&ctx, opener.id) } else { MemoryStage::open_after(&ctx, opener.id, opener.id) };
|
||||
let started = dwell(&ctx, &mut own, opener.id, "dwell", opener.pressed, HOLD);
|
||||
own.write_back();
|
||||
(opener, started)
|
||||
});
|
||||
let slot = stage.session::<OpenerOpen>(sub(first.id, "opens"));
|
||||
|
||||
@@ -536,8 +536,10 @@ pub(crate) fn show_container<C: Container, R>(
|
||||
Inner { output, inner, settle }
|
||||
}
|
||||
|
||||
/// A layer-like container that shows nothing this pass runs no pipeline: it takes its id as step 3 would, forgets
|
||||
/// its layer and returns its output's unshown form. `None` when it shows, or when its output has no unshown form.
|
||||
/// A layer-like container that shows nothing this pass runs no pipeline: it takes its id as step 3 would, without
|
||||
/// registering it, and returns its output's unshown form. Its shown life ends at once: the first pass it shows
|
||||
/// nothing forgets its layer and drops its shown and press entries, so a reopen is a first pass. `None` when it
|
||||
/// shows, or when its output has no unshown form.
|
||||
fn unshown<C: Container>(comp: &mut C, ui: &Ui) -> Option<C::Output> {
|
||||
let props = comp.props(Internal::new());
|
||||
if matches!(props.mount, crate::contract::Mount::Inline | crate::contract::Mount::Pane(_) | crate::contract::Mount::Window { .. }) {
|
||||
@@ -552,9 +554,13 @@ fn unshown<C: Container>(comp: &mut C, ui: &Ui) -> Option<C::Output> {
|
||||
if !crate::contract::body::unshown(comp, ui.ctx(), id, &props, sizing) {
|
||||
return None;
|
||||
}
|
||||
steps::id(ui, &source, !sizing, true, facts.style_key, facts.name);
|
||||
steps::id(ui, &source, false, true, facts.style_key, facts.name);
|
||||
if !sizing {
|
||||
steps::claim_id(ui, id, facts.name);
|
||||
}
|
||||
if !sizing && crate::runtime::memory::owner_pass(ui.ctx(), id).is_some() {
|
||||
crate::contract::overlay::forget_layer(ui.ctx(), id, id);
|
||||
crate::runtime::memory::end_shown(ui.ctx(), id);
|
||||
}
|
||||
Some(output)
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ pub(crate) use apply::{ValueEdit, apply_values, rerun_after_edit};
|
||||
pub(crate) use env::{EnvStep, env, resolved, variants};
|
||||
pub(crate) use finish::{before_finish, inert_response, record_body_size, record_size, value_changed};
|
||||
pub(super) use id::measuring;
|
||||
pub(crate) use id::{draft, id, keeping_ids};
|
||||
pub(crate) use id::{claim_id, draft, id, keeping_ids};
|
||||
pub(crate) use label::scrub_by_label;
|
||||
pub(crate) use measure::{MeasureIn, guard, measure, measure_content, measure_cx, padding, whole};
|
||||
pub(crate) use paint::{Fade, UnderVeil, fade, next_shape, paint_focus, paint_part_layers, paint_surface, surface_ink, unfade};
|
||||
|
||||
@@ -61,7 +61,8 @@ pub(crate) fn keeping_ids<R>(ctx: &Context, f: impl FnOnce() -> (R, bool)) -> R
|
||||
|
||||
/// Step 3, id.
|
||||
///
|
||||
/// `register` is false for `measure_in`, which peeks, and in a sizing pass. `advance` is false only for
|
||||
/// `register` is false for `measure_in`, which peeks, in a sizing pass, and for a container that shows nothing, which
|
||||
/// claims its id with `claim_id`. `advance` is false only for
|
||||
/// `measure_in`: a sizing pass advances the ordinals, so its ids equal those of the pass that follows it.
|
||||
/// `ty` is the component's style key type and `name` its type name.
|
||||
pub(crate) fn id(ui: &Ui, source: &IdSource, register: bool, advance: bool, ty: TypeId, name: &'static str) -> Id {
|
||||
@@ -92,12 +93,21 @@ pub(crate) fn id(ui: &Ui, source: &IdSource, register: bool, advance: bool, ty:
|
||||
};
|
||||
if register {
|
||||
crate::runtime::memory::register_owner(ctx, id);
|
||||
let repeated =
|
||||
PerViewport::<Stamped<IdPass>>::with_pass(ctx, viewport, pass_nr, |pass, _| *pass = IdPass::default(), |pass| !pass.seen.insert(id));
|
||||
if repeated {
|
||||
log::warn!("{name} was shown twice with the id {id:?} in one pass");
|
||||
inspect::finding(ctx, inspect::Finding { rule: "duplicate-id", component: name, subject: format!("{id:?}") });
|
||||
}
|
||||
claim_id(ui, id, name);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Records `id` as taken in this pass and reports a second taker as a duplicate. Step 3 claims every id it registers;
|
||||
/// a container that shows nothing claims its id without registering it.
|
||||
pub(crate) fn claim_id(ui: &Ui, id: Id, name: &'static str) {
|
||||
let ctx = ui.ctx();
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let pass_nr = pass::pass_nr(ctx, viewport);
|
||||
let repeated =
|
||||
PerViewport::<Stamped<IdPass>>::with_pass(ctx, viewport, pass_nr, |pass, _| *pass = IdPass::default(), |pass| !pass.seen.insert(id));
|
||||
if repeated {
|
||||
log::warn!("{name} was shown twice with the id {id:?} in one pass");
|
||||
inspect::finding(ctx, inspect::Finding { rule: "duplicate-id", component: name, subject: format!("{id:?}") });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
use crate::runtime::egui::memory::{self as store, FastMap, Map, Removed, take_raw};
|
||||
use crate::runtime::egui::pass;
|
||||
use crate::runtime::env::Env;
|
||||
use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored};
|
||||
use crate::runtime::pass_state;
|
||||
use crate::runtime::pending::{self, Job, Pending};
|
||||
use craft_behavior::eviction::owner_due;
|
||||
use craft_host::Host;
|
||||
use craft_settings::Remembered;
|
||||
use egui::{Context, Id, ViewportId};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
@@ -88,7 +91,8 @@ pub trait Remember {
|
||||
fn press_slot<T: Slot>(&mut self) -> &mut Option<T>;
|
||||
/// The session slot: it goes only through `forget`.
|
||||
fn keep<T: Slot>(&mut self) -> &mut T;
|
||||
/// The saved slot of `key`: it goes only through `forget_saved`.
|
||||
/// The saved slot of `key`: it goes only through `forget_saved`. With a host in the frame it is loaded from the
|
||||
/// host's settings on first use and stored there when a pass changes it.
|
||||
fn saved<T: Savable>(&mut self, key: &SaveKey) -> &mut T;
|
||||
/// A read-only copy of the shown slot, for paint.
|
||||
fn recall<T: Slot>(&self) -> T;
|
||||
@@ -128,6 +132,70 @@ struct Entry {
|
||||
ended: Option<fn(&(dyn Any + Send + Sync)) -> bool>,
|
||||
/// The slot was in context data when the stage took it: the registry holds its record.
|
||||
recorded: bool,
|
||||
/// A SAVED entry of a real stage on a viewport with a host: what write-back needs to store a changed value.
|
||||
persist: Option<Persist>,
|
||||
}
|
||||
|
||||
/// How a SAVED entry reaches the host's store. The fn pointers are monomorphised where `T: Savable` is known, so
|
||||
/// write-back can serialize and store an entry whose type it does not name.
|
||||
struct Persist {
|
||||
key: SaveKey,
|
||||
host: Arc<Host>,
|
||||
/// The serialized form of the value the stage took; `None` when it does not serialize.
|
||||
before: Option<toml::Value>,
|
||||
form: fn(&(dyn Any + Send + Sync)) -> Option<toml::Value>,
|
||||
store: fn(&(dyn Any + Send + Sync), &Host, &SaveKey),
|
||||
}
|
||||
|
||||
/// The serialized form of a SAVED entry's value, the one the store keeps: TOML has no null, so an `Option` set to
|
||||
/// `None` has none.
|
||||
fn saved_form<T: Savable>(value: &(dyn Any + Send + Sync)) -> Option<toml::Value> {
|
||||
value.downcast_ref::<Wrapped<SAVED, T>>().and_then(|wrapped| toml::Value::try_from(&wrapped.0).ok())
|
||||
}
|
||||
|
||||
fn store_saved<T: Savable>(value: &(dyn Any + Send + Sync), host: &Host, key: &SaveKey) {
|
||||
if let Some(wrapped) = value.downcast_ref::<Wrapped<SAVED, T>>() {
|
||||
Remembered::<T>::new(key.as_str()).store(host, &wrapped.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the stored value of `key`, whatever its type: `Remembered::forget` reads no value.
|
||||
fn forget_stored(host: &Host, key: &SaveKey) {
|
||||
Remembered::<toml::Value>::new(key.as_str()).forget(host);
|
||||
}
|
||||
|
||||
/// The SAVED tier's one load: when the slot of `key` is not in context data and the running viewport has a host, the
|
||||
/// stored value enters context data with its registry record, so later passes take it from there and `forget_saved`
|
||||
/// finds it. A stored value that no longer fits `T`, or none, loads as `T::default()`. Without a host the tier is
|
||||
/// session only.
|
||||
fn load_saved<T: Savable>(ctx: &Context, key: &SaveKey) {
|
||||
let id = key.id();
|
||||
if store::exists::<Wrapped<SAVED, T>>(ctx, id) {
|
||||
return;
|
||||
}
|
||||
let Some(host) = Env::host_of(ctx) else { return };
|
||||
let value = Remembered::<T>::new(key.as_str()).recall(&host).unwrap_or_default();
|
||||
store::put(ctx, id, Wrapped::<SAVED, T>(value));
|
||||
pass_state::with::<Registry, _>(ctx, |reg| {
|
||||
reg.slots.insert((id, SAVED, TypeId::of::<T>()), SlotRecord { owner: id, remove: remove_slot::<SAVED, T> });
|
||||
});
|
||||
}
|
||||
|
||||
/// Stores every SAVED entry whose serialized form changed since the stage took it, and forgets the stored value of
|
||||
/// one that no longer serializes (`Remembered::store` skips such a value and would keep the old one). An unchanged
|
||||
/// value writes nothing. Called outside every lock: a host's `SectionStore` takes its own.
|
||||
fn persist_changed(entries: &[Entry]) {
|
||||
for entry in entries {
|
||||
let Some(persist) = &entry.persist else { continue };
|
||||
let after = (persist.form)(&*entry.value);
|
||||
if after == persist.before {
|
||||
continue;
|
||||
}
|
||||
match after {
|
||||
Some(_) => (persist.store)(&*entry.value, &persist.host, &persist.key),
|
||||
None => forget_stored(&persist.host, &persist.key),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The last registration of an owner: the component id registered at step 3 whose pipeline opened a stage.
|
||||
@@ -183,19 +251,35 @@ pub(crate) fn evict(ctx: &Context) {
|
||||
return;
|
||||
}
|
||||
reg.owners.retain(|id, _| !dead.contains(id));
|
||||
let gone: Vec<(Id, u8, TypeId)> =
|
||||
reg.slots.iter().filter(|(k, r)| dead.contains(&r.owner) && matches!(k.1, SHOWN | PRESS)).map(|(k, _)| *k).collect();
|
||||
let mut moved: Vec<Removed> = Vec::new();
|
||||
for key in gone {
|
||||
if let Some(rec) = reg.slots.remove(&key) {
|
||||
moved.extend(store::locked(ctx, |data| (rec.remove)(data, key.0)));
|
||||
}
|
||||
}
|
||||
let moved = take_shown(ctx, reg, |owner| dead.contains(&owner));
|
||||
QUEUED.fetch_add(moved.len(), Ordering::Release);
|
||||
reg.graveyard.extend(moved);
|
||||
});
|
||||
}
|
||||
|
||||
/// Ends the shown life of `owner` at once, as eviction does once its grace ran out: its shown and press entries go
|
||||
/// with its record. A container that shows nothing ends its own (`run::typed::unshown`), and a dialog host the one of
|
||||
/// a dialog it removes (`overlay::end_stack_dialog`), so a reopen is a first pass. Both run outside every lock and
|
||||
/// hook, so the slots drop here and their dispose hooks (a running gesture's removal) report in this pass. False when
|
||||
/// `owner` has no record: its life ended already, or it never ran.
|
||||
pub(crate) fn end_shown(ctx: &Context, owner: Id) -> bool {
|
||||
let moved = pass_state::with::<Registry, _>(ctx, |reg| reg.owners.remove(&owner).map(|_| take_shown(ctx, reg, |of| of == owner)));
|
||||
moved.is_some()
|
||||
}
|
||||
|
||||
/// Takes the shown and press slots of the owners `ended` picks out of context data (a press entry whose press never
|
||||
/// ended goes with its owner).
|
||||
fn take_shown(ctx: &Context, reg: &mut Registry, ended: impl Fn(Id) -> bool) -> Vec<Removed> {
|
||||
let gone: Vec<(Id, u8, TypeId)> = reg.slots.iter().filter(|(k, r)| ended(r.owner) && matches!(k.1, SHOWN | PRESS)).map(|(k, _)| *k).collect();
|
||||
let mut moved: Vec<Removed> = Vec::new();
|
||||
for key in gone {
|
||||
if let Some(rec) = reg.slots.remove(&key) {
|
||||
moved.extend(store::locked(ctx, |data| (rec.remove)(data, key.0)));
|
||||
}
|
||||
}
|
||||
moved
|
||||
}
|
||||
|
||||
/// Slots queued for disposal across all contexts, so a run with nothing queued takes no lock.
|
||||
static QUEUED: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
@@ -208,20 +292,27 @@ pub(crate) fn forget(ctx: &Context, id: Id) {
|
||||
/// The saved value under `key`, outside a dialog: an app reads one SAVED value through the same store the dialogs'
|
||||
/// remembered fields use.
|
||||
pub fn saved_value<T: Savable>(ctx: &Context, key: &SaveKey) -> T {
|
||||
let _ = (ctx, key);
|
||||
todo!("dl.K13")
|
||||
MemoryStage::peek_saved(ctx, key)
|
||||
}
|
||||
|
||||
/// Writes `value` as the saved value under `key`, outside a dialog.
|
||||
/// Writes `value` as the saved value under `key`, outside a dialog. It is stored through the host when its
|
||||
/// serialized form differs from the saved one.
|
||||
pub fn set_saved_value<T: Savable>(ctx: &Context, key: &SaveKey, value: T) {
|
||||
let _ = (ctx, key, value);
|
||||
todo!("dl.K13")
|
||||
let id = key.id();
|
||||
let mut stage = MemoryStage::new(ctx, id, id, false);
|
||||
// No component shows under the key's id, so the stage stamps no `Seen` for it.
|
||||
stage.touched.get_mut().clear();
|
||||
*stage.saved::<T>(key) = value;
|
||||
stage.write_back();
|
||||
}
|
||||
|
||||
/// Removes the saved slots of `key`. The only way a saved slot goes.
|
||||
/// Removes the saved slots of `key` and the value stored under it. The only way a saved slot goes.
|
||||
#[cfg_attr(not(feature = "testing"), expect(dead_code, reason = "used by the commands (F3)"))]
|
||||
pub(crate) fn forget_saved(ctx: &Context, key: &SaveKey) {
|
||||
forget_tier(ctx, key.id(), SAVED);
|
||||
if let Some(host) = Env::host_of(ctx) {
|
||||
forget_stored(&host, key);
|
||||
}
|
||||
}
|
||||
|
||||
fn forget_tier(ctx: &Context, id: Id, tier: u8) {
|
||||
@@ -330,9 +421,9 @@ impl MemoryStage {
|
||||
stage
|
||||
}
|
||||
|
||||
/// A stage over `base` opened after the pass's real run wrote its own back: it claims nothing and stamps no
|
||||
/// `Seen` for `base` (`appeared()` is unchanged), and the slots it creates are recorded under `owner`, so they
|
||||
/// are evicted with the container.
|
||||
/// A stage over `base` that claims nothing and stamps no `Seen` for `base` (`appeared()` is unchanged): opened
|
||||
/// after the pass's real run wrote its own back, by a container that shows nothing, or for a slot of another
|
||||
/// component (a hold opener's dwell). The slots it creates are recorded under `owner`, so they are evicted with it.
|
||||
pub(crate) fn open_after(ctx: &Context, base: Id, owner: Id) -> Self {
|
||||
let stage = Self::new(ctx, base, owner, false);
|
||||
stage.touched.borrow_mut().clear();
|
||||
@@ -389,6 +480,7 @@ impl MemoryStage {
|
||||
/// Read-only access to a saved slot, as `peek` does for a shown one.
|
||||
#[doc(hidden)]
|
||||
pub fn peek_saved<T: Savable>(ctx: &Context, key: &SaveKey) -> T {
|
||||
load_saved::<T>(ctx, key);
|
||||
store::peek_clone::<Wrapped<SAVED, T>>(ctx, key.id()).map(|wrapped| wrapped.0).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -429,7 +521,15 @@ impl MemoryStage {
|
||||
_ => (Box::new(Wrapped::<TIER, T>::default()), false),
|
||||
}
|
||||
};
|
||||
self.entries.push(Entry { key, value, write_back: write_back::<TIER, T>, remove: remove_slot::<TIER, T>, ended: None, recorded });
|
||||
self.entries.push(Entry {
|
||||
key,
|
||||
value,
|
||||
write_back: write_back::<TIER, T>,
|
||||
remove: remove_slot::<TIER, T>,
|
||||
ended: None,
|
||||
recorded,
|
||||
persist: None,
|
||||
});
|
||||
self.entries.len() - 1
|
||||
}
|
||||
};
|
||||
@@ -458,7 +558,21 @@ impl MemoryStage {
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn saved<T: Savable>(&mut self, key: &SaveKey) -> &mut T {
|
||||
self.slot::<SAVED, T>(key.id())
|
||||
let id = key.id();
|
||||
let entry_key = (SAVED, TypeId::of::<T>(), id);
|
||||
if !self.entries.iter().any(|entry| entry.key == entry_key) {
|
||||
load_saved::<T>(&self.ctx, key);
|
||||
self.slot::<SAVED, T>(id);
|
||||
// A peek stage writes nothing back, so it never stores.
|
||||
let host = if self.peek_only { None } else { Env::host_of(&self.ctx) };
|
||||
if let Some(host) = host
|
||||
&& let Some(entry) = self.entries.iter_mut().find(|entry| entry.key == entry_key)
|
||||
{
|
||||
let before = saved_form::<T>(&*entry.value);
|
||||
entry.persist = Some(Persist { key: key.clone(), host, before, form: saved_form::<T>, store: store_saved::<T> });
|
||||
}
|
||||
}
|
||||
self.slot::<SAVED, T>(id)
|
||||
}
|
||||
|
||||
/// The shown slot of `id`, moved out: it is read once. `None` when nothing was written under it.
|
||||
@@ -501,6 +615,7 @@ impl MemoryStage {
|
||||
let (owner, retags) = (self.owner, self.retags);
|
||||
let touched = self.touched.into_inner();
|
||||
let ctx = self.ctx.clone();
|
||||
persist_changed(&self.entries);
|
||||
let mut ended: Vec<(Id, u8, TypeId)> = Vec::new();
|
||||
let mut record: Vec<((Id, u8, TypeId), Remover)> = Vec::new();
|
||||
// One data lock for every slot; the values they replace and the ended presses drop outside it.
|
||||
|
||||
@@ -157,6 +157,8 @@ pub struct OpenEntry {
|
||||
pub(crate) region: Option<Rect>,
|
||||
/// The layer's place on its dialog stack (`stack_place`): the modal families of one stack stack in its order.
|
||||
pub(crate) place: Option<usize>,
|
||||
/// The dialog of a dialog host the layer shows for (`stack_place`).
|
||||
dialog: Option<Id>,
|
||||
}
|
||||
|
||||
impl OpenEntry {
|
||||
@@ -179,6 +181,7 @@ impl OpenEntry {
|
||||
window: false,
|
||||
region: None,
|
||||
place: None,
|
||||
dialog: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,8 +221,9 @@ pub(crate) struct Pass {
|
||||
pressed_outside: Vec<Id>,
|
||||
/// The popup a press that opened it ended on, and where, this pass.
|
||||
dragged_release: Option<(Id, Pos2)>,
|
||||
/// The dialog stack place of the layers recorded now (`stack_place`).
|
||||
/// The dialog stack place of the layers recorded now, and the dialog they show for (`stack_place`).
|
||||
place: Option<usize>,
|
||||
dialog: Option<Id>,
|
||||
}
|
||||
|
||||
/// The top modal layer of a viewport: its id and the scrim under it.
|
||||
@@ -277,6 +281,7 @@ fn with_pass<R>(ctx: &Context, f: impl FnOnce(&mut Pass) -> R) -> R {
|
||||
pass.pressed_outside.clear();
|
||||
pass.dragged_release = None;
|
||||
pass.place = None;
|
||||
pass.dialog = None;
|
||||
},
|
||||
f,
|
||||
)
|
||||
@@ -610,17 +615,29 @@ pub(crate) fn note_peers(ctx: &Context, id: Id, peers: Vec<Rect>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Runs `show` with the layers it records at `place` on the dialog stack: a dialog host shows each open dialog
|
||||
/// inside its stack place, bottom first, and the modal families of the stack then stack in that order whatever
|
||||
/// opened, appeared or was pressed last. Families without a place keep their raise order.
|
||||
/// Runs `show` with the layers it records at `place` on the dialog stack, for the host's `dialog`: a dialog host shows
|
||||
/// each open dialog inside its stack place, bottom first, and the modal families of the stack then stack in that order
|
||||
/// whatever opened, appeared or was pressed last. Families without a place keep their raise order.
|
||||
#[doc(hidden)]
|
||||
pub fn stack_place<R>(ctx: &Context, place: usize, show: impl FnOnce() -> R) -> R {
|
||||
let outer = with_pass(ctx, |pass| pass.place.replace(place));
|
||||
pub fn stack_place<R>(ctx: &Context, place: usize, dialog: Id, show: impl FnOnce() -> R) -> R {
|
||||
let outer = with_pass(ctx, |pass| (pass.place.replace(place), pass.dialog.replace(dialog)));
|
||||
let out = show();
|
||||
with_pass(ctx, |pass| pass.place = outer);
|
||||
with_pass(ctx, |pass| (pass.place, pass.dialog) = outer);
|
||||
out
|
||||
}
|
||||
|
||||
/// A dialog host removed `dialog`: the layers it showed for it (`stack_place`) in the running or the last pass end
|
||||
/// their shown life at once (`memory::end_shown`), as a container that shows nothing does, so the next open of the
|
||||
/// dialog is a first pass.
|
||||
#[doc(hidden)]
|
||||
pub fn end_stack_dialog(ctx: &Context, dialog: Id) {
|
||||
let shown: Vec<Id> =
|
||||
with_pass(ctx, |pass| pass.current.iter().chain(&pass.last).filter(|entry| entry.dialog == Some(dialog)).map(|entry| entry.id).collect());
|
||||
for id in shown {
|
||||
crate::runtime::memory::end_shown(ctx, id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the layer shown in this pass, parent first: a layer is recorded once its body ran, after the layers opened
|
||||
/// from inside it, so it goes in front of them, and every layer then stacks above the layer it was opened from. A
|
||||
/// layer shown again in a discarded pass replaces its entry.
|
||||
@@ -628,6 +645,7 @@ pub(crate) fn record(ctx: &Context, mut entry: OpenEntry) {
|
||||
crate::runtime::replay::block(ctx);
|
||||
with_pass(ctx, |pass| {
|
||||
entry.place = entry.place.or(pass.place);
|
||||
entry.dialog = entry.dialog.or(pass.dialog);
|
||||
if let Some(at) = pass.current.iter().position(|recorded| recorded.id == entry.id) {
|
||||
pass.current[at] = entry;
|
||||
return;
|
||||
|
||||
@@ -1,10 +1,116 @@
|
||||
//! Memory lifetimes, eviction by owner and the runtime sub-id derivation.
|
||||
|
||||
use craft_ui::runtime::memory::{Remember, SaveKey};
|
||||
use craft_host::{AppInfo, Host, MemorySections, SectionStore};
|
||||
use craft_ui::contract::{
|
||||
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, Overlay, Props as _, Role, ShowContainer as _,
|
||||
};
|
||||
use craft_ui::runtime::memory::{Remember, SaveKey, saved_value, set_saved_value};
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::memory::{Stage, dispose_evicted, forget, forget_saved, global, records_written};
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use craft_ui_test_kit::contract::PlainStyle;
|
||||
use egui::{Id, Response, Ui, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
const PLACE: SaveKey = SaveKey::new("craft_tests.place");
|
||||
const KEPT: SaveKey = SaveKey::new("craft_tests.kept");
|
||||
|
||||
/// A host's settings store that counts its writes.
|
||||
#[derive(Default)]
|
||||
struct Counted {
|
||||
sections: MemorySections,
|
||||
writes: AtomicUsize,
|
||||
}
|
||||
|
||||
impl Counted {
|
||||
fn writes(&self) -> usize {
|
||||
self.writes.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
impl SectionStore for Counted {
|
||||
fn read(&self, key: &str) -> Option<toml::Table> {
|
||||
self.sections.read(key)
|
||||
}
|
||||
|
||||
fn write(&self, key: &str, table: toml::Table) {
|
||||
self.writes.fetch_add(1, Ordering::Relaxed);
|
||||
self.sections.write(key, table);
|
||||
}
|
||||
}
|
||||
|
||||
fn counted_host() -> (Arc<Counted>, Arc<Host>) {
|
||||
let store = Arc::new(Counted::default());
|
||||
let host = Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).settings(store.clone()).build());
|
||||
(store, host)
|
||||
}
|
||||
|
||||
/// The saved `u32` of `KEPT` a stage of `id` reads in one frame of `frames`.
|
||||
fn read_kept(frames: &mut Frames, id: Id) -> u32 {
|
||||
let mut read = 0;
|
||||
frames.frame(vec![], |ui| {
|
||||
let mut stage = Stage::open(ui.ctx(), id);
|
||||
read = *stage.saved::<u32>(&KEPT);
|
||||
stage.finish();
|
||||
});
|
||||
read
|
||||
}
|
||||
|
||||
/// The SAVED tier persists through the frame's host: a value written in one context is read by a new context over
|
||||
/// the same host, an unchanged value (a rerun pass, later frames) is never stored again, and `forget_saved` forgets
|
||||
/// the stored value too.
|
||||
#[trial]
|
||||
fn a_saved_slot_survives_a_new_context_with_the_same_host_and_is_stored_once_per_change() {
|
||||
let (store, host) = counted_host();
|
||||
let id = global("saver", ());
|
||||
let mut frames = Frames::new();
|
||||
frames.host(host.clone());
|
||||
let mut first = true;
|
||||
let passes = frames.frame(vec![], |ui| {
|
||||
if std::mem::take(&mut first) {
|
||||
ui.ctx().request_discard("the writing frame runs twice");
|
||||
}
|
||||
let mut stage = Stage::open(ui.ctx(), id);
|
||||
*stage.saved::<u32>(&KEPT) = 6;
|
||||
stage.finish();
|
||||
});
|
||||
assert_eq!(passes, 2, "the writing frame reran its pass");
|
||||
let read = [read_kept(&mut frames, id), read_kept(&mut frames, id)];
|
||||
assert_eq!(read, [6, 6]);
|
||||
assert_eq!(store.writes(), 1, "the value is stored once: a rerun pass and later frames that leave it unchanged store nothing");
|
||||
|
||||
let mut again = Frames::new();
|
||||
again.host(host.clone());
|
||||
assert_eq!(read_kept(&mut again, id), 6, "a new context over the same host reads the stored value");
|
||||
forget_saved(&again.ctx, &KEPT);
|
||||
|
||||
let mut third = Frames::new();
|
||||
third.host(host);
|
||||
assert_eq!(read_kept(&mut third, id), 0, "forget_saved forgot the stored value");
|
||||
}
|
||||
|
||||
/// L-12: a value written with `set_saved_value` is read in the next pass by `saved_value` and by a stage's
|
||||
/// `Remember::saved`, through the one slot, and is stored once per change.
|
||||
#[trial]
|
||||
fn set_saved_value_is_read_back_by_saved_value_and_stored_once() {
|
||||
let (store, host) = counted_host();
|
||||
let id = global("saved_value_reader", ());
|
||||
let mut frames = Frames::new();
|
||||
frames.host(host);
|
||||
frames.frame(vec![], |ui| set_saved_value(ui.ctx(), &KEPT, 7u32));
|
||||
let mut read = Vec::new();
|
||||
frames.frame(vec![], |ui| {
|
||||
read.push(saved_value::<u32>(ui.ctx(), &KEPT));
|
||||
set_saved_value(ui.ctx(), &KEPT, 7u32);
|
||||
});
|
||||
read.push(read_kept(&mut frames, id));
|
||||
assert_eq!(read, vec![7, 7], "saved_value and a stage read the value set_saved_value wrote");
|
||||
assert_eq!(store.writes(), 1, "writing the same value again stores nothing");
|
||||
frames.frame(vec![], |ui| set_saved_value(ui.ctx(), &KEPT, 8u32));
|
||||
assert_eq!(store.writes(), 2, "a changed value is stored once");
|
||||
}
|
||||
|
||||
/// The lifetimes of 7.2, through `Remember`: shown entries go with their owner; session and saved ones only
|
||||
/// through `forget` and `forget_saved`; a press entry goes when its press ends.
|
||||
@@ -110,3 +216,86 @@ fn a_settled_stage_records_no_slot_again() {
|
||||
});
|
||||
assert!(records_written(&frames.ctx) >= first + 3, "an owning stage records what it writes in every frame");
|
||||
}
|
||||
|
||||
/// A layer with a bound open state whose output has an unshown form: closed, it runs no pipeline.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
#[component(container)]
|
||||
struct Sheet<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
#[container]
|
||||
props: ContainerProps,
|
||||
open: Bind<'a, bool>,
|
||||
}
|
||||
|
||||
struct SheetOut(Response);
|
||||
|
||||
impl Outcome for SheetOut {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.0
|
||||
}
|
||||
|
||||
fn unshown(response: Response) -> Option<Self> {
|
||||
Some(SheetOut(response))
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for Sheet<'_> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
type Style = PlainStyle;
|
||||
type Output = SheetOut;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: SheetStyleKey) -> PlainStyle {
|
||||
PlainStyle::min(Vec2::new(120.0, 60.0))
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> SheetOut {
|
||||
SheetOut(cx.response.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Container for Sheet<'_> {
|
||||
fn open(&mut self) -> Option<BindMut<'_, bool>> {
|
||||
Some(self.open.reborrow())
|
||||
}
|
||||
}
|
||||
|
||||
/// A container that shows nothing ends its shown life at once: closed, its body runs no more, and its next open is a
|
||||
/// first pass with nothing kept, well inside the eviction grace. While it shows, its body keeps its entries.
|
||||
#[trial]
|
||||
fn a_closed_container_ends_its_shown_life_at_once_and_a_shown_one_keeps_it() {
|
||||
let open = Cell::new(true);
|
||||
// Each body run: whether it is the body's first pass, and how many passes its kept count has seen.
|
||||
let runs = RefCell::new(Vec::<(bool, u32)>::new());
|
||||
let mut show = |ui: &mut Ui| {
|
||||
let mut is_open = open.get();
|
||||
let props = ContainerProps::new().mount(Mount::Layer(Overlay::floating()));
|
||||
Sheet { common: Common::new(), props, open: Bind::bound(&mut is_open) }.id_salt("sheet").show(ui, |_, cx| {
|
||||
let kept = cx.memory::<u32>();
|
||||
*kept += 1;
|
||||
let kept = *kept;
|
||||
runs.borrow_mut().push((cx.appeared(), kept));
|
||||
});
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(4, &mut show);
|
||||
let shown = runs.borrow().clone();
|
||||
assert!(shown.first().is_some_and(|run| run.0), "the first open is a first pass");
|
||||
assert!(shown.last().is_some_and(|run| !run.0 && run.1 >= 3), "a shown body keeps its entries: {shown:?}");
|
||||
|
||||
open.set(false);
|
||||
frames.idle(2, &mut show);
|
||||
// Past the exit fade, and less than the 0.5 s an evicted owner waits.
|
||||
frames.advance(0.25);
|
||||
frames.idle(2, &mut show);
|
||||
let closed = runs.borrow().len();
|
||||
frames.idle(3, &mut show);
|
||||
assert_eq!(runs.borrow().len(), closed, "a closed container runs no body");
|
||||
|
||||
open.set(true);
|
||||
frames.idle(1, &mut show);
|
||||
let reopened = runs.borrow()[closed..].to_vec();
|
||||
assert!(reopened.first().is_some_and(|run| run.0 && run.1 == 1), "the reopen is a first pass with nothing kept: {reopened:?}");
|
||||
}
|
||||
|
||||
@@ -32,6 +32,11 @@ impl Outcome for DialogOutput {
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
|
||||
/// A closed dialog runs no pipeline: it neither closed nor picked in this pass.
|
||||
fn unshown(response: Response) -> Option<Self> {
|
||||
Some(DialogOutput { response, closed: None, picked: None })
|
||||
}
|
||||
}
|
||||
|
||||
impl DialogOutput {
|
||||
|
||||
@@ -187,3 +187,19 @@ fn cancel_or_escape_takes_the_dialogs_field_edits_back() {
|
||||
assert!(matches!(app.outer[..], [OuterEdit::Begin { id: first, .. }, _, OuterEdit::Begin { id: second, .. }] if first != second));
|
||||
}
|
||||
}
|
||||
|
||||
/// The app closing the dialog through its open binding takes the field edits back, as Cancel does.
|
||||
#[trial]
|
||||
fn a_close_through_the_open_binding_takes_the_dialogs_field_edits_back() {
|
||||
let (mut fixture, app) = dialog();
|
||||
edit_both(&mut fixture, &app);
|
||||
app.borrow_mut().open = false;
|
||||
// Past its exit fade the dialog shows nothing.
|
||||
fixture.settle();
|
||||
fixture.advance(1.0).idle(4);
|
||||
let mut app = app.borrow_mut();
|
||||
app.drain(fixture.ctx());
|
||||
assert!(!app.host.is_active(), "the close ends the dialog's gesture");
|
||||
assert!(app.doc.steps.is_empty(), "the close leaves no undo step: {:?}", app.doc.steps);
|
||||
assert_eq!(app.doc.values, Values::default(), "the close restores both values");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user