Skip to main content

bus_contract/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5mod tools;
6mod types;
7
8use std::any::{Any, TypeId, type_name};
9use std::rc::Rc;
10use std::sync::Arc;
11use std::time::Duration;
12
13pub use tools::{declare_all, missing_targets, order_dump};
14pub use types::*;
15
16/// A point as the erased methods of [`Bus`] name it: its id, its kind and
17/// its type, so an implementation refuses one id registered with two
18/// types.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20pub struct PointKey {
21    /// The point's id ([`Point::ID`]).
22    pub id: &'static str,
23    /// What it is for ([`Point::KIND`]).
24    pub kind: PointKind,
25    /// The point type's id.
26    pub type_id: TypeId,
27    /// The point type's name, for messages.
28    pub type_name: &'static str,
29}
30
31impl PointKey {
32    /// The key of the point `P`.
33    pub fn of<P: Point>() -> PointKey {
34        PointKey {
35            id: P::ID,
36            kind: P::KIND,
37            type_id: TypeId::of::<P>(),
38            type_name: type_name::<P>(),
39        }
40    }
41}
42
43/// An emit's input, its type erased: a point's [`Point::Input`].
44pub type AnyInput = Arc<dyn Any + Send + Sync>;
45
46/// A value going through an emit, its type erased: a point's
47/// [`Point::Value`].
48pub type AnyValue = Box<dyn Any + Send>;
49
50/// A listener, its types erased: it reads the input and edits the value
51/// in place.
52pub type AnyListener = Arc<
53    dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError> + Send + Sync,
54>;
55
56/// A local listener, its types erased: like [`AnyListener`], but neither
57/// `Send` nor `Sync`. It is bound to the thread that registered it
58/// ([`Bus::listen_local_any`]).
59pub type AnyLocalListener =
60    Rc<dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError>>;
61
62/// Called when local work is queued for a thread
63/// ([`Bus::add_pending_waker`]), with that thread's id, on the emitting
64/// thread.
65pub type PendingWaker = Arc<dyn Fn(std::thread::ThreadId) + Send + Sync>;
66
67/// Copies an erased value of a point's type (an alter keeps the value as
68/// it was when a listener fails).
69pub type CloneFn = fn(&(dyn Any + Send)) -> AnyValue;
70
71/// Makes a fresh erased value of a point's type (each listener's part in
72/// a collect).
73pub type FreshFn = fn() -> AnyValue;
74
75/// Receives each failure that dropped a contribution
76/// ([`Failure::dropped`]).
77pub type FailureSink = Arc<dyn Fn(&Failure) + Send + Sync>;
78
79/// The bus contract: hook points, their listeners in a declared order,
80/// emits and introspection. An application supplies one implementation
81/// (its own, or one written for it, such as `egui-pop-hooks`'s `Kernel`)
82/// and hands it to each
83/// library at construction; a library never constructs the bus it
84/// publishes on.
85///
86/// The methods are object safe and their values erased, so a library
87/// holds an `Arc<dyn Bus>`; the typed calls (`declare::<P>`,
88/// `listen::<P>`, `alter::<P>`, `collect::<P>`, `on_failure`) are methods
89/// of `dyn Bus`, written once here over these.
90///
91/// What an implementation promises:
92///
93/// - Listeners run ordered by `after` / `before` first (the target
94///   [`LAST`] places one after every other of its point, one per point),
95///   then by priority (higher first), then by registration. A cycle is
96///   refused at registration ([`Refused::Cycle`]); a target not there is
97///   reported ([`FailureKind::MissingTarget`]) and ignored.
98/// - A listener's edit counts only when it returns `Ok` within its
99///   deadline without panicking; otherwise it is dropped, the others
100///   still run, and the failure is returned and sent to the sinks.
101/// - The value an emit returns is of the point's type: the typed calls
102///   panic otherwise, as a defect of the implementation.
103/// - Listeners run with no lock held, so a listener may emit or listen.
104///
105/// Local listeners ([`Bus::listen_local_any`]) are for state that is not
106/// `Send` (`Rc`, `RefCell`), such as an interface's. Each is bound to the
107/// thread that registered it:
108///
109/// - It takes its place in the same order as the other listeners of its
110///   point (`after` / `before` / [`LAST`], priority, registration), keeps
111///   its owner and deadline, and shows in introspection
112///   ([`ListenerInfo::local`]).
113/// - An emit on its thread runs it in that order, inline, with the
114///   others.
115/// - An emit on another thread runs every other listener in order and
116///   queues the local ones for their thread; the result names them
117///   ([`Altered::deferred`], [`Collected::deferred`]) and the wakers
118///   ([`Bus::add_pending_waker`]) are called. The thread runs them when
119///   it calls [`Bus::run_pending`], in their order, emits in the order
120///   they were queued. A deferred alter's listeners edit a copy of the
121///   value the emit returned; a deferred collect's listeners each fill a
122///   fresh value. What they do is reported by [`Bus::run_pending`], not
123///   to the emitter.
124/// - A listener removed ([`Bus::unlisten`], [`Bus::forget`]), from any
125///   thread, does not run again, queued or not.
126pub trait Bus: Send + Sync {
127    /// Declares a point: its description and deadline. Listeners may
128    /// register before or after; declaring twice is refused.
129    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused>;
130
131    /// Registers a listener on a point under `id`. Refused, with nothing
132    /// changed, when the id is taken on the point, when its constraints
133    /// close a cycle, or when the point is registered with another type.
134    fn listen_any(
135        &self,
136        point: PointKey,
137        id: String,
138        opts: ListenOpts,
139        run: AnyListener,
140    ) -> Result<(), Refused>;
141
142    /// Registers a local listener on a point under `id`, bound to the
143    /// calling thread: it runs only on that thread. Refused as
144    /// [`Bus::listen_any`] is, and when `opts` asks for a thread of its
145    /// own ([`Refused::Threaded`]).
146    fn listen_local_any(
147        &self,
148        point: PointKey,
149        id: String,
150        opts: ListenOpts,
151        run: AnyLocalListener,
152    ) -> Result<(), Refused>;
153
154    /// Runs the local listeners queued for the calling thread by emits
155    /// on other threads, emit by emit in the order they were queued;
156    /// what each emit's deferred part did. Empty when nothing waits.
157    fn run_pending(&self) -> Vec<PendingRun>;
158
159    /// Adds a waker called when an emit queues local listeners for a
160    /// thread, with that thread's id: where the host asks that thread to
161    /// call [`Bus::run_pending`] (a repaint request, a message to its
162    /// loop). A waker that panics is ignored.
163    fn add_pending_waker(&self, wake: PendingWaker);
164
165    /// Removes the listener `id` of the point `point`; whether it was
166    /// there.
167    fn unlisten(&self, point: &str, id: &str) -> bool;
168
169    /// Removes every listener of `owner`, on every point; how many.
170    fn forget(&self, owner: &str) -> usize;
171
172    /// Passes `value` through the point's listeners in order, each
173    /// editing what the previous ones left; `clone` copies it so a
174    /// failing listener leaves it as it found it.
175    fn alter_any(
176        &self,
177        point: PointKey,
178        input: AnyInput,
179        value: AnyValue,
180        clone: CloneFn,
181    ) -> Altered<AnyValue>;
182
183    /// Gives each of the point's listeners, in order, a value from
184    /// `fresh` to fill, and gathers those that succeed.
185    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue>;
186
187    /// Adds a sink called with each failure that dropped a contribution,
188    /// as it happens.
189    fn add_failure_sink(&self, sink: FailureSink);
190
191    /// Every point, in id order, with its listeners in the order they
192    /// run.
193    fn points(&self) -> Vec<PointInfo>;
194
195    /// The listeners of the point `point`, in the order they run; `None`
196    /// for a point nobody declared or listened to.
197    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>>;
198}
199
200/// A shared bus is a bus: `&Arc<dyn Bus>` goes where `&dyn Bus` is
201/// asked, and an application may hand out `Arc<MyBus>` as it is.
202impl<B: Bus + ?Sized> Bus for Arc<B> {
203    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused> {
204        (**self).declare_point(point, spec)
205    }
206
207    fn listen_any(
208        &self,
209        point: PointKey,
210        id: String,
211        opts: ListenOpts,
212        run: AnyListener,
213    ) -> Result<(), Refused> {
214        (**self).listen_any(point, id, opts, run)
215    }
216
217    fn listen_local_any(
218        &self,
219        point: PointKey,
220        id: String,
221        opts: ListenOpts,
222        run: AnyLocalListener,
223    ) -> Result<(), Refused> {
224        (**self).listen_local_any(point, id, opts, run)
225    }
226
227    fn run_pending(&self) -> Vec<PendingRun> {
228        (**self).run_pending()
229    }
230
231    fn add_pending_waker(&self, wake: PendingWaker) {
232        (**self).add_pending_waker(wake);
233    }
234
235    fn unlisten(&self, point: &str, id: &str) -> bool {
236        (**self).unlisten(point, id)
237    }
238
239    fn forget(&self, owner: &str) -> usize {
240        (**self).forget(owner)
241    }
242
243    fn alter_any(
244        &self,
245        point: PointKey,
246        input: AnyInput,
247        value: AnyValue,
248        clone: CloneFn,
249    ) -> Altered<AnyValue> {
250        (**self).alter_any(point, input, value, clone)
251    }
252
253    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue> {
254        (**self).collect_any(point, input, fresh)
255    }
256
257    fn add_failure_sink(&self, sink: FailureSink) {
258        (**self).add_failure_sink(sink);
259    }
260
261    fn points(&self) -> Vec<PointInfo> {
262        (**self).points()
263    }
264
265    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>> {
266        (**self).listeners(point)
267    }
268}
269
270/// Copies an erased value of type `V`.
271fn clone_value<V: Clone + Send + 'static>(value: &(dyn Any + Send)) -> AnyValue {
272    match value.downcast_ref::<V>() {
273        Some(v) => Box::new(v.clone()),
274        None => panic!(
275            "a bus implementation passed a value that is not a `{}`",
276            type_name::<V>()
277        ),
278    }
279}
280
281/// A fresh erased value of type `V`.
282fn fresh_value<V: Default + Send + 'static>() -> AnyValue {
283    Box::new(V::default())
284}
285
286/// Takes the typed value back from what an implementation returned.
287fn typed<P: Point>(value: AnyValue) -> P::Value {
288    match value.downcast::<P::Value>() {
289        Ok(v) => *v,
290        Err(_) => panic!(
291            "the bus returned a value of another type than `{}`'s ({})",
292            P::ID,
293            type_name::<P::Value>()
294        ),
295    }
296}
297
298impl<'a> dyn Bus + 'a {
299    /// Declares the point `P`: its description and deadline. Listeners
300    /// may register before or after; declaring twice is refused.
301    pub fn declare<P: Point>(&self, spec: PointSpec) -> Result<(), Refused> {
302        self.declare_point(PointKey::of::<P>(), spec)
303    }
304
305    /// Registers a listener on `P` under `id`. It reads the emit's input
306    /// and edits the value; its edit counts only when it returns `Ok`
307    /// within its deadline without panicking.
308    ///
309    /// Refused, with nothing changed, when the id is taken on the point
310    /// or when its `after`/`before` close a cycle. A constraint naming a
311    /// listener not (yet) registered is accepted, reported by each emit
312    /// and by introspection, and ignored.
313    pub fn listen<P: Point>(
314        &self,
315        id: impl Into<String>,
316        opts: ListenOpts,
317        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
318    ) -> Result<(), Refused> {
319        self.listen_any(PointKey::of::<P>(), id.into(), opts, erase::<P>(run))
320    }
321
322    /// Registers a local listener on `P` under `id`, bound to the calling
323    /// thread: it may hold state that is not `Send` (`Rc<RefCell<…>>`).
324    /// It takes its place in the point's order with the other listeners;
325    /// an emit from another thread queues it for this thread's next
326    /// [`Bus::run_pending`]. See [`Bus`] for the guarantees.
327    pub fn listen_local<P: Point>(
328        &self,
329        id: impl Into<String>,
330        opts: ListenOpts,
331        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
332    ) -> Result<(), Refused> {
333        self.listen_local_any(PointKey::of::<P>(), id.into(), opts, erase_local::<P>(run))
334    }
335
336    /// Adds a waker called, with the thread's id, when an emit queues
337    /// local listeners for that thread. A waker that panics is ignored.
338    pub fn on_pending(&self, wake: impl Fn(std::thread::ThreadId) + Send + Sync + 'static) {
339        self.add_pending_waker(Arc::new(wake));
340    }
341
342    /// Passes `value` through `P`'s listeners in order: each edits the
343    /// value the previous ones left. A listener that fails leaves it as
344    /// it found it.
345    pub fn alter<P: Point>(&self, input: P::Input, value: P::Value) -> Altered<P::Value>
346    where
347        P::Value: Clone,
348    {
349        let out = self.alter_any(
350            PointKey::of::<P>(),
351            Arc::new(input),
352            Box::new(value),
353            clone_value::<P::Value>,
354        );
355        Altered {
356            value: typed::<P>(out.value),
357            failures: out.failures,
358            deferred: out.deferred,
359        }
360    }
361
362    /// Gives each of `P`'s listeners, in order, a fresh default value to
363    /// fill, and gathers the values of those that succeed.
364    pub fn collect<P: Point>(&self, input: P::Input) -> Collected<P::Value>
365    where
366        P::Value: Default,
367    {
368        let out = self.collect_any(
369            PointKey::of::<P>(),
370            Arc::new(input),
371            fresh_value::<P::Value>,
372        );
373        Collected {
374            parts: out
375                .parts
376                .into_iter()
377                .map(|(id, v)| (id, typed::<P>(v)))
378                .collect(),
379            failures: out.failures,
380            deferred: out.deferred,
381        }
382    }
383
384    /// Adds a sink called with each failure that dropped a contribution
385    /// ([`Failure::dropped`]), as it happens: where the host publishes
386    /// its [`FAILED_FACT`] fact or logs. A sink that panics is ignored.
387    pub fn on_failure(&self, sink: impl Fn(&Failure) + Send + Sync + 'static) {
388        self.add_failure_sink(Arc::new(sink));
389    }
390}
391
392/// Erases a typed listener of `P`.
393pub fn erase<P: Point>(
394    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
395) -> AnyListener {
396    Arc::new(move |input, value| {
397        let Some(input) = input.downcast_ref::<P::Input>() else {
398            return Err(HookError(format!(
399                "`{}`: the input is not a `{}`",
400                P::ID,
401                type_name::<P::Input>()
402            )));
403        };
404        let Some(value) = value.downcast_mut::<P::Value>() else {
405            return Err(HookError(format!(
406                "`{}`: the value is not a `{}`",
407                P::ID,
408                type_name::<P::Value>()
409            )));
410        };
411        run(input, value)
412    })
413}
414
415/// Erases a typed local listener of `P`.
416pub fn erase_local<P: Point>(
417    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
418) -> AnyLocalListener {
419    Rc::new(move |input, value| {
420        let Some(input) = input.downcast_ref::<P::Input>() else {
421            return Err(HookError(format!(
422                "`{}`: the input is not a `{}`",
423                P::ID,
424                type_name::<P::Input>()
425            )));
426        };
427        let Some(value) = value.downcast_mut::<P::Value>() else {
428            return Err(HookError(format!(
429                "`{}`: the value is not a `{}`",
430                P::ID,
431                type_name::<P::Value>()
432            )));
433        };
434        run(input, value)
435    })
436}
437
438/// One line of a library's contract table: a point it declares, built
439/// from the point's type in a `const` (`PointDecl::of::<DocClose>(…)`),
440/// so the application can read what a library will host before building
441/// anything. [`declare_all`] declares a table on a bus.
442#[derive(Clone, Copy, Debug)]
443pub struct PointDecl {
444    /// The point's id.
445    pub id: &'static str,
446    /// What it is for.
447    pub kind: PointKind,
448    /// What it does, for people and agents reading introspection.
449    pub description: &'static str,
450    /// The deadline of its listeners that set none; `None` takes the
451    /// bus's.
452    pub deadline: Option<Duration>,
453    key: fn() -> PointKey,
454}
455
456impl PointDecl {
457    /// The declaration of the point `P`, described by `description`.
458    pub const fn of<P: Point>(description: &'static str) -> PointDecl {
459        PointDecl {
460            id: P::ID,
461            kind: P::KIND,
462            description,
463            deadline: None,
464            key: PointKey::of::<P>,
465        }
466    }
467
468    /// The deadline of its listeners that set none.
469    pub const fn deadline(mut self, deadline: Duration) -> PointDecl {
470        self.deadline = Some(deadline);
471        self
472    }
473
474    /// The point's key.
475    pub fn key(&self) -> PointKey {
476        (self.key)()
477    }
478
479    /// The point's spec, as [`Bus::declare_point`] takes it.
480    pub fn spec(&self) -> PointSpec {
481        let spec = PointSpec::new(self.description);
482        match self.deadline {
483            Some(d) => spec.deadline(d),
484            None => spec,
485        }
486    }
487}