crabshell_ui/cx.rs
1//! [`Cx`], the context that widget code, event handlers and list views get.
2
3use std::any::{Any, TypeId};
4use std::cell::{OnceCell, RefCell};
5use std::collections::HashMap;
6use std::rc::{Rc, Weak};
7
8use crabshell_reactive::{Effect, Memo, Owner, ReadSignal, Signal, untrack};
9
10use crate::animation::{Activity, Busy};
11use crate::style::Font;
12use crate::text::{TextMetrics, TextSystem};
13use crate::tree::{NodeId, Tree};
14
15/// The context widget code runs in.
16///
17/// A `Cx` wraps the reactive [`Owner`] of one part of the shell: a window,
18/// a widget or one item of a keyed list. Signals, memos and effects created
19/// through it belong to that owner, so they are freed when that part of the
20/// shell goes away. Event handlers receive the `Cx` of their button, and
21/// [`children_keyed`](crate::Row::children_keyed) views receive the `Cx` of
22/// their item.
23///
24/// A context also carries the shell's services, keyed by type: the
25/// platform, and later the clock, Sway, audio and the tray. Every context
26/// made from it shares the same map, so a service provided once at the
27/// root reaches every widget and handler.
28#[derive(Clone)]
29pub struct Cx {
30 owner: Owner,
31 services: Rc<Services>,
32 /// The widget this context belongs to, if any, for
33 /// [`open_popup`](Self::open_popup). A child context shares it.
34 pub(crate) anchor: Option<Rc<Anchor>>,
35 /// Whether the keyed item this context is in, or one around it, is
36 /// leaving. A child context shares it; outside such an item it is the
37 /// root's signal that stays `false`.
38 leaving: ReadSignal<bool>,
39 /// The count of animations in the innermost item of a list with an
40 /// exit this context is in, which that item's exit waits for.
41 pub(crate) activity: Option<Rc<Activity>>,
42}
43
44/// Where a widget is: its window's tree and its node. Set once the node
45/// exists, which is after its context is made.
46#[derive(Default)]
47pub(crate) struct Anchor(OnceCell<(Weak<RefCell<Tree>>, NodeId)>);
48
49impl Anchor {
50 pub(crate) fn set(&self, tree: Weak<RefCell<Tree>>, node: NodeId) {
51 // A second set can't happen: each anchor is made for one node.
52 let _ = self.0.set((tree, node));
53 }
54
55 /// The tree, while the window is there, and the node.
56 pub(crate) fn get(&self) -> Option<(Rc<RefCell<Tree>>, NodeId)> {
57 let (tree, node) = self.0.get()?;
58 Some((tree.upgrade()?, *node))
59 }
60}
61
62/// The services of one shell, by type.
63#[derive(Default)]
64struct Services(RefCell<HashMap<TypeId, Rc<dyn Any>>>);
65
66impl std::fmt::Debug for Cx {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 let services = self.services.0.borrow().len();
69 f.debug_struct("Cx")
70 .field("owner", &self.owner)
71 .field("services", &services)
72 .finish()
73 }
74}
75
76impl Cx {
77 /// A context that creates everything under `owner`, with no services
78 /// yet.
79 pub fn new(owner: Owner) -> Cx {
80 Cx {
81 leaving: owner.signal(false).read_only(),
82 owner,
83 services: Rc::default(),
84 anchor: None,
85 activity: None,
86 }
87 }
88
89 /// The owner that signals, memos and effects created through this
90 /// context belong to.
91 pub fn owner(&self) -> Owner {
92 self.owner
93 }
94
95 /// A context for a part of the shell inside this one: what it creates
96 /// is freed when this context's owner is. The services are shared with
97 /// the child.
98 pub fn child(&self) -> Cx {
99 Cx {
100 owner: self.owner.child(),
101 services: Rc::clone(&self.services),
102 anchor: self.anchor.clone(),
103 leaving: self.leaving,
104 activity: self.activity.clone(),
105 }
106 }
107
108 /// Whether the keyed item this context is in is leaving: `true` from
109 /// when its key leaves a list with an [`exit`](crate::Row::exit) until
110 /// it is removed, or until the key comes back, and while an item of
111 /// such a list around it is leaving. Every context made inside the item
112 /// reads the same signal, and outside one it stays `false`.
113 pub fn leaving(&self) -> ReadSignal<bool> {
114 self.leaving
115 }
116
117 /// The context of an item of a list with an exit, which leaves when
118 /// `own` is true or the item around it leaves.
119 pub(crate) fn in_item(self, own: ReadSignal<bool>) -> Cx {
120 let outer = self.leaving;
121 // Only inside another such item can an outer one leave.
122 let leaving = match self.activity {
123 Some(_) => {
124 let either = move || own.try_get() == Some(true) || outer.try_get() == Some(true);
125 let both = self.signal(untrack(either));
126 self.effect(move || {
127 let now = either();
128 if untrack(|| both.try_get()) != Some(now) {
129 both.try_set(now);
130 }
131 });
132 both.read_only()
133 }
134 None => own,
135 };
136 Cx {
137 leaving,
138 activity: Some(Activity::new(self.activity.clone())),
139 ..self
140 }
141 }
142
143 /// Counts an animation starting in this context as running in the
144 /// items it is in, until the result is dropped.
145 pub(crate) fn busy(&self) -> Option<Busy> {
146 self.activity.as_ref().map(Busy::new)
147 }
148
149 /// Gives the context's owner a debug name, such as a widget path.
150 pub(crate) fn named(self, name: impl Into<String>) -> Cx {
151 Cx {
152 owner: self.owner.named(name),
153 ..self
154 }
155 }
156
157 /// The context of a widget's own node, at `anchor`.
158 pub(crate) fn at(self, anchor: Rc<Anchor>) -> Cx {
159 Cx {
160 anchor: Some(anchor),
161 ..self
162 }
163 }
164
165 /// Makes `service` reachable from every context of this shell, through
166 /// [`service`](Self::service), and returns it shared. A service of the
167 /// same type provided before is replaced; whoever holds it keeps it.
168 pub fn provide<T: 'static>(&self, service: T) -> Rc<T> {
169 let service = Rc::new(service);
170 let shared: Rc<dyn Any> = Rc::clone(&service) as Rc<dyn Any>;
171 let replaced = self
172 .services
173 .0
174 .borrow_mut()
175 .insert(TypeId::of::<T>(), shared);
176 // Dropped after the map is released: its `Drop` may use a context.
177 drop(replaced);
178 service
179 }
180
181 /// The service of type `T`, if one was provided.
182 pub fn service<T: 'static>(&self) -> Option<Rc<T>> {
183 let service = self.services.0.borrow().get(&TypeId::of::<T>()).cloned()?;
184 service.downcast::<T>().ok()
185 }
186
187 /// Creates a [`Signal`] holding `value`. See [`Owner::signal`].
188 #[track_caller]
189 pub fn signal<T: 'static>(&self, value: T) -> Signal<T> {
190 self.owner.signal(value)
191 }
192
193 /// Creates a [`Memo`] that derives its value with `f`. See
194 /// [`Owner::memo`].
195 #[track_caller]
196 pub fn memo<T: PartialEq + 'static>(&self, f: impl FnMut() -> T + 'static) -> Memo<T> {
197 self.owner.memo(f)
198 }
199
200 /// Creates an [`Effect`] that reruns `f` when something it read changes.
201 /// See [`Owner::effect`].
202 #[track_caller]
203 pub fn effect(&self, f: impl FnMut() + 'static) -> Effect {
204 self.owner.effect(f)
205 }
206
207 /// Measures `text` as a [`Text`](crate::Text) with `font` lays it out,
208 /// with the same fonts and fallbacks. Each line break starts another
209 /// line: the width is the widest line's and the height a line height per
210 /// line. It isn't reactive itself; a binding that calls it runs again
211 /// when the signals it read change.
212 pub fn measure_text(&self, text: &str, font: Font) -> TextMetrics {
213 self.text_system().fonts().measure(text, font)
214 }
215
216 /// Adds the fonts in `bytes`, such as `include_bytes!("fonts/Inter.ttf")`,
217 /// without copying them. A family they provide is used before any
218 /// installed font of that name, and text already laid out shapes again.
219 /// Bytes that hold no font are logged and ignored.
220 pub fn add_font(&self, bytes: &'static [u8]) {
221 self.text_system().fonts().add(bytes);
222 }
223
224 /// The shell's text system, which the platform provides; one is made if
225 /// it didn't.
226 fn text_system(&self) -> Rc<TextSystem> {
227 self
228 .service()
229 .unwrap_or_else(|| self.provide(TextSystem::new()))
230 }
231}