Skip to main content

corundum_framework_gui/settings/
mod.rs

1//! The settings screen, and the pieces its pages are made of.
2//!
3//! [`Settings`] is the screen: the pages an app and the frameworks under it put in, by
4//! group, in a list beside the open page — or, narrower than
5//! [`COMPACT_WIDTH`](crate::COMPACT_WIDTH), the list, then one page under a way back to
6//! it. A host whose pages share state, or come and go (pages made from a schema, say),
7//! gives the list itself each frame to a [`SettingsLayout`] instead.
8//!
9//! [`scope_tabs`] is the row of tabs a page shows when a setting can be kept in more than
10//! one place — on this device or for the whole workgroup, on the client or on the server.
11//! [`AppearancePage`] is the theme and the language over those tabs. [`RailPage`] is the
12//! order of the shell's rail, and which items it shows. [`LauncherRow`] is a row for an app's
13//! own page: whether the app is in the OS's app menu, and the button that changes it.
14//!
15//! Nothing here stores a setting or checks one: the pages show the host's values and give
16//! back what the person changed, and the host keeps them as it keeps the rest of its
17//! settings. [`RailPage`] alone hands its change to the shell at once, and [`LauncherRow`]
18//! changes the app menu at once, keeping the choice in corundum's [store](crate::store).
19
20mod appearance;
21mod launcher;
22mod layout;
23mod rail;
24mod scope;
25
26pub use appearance::{AppearanceChange, AppearanceCtx, AppearancePage, AppearanceScope};
27pub use launcher::LauncherRow;
28pub use layout::{ListItem, SettingsLayout};
29pub use rail::RailPage;
30pub use scope::{ScopeTab, scope_tabs};
31
32/// A page of [`Settings`].
33pub trait SettingsSection {
34    /// The page's name in the list, in the language installed in `ctx`. It is asked every
35    /// frame, so a language switch reaches the list at once.
36    fn label(&self, ctx: &egui::Context) -> String;
37
38    /// Render the page, its own heading first.
39    fn ui(&mut self, ui: &mut egui::Ui);
40
41    /// Whether the page holds changes not saved yet; its entry is marked.
42    fn dirty(&self) -> bool {
43        false
44    }
45}
46
47/// How a group's heading is named.
48enum Heading {
49    /// No heading: the group is set apart by a gap.
50    None,
51    /// A message id, looked up in the installed language.
52    Message(&'static str),
53    /// Text as it is: the app's name, say.
54    Text(String),
55}
56
57/// Pages under one heading in [`Settings`]: the app's own, a framework's, About.
58pub struct SettingsGroup {
59    heading: Heading,
60    sections: Vec<Box<dyn SettingsSection>>,
61}
62
63impl SettingsGroup {
64    /// `sections` with no heading, set apart from the group before by a gap: About, say.
65    pub fn new(sections: Vec<Box<dyn SettingsSection>>) -> SettingsGroup {
66        SettingsGroup {
67            heading: Heading::None,
68            sections,
69        }
70    }
71
72    /// Head the group with the message `id`, in the installed language.
73    pub fn titled(mut self, id: &'static str) -> SettingsGroup {
74        self.heading = Heading::Message(id);
75        self
76    }
77
78    /// Head the group with `name` as it is: the app's name, say.
79    pub fn named(mut self, name: impl Into<String>) -> SettingsGroup {
80        self.heading = Heading::Text(name.into());
81        self
82    }
83}
84
85/// The settings screen: groups of pages, in a list beside the open page. Hold one; call
86/// [`ui`](Self::ui) every frame it is shown, as the root of what the shell leaves.
87///
88/// ```no_run
89/// # use corundum_framework_gui::settings::{Settings, SettingsGroup, SettingsSection};
90/// # fn example(general: Box<dyn SettingsSection>, about: Box<dyn SettingsSection>, ui: &mut egui::Ui) {
91/// let mut settings = Settings::new()
92///     .with_group(SettingsGroup::new(vec![general]).named("Journal"))
93///     .with_group(SettingsGroup::new(vec![about]));
94/// settings.ui(ui);
95/// # }
96/// ```
97#[derive(Default)]
98pub struct Settings {
99    groups: Vec<SettingsGroup>,
100    /// The open page, by group and by section.
101    layout: SettingsLayout<(usize, usize)>,
102}
103
104impl Settings {
105    /// Settings with no pages yet.
106    pub fn new() -> Settings {
107        Settings::default()
108    }
109
110    /// Add `group`, after the groups already there.
111    pub fn with_group(mut self, group: SettingsGroup) -> Settings {
112        self.groups.push(group);
113        self
114    }
115
116    /// Add `group`, after the groups already there: a framework's pages, put in by the
117    /// framework once the app has added its own.
118    pub fn push_group(&mut self, group: SettingsGroup) {
119        self.groups.push(group);
120    }
121
122    /// Open the `section`th page of the `group`th group.
123    pub fn open(&mut self, group: usize, section: usize) {
124        self.layout.open(Some((group, section)));
125    }
126
127    /// The open page, by group and by section.
128    pub fn current(&self) -> Option<(usize, usize)> {
129        self.layout.current().copied()
130    }
131
132    /// Render into `ui`, as the root of what the shell leaves of it.
133    pub fn ui(&mut self, ui: &mut egui::Ui) {
134        let items = self.items(ui.ctx());
135        let Settings { groups, layout } = self;
136        layout.ui(ui, &items, |ui, (g, s)| {
137            if let Some(section) = groups.get_mut(g).and_then(|g| g.sections.get_mut(s)) {
138                section.ui(ui);
139            }
140        });
141    }
142
143    /// The list, in the language installed in `ctx`.
144    fn items(&self, ctx: &egui::Context) -> Vec<ListItem<(usize, usize)>> {
145        let mut out = Vec::new();
146        for (g, group) in self.groups.iter().enumerate() {
147            match &group.heading {
148                Heading::None if g > 0 => out.push(ListItem::Gap),
149                Heading::None => {}
150                Heading::Message(id) => out.push(ListItem::Heading(crate::i18n::tr(ctx, id))),
151                Heading::Text(text) => out.push(ListItem::Heading(text.clone())),
152            }
153            for (s, section) in group.sections.iter().enumerate() {
154                out.push(ListItem::Entry {
155                    page: (g, s),
156                    label: section.label(ctx),
157                    dirty: section.dirty(),
158                });
159            }
160        }
161        out
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use crate::test_support::render;
169
170    struct Named(&'static str, bool);
171
172    impl SettingsSection for Named {
173        fn label(&self, _ctx: &egui::Context) -> String {
174            self.0.to_owned()
175        }
176
177        fn ui(&mut self, ui: &mut egui::Ui) {
178            ui.label(self.0);
179        }
180
181        fn dirty(&self) -> bool {
182            self.1
183        }
184    }
185
186    fn settings() -> Settings {
187        Settings::new()
188            .with_group(
189                SettingsGroup::new(vec![
190                    Box::new(Named("Look", false)),
191                    Box::new(Named("Sync", true)),
192                ])
193                .named("Example"),
194            )
195            .with_group(
196                SettingsGroup::new(vec![Box::new(Named("Appearance", false))])
197                    .titled("corundum-settings"),
198            )
199            .with_group(SettingsGroup::new(vec![Box::new(Named("About", false))]))
200    }
201
202    fn labels(settings: &Settings) -> Vec<String> {
203        let ctx = egui::Context::default();
204        crate::i18n::install(
205            &ctx,
206            &crate::i18n::LanguageSettings {
207                language: crate::i18n::Language::Explicit("en".into()),
208            },
209        );
210        settings
211            .items(&ctx)
212            .into_iter()
213            .map(|item| match item {
214                ListItem::Heading(h) => format!("# {h}"),
215                ListItem::Entry { label, dirty, .. } => layout::marked(&label, dirty),
216                ListItem::Gap => "-".into(),
217            })
218            .collect()
219    }
220
221    #[test]
222    fn groups_are_listed_in_order() {
223        let mut settings = settings();
224        settings
225            .push_group(SettingsGroup::new(vec![Box::new(Named("Later", false))]).named("Late"));
226        let labels = labels(&settings);
227        assert_eq!(
228            labels,
229            [
230                "# Example",
231                "Look",
232                "Sync •",
233                "# Settings",
234                "Appearance",
235                "-",
236                "About",
237                "# Late",
238                "Later",
239            ]
240        );
241    }
242
243    #[test]
244    fn wide_it_opens_the_first_page() {
245        let mut settings = settings();
246        render([900.0, 600.0], |ui| settings.ui(ui));
247        assert_eq!(settings.current(), Some((0, 0)));
248    }
249
250    #[test]
251    fn compact_it_shows_the_list_then_the_page_opened() {
252        let mut settings = settings();
253        render([400.0, 700.0], |ui| settings.ui(ui));
254        assert_eq!(settings.current(), None);
255        settings.open(2, 0);
256        render([400.0, 700.0], |ui| settings.ui(ui));
257        assert_eq!(settings.current(), Some((2, 0)));
258    }
259}