Skip to main content

egui_pop_api/bus/
settings.rs

1//! Settings changed, on the bus (ADR 0029).
2//!
3//! The value store is the one writer of a setting's value (ADR 0016):
4//! every change of a `settings/` path, made here (the Settings app, a
5//! bound widget, `value.set`, the application's code) or by another
6//! client of the host's store (applied by the Settings app's sync), is
7//! said **once** as `pop.settings.changed` ([`SettingsChanged`], a
8//! [`SettingChange`]: path, scope, by). Whoever follows a setting is one
9//! of its listeners and does its own part there; nobody compares a
10//! setting every pass.
11//!
12//! The store tells its listeners under its lock, where nothing may read
13//! it back, so the change is said right after the write, at the next of
14//! these points, all on the interface's thread: the start of the
15//! application's logic, after the requests it ran, after the Settings
16//! app's sync applied changes made elsewhere, and at the end of the main
17//! window's pass ([`AppHandle::deliver_settings`]). A change heard from
18//! another client is therefore followed in the pass it is heard.
19//!
20//! egui-pop's own listeners, local (they touch the interface's state):
21//! [`THEME_INSTALL`] (the accent, the text size and fonts, the scroll
22//! bars, the light or dark preference), [`POINTER_PROFILE`] (the
23//! pointer profile's bindings), [`FRAME_DECORATIONS`] (the main window's
24//! decorations for `window.frame`).
25
26use std::cell::RefCell;
27use std::sync::{Arc, Mutex};
28
29use bus_contract::{Point, PointId, PointKind};
30use egui_pop_core::lock;
31use egui_pop_model::values::Store;
32use serde::Serialize;
33
34use super::emit_with;
35use crate::app::AppHandle;
36
37/// A setting changed: its store path (`settings/<id>`), the value scope
38/// it changed in (`app`, a host's scope such as `library`, `run`), who
39/// wrote it (`user`, `agent:<session>`, `store` for another client of
40/// the host's store) and the value store's sequence number of the write.
41#[derive(Clone, Debug, PartialEq, Serialize)]
42#[non_exhaustive]
43pub struct SettingChange {
44    pub path: String,
45    pub scope: String,
46    pub by: String,
47    pub seq: u64,
48}
49
50impl SettingChange {
51    pub fn new(path: impl Into<String>, scope: impl Into<String>, by: impl Into<String>) -> Self {
52        Self {
53            path: path.into(),
54            scope: scope.into(),
55            by: by.into(),
56            seq: 0,
57        }
58    }
59
60    /// The setting's id: the path without `settings/`.
61    pub fn id(&self) -> &str {
62        self.path.strip_prefix(PREFIX).unwrap_or(&self.path)
63    }
64
65    /// Whether it is one of `ids`.
66    pub fn is_any(&self, ids: &[egui_pop_model::ids::SettingId]) -> bool {
67        ids.iter().any(|id| id.as_str() == self.id())
68    }
69}
70
71/// A setting changed (`pop.settings.changed`), said once per change of its
72/// value by the value store, its one writer.
73#[derive(Debug)]
74pub struct SettingsChanged;
75impl Point for SettingsChanged {
76    const KIND: PointKind = PointKind::Event;
77    const ID: PointId = PointId::new("pop.settings.changed");
78    type Input = SettingChange;
79    type Value = ();
80}
81
82/// The settings points, in the order [`super::order_dump`] prints them.
83pub const SETTINGS_POINTS: [&str; 1] = [SettingsChanged::ID.as_str()];
84
85/// egui-pop's listener installing the theme a setting changes.
86pub const THEME_INSTALL: &str = "pop.theme.install";
87/// egui-pop's listener loading the pointer profile the setting names.
88pub const POINTER_PROFILE: &str = "pop.pointer.profile";
89/// egui-pop's listener giving the main window the decorations
90/// `window.frame` asks for.
91pub const FRAME_DECORATIONS: &str = "pop.frame.decorations";
92
93/// Where settings live in the value store.
94const PREFIX: &str = "settings/";
95
96/// How many rounds a delivery runs: a listener writing a setting is
97/// followed in the same delivery, a loop is cut.
98const ROUNDS: usize = 16;
99
100thread_local! {
101    /// The scope and the writer the Settings app names while it writes
102    /// what a layer or another client changed.
103    static WRITING: RefCell<Vec<(String, Option<String>)>> = const { RefCell::new(Vec::new()) };
104}
105
106/// Names the scope (and the writer, when it is not the write's origin)
107/// of the writes made on this thread until dropped.
108pub(crate) fn writing(scope: &str, by: Option<&str>) -> Writing {
109    WRITING.with_borrow_mut(|w| w.push((scope.to_string(), by.map(str::to_string))));
110    Writing(std::marker::PhantomData)
111}
112
113/// Ends [`writing`].
114#[must_use]
115pub(crate) struct Writing(std::marker::PhantomData<*const ()>);
116
117impl Drop for Writing {
118    fn drop(&mut self) {
119        WRITING.with_borrow_mut(|w| w.pop());
120    }
121}
122
123/// The changes the value store told and not said yet.
124pub(crate) type Heard = Arc<Mutex<Vec<SettingChange>>>;
125
126/// Listens to the value store's `settings/` paths: each change is kept
127/// for [`AppHandle::deliver_settings`].
128pub(crate) fn hear(store: &mut Store, heard: &Heard) {
129    let heard = heard.clone();
130    store.listen(&egui_pop_model::ids::OwnerId::FRAMEWORK, PREFIX, move |c| {
131        let (scope, by) = WRITING
132            .with_borrow(|w| w.last().cloned())
133            .unwrap_or_else(|| ("app".to_string(), None));
134        lock(&heard).push(SettingChange {
135            path: c.path.clone(),
136            scope,
137            by: by.unwrap_or_else(|| c.origin.to_string()),
138            seq: c.seq,
139        });
140    });
141}
142
143impl AppHandle {
144    /// Says each setting changed since the last time as
145    /// `pop.settings.changed`, once, in the order the value store wrote them:
146    /// its listeners run now, on this thread. A listener writing a
147    /// setting is followed in the same call. Asked from inside a
148    /// delivery, it returns at once: the delivery running takes it.
149    ///
150    /// <div class="warning">Experimental: may change in any release
151    /// (docs/stability.md).</div>
152    pub fn deliver_settings(&self) {
153        let bus = &self.0.bus;
154        if bus.settings_delivering.replace(true) {
155            return;
156        }
157        let _delivering = super::Delivering(&bus.settings_delivering);
158        for _ in 0..ROUNDS {
159            let changes = std::mem::take(&mut *lock(&bus.settings_heard));
160            if changes.is_empty() {
161                return;
162            }
163            for change in changes {
164                emit_with::<SettingsChanged>(self, change, ());
165            }
166        }
167        log::warn!(target: "egui_pop", "settings.changed: listeners kept changing settings; the rest waits for the next pass");
168    }
169}