Bind pass services once for each component tree

This commit is contained in:
FredApps
2026-11-19 11:07:30 +01:00
parent cc808e7c07
commit ec09134007
5 changed files with 109 additions and 11 deletions
Generated
+1
View File
@@ -4208,6 +4208,7 @@ dependencies = [
"libtest-mimic",
"log",
"proc-macro2",
"scoped-tls",
"serde",
"skrifa 0.44.0",
"smallvec",
+1
View File
@@ -260,6 +260,7 @@ md5 = { package = "md-5", version = "0.10", default-features = false }
jxl-oxide = { version = "0.12", default-features = false }
jixel = "=0.3.4"
rayon = "1"
scoped-tls = "1"
smallvec = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+1
View File
@@ -48,6 +48,7 @@ craft-quit = { workspace = true }
craft-platform = { workspace = true, features = ["appearance"] }
craft-i18n = { workspace = true, features = ["collate"] }
log = "0.4"
scoped-tls = { workspace = true }
smallvec = { workspace = true }
inventory = "0.3.25"
serde = { workspace = true }
+8
View File
@@ -1385,6 +1385,14 @@ fn measured(t: &mut dyn Erased, input: &MeasureIn<'_>, style: &dyn StyleView, re
/// The pipeline: steps 1 to 17 for one component, whatever its type and shape. A component that takes a cell of a
/// `Grid` runs under the column group of its cell's column (`ColumnGroup::cell`).
pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option<TipFn<'_>>) {
if crate::runtime::pass_state::in_component_tree() {
return run_in_context(t, ui, at, tip);
}
let ctx = ui.ctx().clone();
crate::runtime::pass_state::with_component_tree(&ctx, || run_in_context(t, ui, at, tip));
}
fn run_in_context(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option<TipFn<'_>>) {
let cell = (matches!(at, ShowAt::Flow) && t.in_flow()).then(|| crate::layout::grid_cell(ui)).flatten();
match cell {
Some((grid, column, sized)) => {
+98 -11
View File
@@ -154,6 +154,11 @@ struct HeldStates {
}
impl HeldStates {
fn take(&mut self, ctx: &Context) -> Option<Held> {
self.get(ctx)?;
Some(self.entries.swap_remove(self.current.get()))
}
/// Service reads in the same context reuse its slot. A nested context or a swap on release
/// can change the slot, so verify its owner before reusing it.
fn get(&self, ctx: &Context) -> Option<&PassState> {
@@ -171,6 +176,49 @@ thread_local! {
static HELD: RefCell<HeldStates> = const { RefCell::new(HeldStates { entries: Vec::new(), current: Cell::new(0) }) };
}
scoped_tls::scoped_thread_local!(static RUNNING: Held);
/// Descendants use the binding of their outer component. A nested, different context
/// continues to find its own state among the thread's other held contexts.
pub(crate) fn in_component_tree() -> bool {
RUNNING.is_set()
}
fn bound(ctx: &Context) -> bool {
RUNNING.is_set() && RUNNING.with(|entry| entry.ctx == *ctx)
}
pub(crate) fn with_component_tree(ctx: &Context, run: impl FnOnce()) {
let entry = HELD.with(|held| held.try_borrow_mut().ok()?.take(ctx));
let Some(entry) = entry else { return run() };
// The binding unwinds before this guard, so a panic also returns the state to its owner.
struct Restore(Option<Held>);
impl Drop for Restore {
fn drop(&mut self) {
if let Some(entry) = self.0.take() {
if frame::running(&entry.ctx).is_some() {
keep(entry);
} else {
park(entry);
}
}
}
}
let restore = Restore(Some(entry));
if let Some(entry) = &restore.0 {
RUNNING.set(entry, run);
}
}
fn keep(entry: Held) {
HELD.with(|held| {
let mut held = held.borrow_mut();
held.current.set(held.entries.len());
held.entries.push(entry);
});
}
/// The state of a context between passes; `None` while a thread holds it.
struct Parked(Option<Box<PassState>>);
@@ -197,6 +245,17 @@ pub(crate) fn with<S: PassLocal, R>(ctx: &Context, f: impl FnOnce(&mut S) -> R)
/// The thread-local lookup and the parked-state slow path are shared by every service and caller.
fn visit(ctx: &Context, f: &mut dyn FnMut(&PassState)) {
if RUNNING.is_set()
&& RUNNING.with(|entry| {
if entry.ctx != *ctx {
return false;
}
f(&entry.state);
true
})
{
return;
}
let found = HELD.with(|held| {
let held = held.borrow();
let Some(state) = held.get(ctx) else { return false };
@@ -225,6 +284,9 @@ fn visit(ctx: &Context, f: &mut dyn FnMut(&PassState)) {
/// Moves the context's state into this thread unless it holds it already: the begin hook. States of other contexts
/// with no pass running here (a pass a panic left open) go back to their contexts first.
pub(crate) fn hold(ctx: &Context) {
if bound(ctx) {
return;
}
let stale: Vec<Held> =
HELD.with(|held| held.borrow_mut().entries.extract_if(.., |entry| entry.ctx != *ctx && frame::running(&entry.ctx).is_none()).collect());
for held in stale {
@@ -236,23 +298,15 @@ pub(crate) fn hold(ctx: &Context) {
let state = Service::<Parked>::run(ctx, |parked| parked.0.take());
debug_assert!(state.is_some(), "another thread holds this context's pass state");
let state = state.unwrap_or_default();
HELD.with(|held| {
let mut held = held.borrow_mut();
held.current.set(held.entries.len());
held.entries.push(Held { ctx: ctx.clone(), state });
});
keep(Held { ctx: ctx.clone(), state });
}
/// Moves the context's state back into its context data unless a pass of it still runs on this thread: the end hook.
pub(crate) fn release(ctx: &Context) {
if frame::running(ctx).is_some() {
if bound(ctx) || frame::running(ctx).is_some() {
return;
}
let held = HELD.with(|held| {
let mut held = held.borrow_mut();
held.entries.iter().position(|held| held.ctx == *ctx).map(|at| held.entries.swap_remove(at))
});
if let Some(held) = held {
if let Some(held) = HELD.with(|held| held.borrow_mut().take(ctx)) {
park(held);
}
}
@@ -260,3 +314,36 @@ pub(crate) fn release(ctx: &Context) {
fn park(held: Held) {
Service::<Parked>::run(&held.ctx, |parked| parked.0 = Some(held.state));
}
#[cfg(feature = "testing")]
mod binding_tests {
use super::{PassState, bound, hold, in_component_tree, visit, with_component_tree};
use crate::testing::trial;
use egui::Context;
fn address(ctx: &Context) -> *const PassState {
let mut address = std::ptr::null();
visit(ctx, &mut |state| address = std::ptr::from_ref(state));
address
}
#[trial]
fn component_tree_restores_its_state_after_nested_context_access_and_unwind() {
let outer = Context::default();
let inner = Context::default();
hold(&outer);
let original = address(&outer);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
with_component_tree(&outer, || {
assert!(bound(&outer));
assert!(!bound(&inner));
assert_ne!(address(&inner), original);
assert_eq!(address(&outer), original);
std::panic::resume_unwind(Box::new("component unwound"));
});
}));
assert!(unwound.is_err_and(|reason| reason.downcast_ref::<&str>() == Some(&"component unwound")));
assert!(!in_component_tree());
assert_eq!(address(&outer), original);
}
}