1use std::cell::{Cell, RefCell};
35use std::collections::HashMap;
36use std::rc::Rc;
37
38use day_core::{AnyPiece, Piece};
39use day_pieces::prelude::*;
40use day_pieces::{Label, TextSource};
41use day_reactive::{Signal, watch};
42use day_spec::{Cap, Support};
43
44day_pieces::glue_modules!(appkit, gtk, qt, uikit, material, arkui);
45
46#[cfg(all(feature = "xaml", target_os = "windows"))]
47#[path = "lib-xaml.rs"]
48mod xaml_impl;
49
50pub type LocaleTable = &'static [(&'static str, &'static str)];
52
53pub mod prelude {
56 pub use crate::{
57 APPEARANCE, About, Appearance, Group, LANGUAGE, Pref, PrefValue, Preferences, Prefs,
58 Presentation, Providers, Row, Section, appearance_row, general_group, language_row,
59 pref_enum, rows,
60 };
61}
62
63pub use day_part_preferences::{
68 MemoryStore, NativeStore, Pref, PrefValue, Store, install_store, persistence_failures,
69 pref_enum,
70};
71
72day_core::tls_group! {
73 static INSTALLED: RefCell<Option<Rc<Installed>>> = const { RefCell::new(None) };
75 static RUNTIME_PROVIDERS: RefCell<Vec<&'static Provider>> = const { RefCell::new(Vec::new()) };
78 static GENERAL_WIRED: Cell<bool> = const { Cell::new(false) };
80 static SYSTEM_LOCALE: std::cell::OnceCell<String> = const { std::cell::OnceCell::new() };
83 static SUBPAGES: RefCell<HashMap<String, Build>> = RefCell::new(HashMap::new());
85}
86
87#[derive(Clone, Debug, PartialEq)]
93pub enum GroupIcon {
94 Image(day_spec::ImageName),
95 Symbol(day_spec::Symbol),
96}
97
98impl From<day_spec::Symbol> for GroupIcon {
99 fn from(s: day_spec::Symbol) -> Self {
100 GroupIcon::Symbol(s)
101 }
102}
103impl From<day_spec::ImageName> for GroupIcon {
104 fn from(n: day_spec::ImageName) -> Self {
105 GroupIcon::Image(n)
106 }
107}
108impl From<day_spec::VectorName> for GroupIcon {
109 fn from(n: day_spec::VectorName) -> Self {
110 GroupIcon::Image(n.into())
111 }
112}
113
114type Build = Rc<dyn Fn() -> AnyPiece>;
115type Avail = Rc<dyn Fn() -> bool>;
116
117#[derive(Clone)]
120#[must_use]
121pub struct Group {
122 id: &'static str,
123 title: TextSource,
124 subtitle: Option<TextSource>,
125 icon: Option<GroupIcon>,
126 sections: Vec<Section>,
127 custom: Option<Build>,
128 order: i32,
129 available: Option<Avail>,
130}
131
132impl Group {
133 pub fn new<M>(id: &'static str, title: impl IntoText<M>) -> Self {
135 Group {
136 id,
137 title: title.into_text(),
138 subtitle: None,
139 icon: None,
140 sections: Vec::new(),
141 custom: None,
142 order: 0,
143 available: None,
144 }
145 }
146 pub fn icon(mut self, icon: impl Into<GroupIcon>) -> Self {
149 self.icon = Some(icon.into());
150 self
151 }
152 pub fn subtitle<M>(mut self, t: impl IntoText<M>) -> Self {
154 self.subtitle = Some(t.into_text());
155 self
156 }
157 pub fn section(mut self, section: Section) -> Self {
159 self.sections.push(section);
160 self
161 }
162 pub fn row(mut self, row: Row) -> Self {
164 match self.sections.last_mut() {
165 Some(s) if s.title.is_none() && s.footer.is_none() => s.rows.push(row),
166 _ => self.sections.push(Section::new().row(row)),
167 }
168 self
169 }
170 pub fn custom<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
173 self.custom = Some(Rc::new(move || AnyPiece::new(build())));
174 self
175 }
176 pub fn order(mut self, order: i32) -> Self {
179 self.order = order;
180 self
181 }
182 pub fn available(mut self, f: impl Fn() -> bool + 'static) -> Self {
184 self.available = Some(Rc::new(f));
185 self
186 }
187 pub fn requires(self, cap: Cap) -> Self {
189 self.available(move || day_core::capability(cap) != Support::Unsupported)
190 }
191 #[must_use]
193 pub fn id(&self) -> &'static str {
194 self.id
195 }
196 fn is_available(&self) -> bool {
197 self.available.as_ref().is_none_or(|f| f())
198 }
199}
200
201#[derive(Clone, Default)]
203#[must_use]
204pub struct Section {
205 title: Option<TextSource>,
206 footer: Option<TextSource>,
207 rows: Vec<Row>,
208}
209
210impl Section {
211 pub fn new() -> Self {
212 Section::default()
213 }
214 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
216 self.title = Some(t.into_text());
217 self
218 }
219 pub fn footer<M>(mut self, t: impl IntoText<M>) -> Self {
221 self.footer = Some(t.into_text());
222 self
223 }
224 pub fn row(mut self, row: Row) -> Self {
225 self.rows.push(row);
226 self
227 }
228 pub fn rows(mut self, rows: impl IntoIterator<Item = Row>) -> Self {
229 self.rows.extend(rows);
230 self
231 }
232}
233
234#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
236pub enum ChoiceStyle {
237 #[default]
239 Menu,
240 Segmented,
242}
243
244#[derive(Clone)]
245enum RowKind {
246 Toggle(Signal<bool>),
247 Choice {
248 labels: Vec<TextSource>,
249 index: Signal<usize>,
250 style: ChoiceStyle,
251 },
252 Slider {
253 value: Signal<f64>,
254 range: std::ops::RangeInclusive<f64>,
255 step: Option<f64>,
256 value_text: Option<Rc<dyn Fn(f64) -> String>>,
257 },
258 Stepper {
259 value: Signal<f64>,
260 range: std::ops::RangeInclusive<f64>,
261 step: f64,
262 },
263 Text {
264 value: Signal<String>,
265 placeholder: Option<TextSource>,
266 secure: bool,
267 },
268 Action {
269 on: Rc<dyn Fn()>,
270 destructive: bool,
271 confirm: Option<TextSource>,
272 confirm_label: Option<TextSource>,
273 busy: Option<Reactive<bool>>,
274 },
275 Link(String),
276 Navigate(Build),
277 Info {
278 value: TextSource,
279 copyable: bool,
280 },
281 Note,
282 Custom(Build),
283}
284
285#[derive(Clone)]
287#[must_use]
288pub struct Row {
289 title: TextSource,
290 caption: Option<TextSource>,
291 id: Option<day_core::ElementId>,
292 enabled: Option<Reactive<bool>>,
293 available: Option<Avail>,
294 kind: RowKind,
295}
296
297impl Row {
298 fn new<M>(title: impl IntoText<M>, kind: RowKind) -> Self {
299 Row {
300 title: title.into_text(),
301 caption: None,
302 id: None,
303 enabled: None,
304 available: None,
305 kind,
306 }
307 }
308 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
310 self.title = t.into_text();
311 self
312 }
313 pub fn caption<M>(mut self, t: impl IntoText<M>) -> Self {
315 self.caption = Some(t.into_text());
316 self
317 }
318 pub fn id(mut self, id: day_core::ElementId) -> Self {
320 self.id = Some(id);
321 self
322 }
323 pub fn enabled<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
326 self.enabled = Some(enabled.into_reactive());
327 self
328 }
329 pub fn available(mut self, f: impl Fn() -> bool + 'static) -> Self {
331 self.available = Some(Rc::new(f));
332 self
333 }
334 pub fn requires(self, cap: Cap) -> Self {
336 self.available(move || day_core::capability(cap) != Support::Unsupported)
337 }
338 fn is_available(&self) -> bool {
339 self.available.as_ref().is_none_or(|f| f())
340 }
341}
342
343pub mod rows {
346 use super::*;
347
348 fn pref_id<T: PrefValue>(p: &Pref<T>) -> day_core::ElementId {
349 day_core::id!(pref, p.key())
350 }
351
352 pub fn toggle<M>(pref: &'static Pref<bool>, title: impl IntoText<M>) -> Row {
354 Row::new(title, RowKind::Toggle(pref.signal())).id(pref_id(pref))
355 }
356
357 pub fn choice<T: PrefValue, M, L, LM>(
360 pref: &'static Pref<T>,
361 title: impl IntoText<M>,
362 options: impl IntoIterator<Item = (T, L)>,
363 ) -> Row
364 where
365 L: IntoText<LM>,
366 {
367 let (values, labels): (Vec<T>, Vec<TextSource>) =
368 options.into_iter().map(|(v, l)| (v, l.into_text())).unzip();
369 let sig = pref.signal();
370 let current = sig.get_untracked();
371 let index = Signal::global(values.iter().position(|v| *v == current).unwrap_or(0));
372 {
375 let values = values.clone();
376 watch(
377 move || index.get(),
378 move |ix, _| {
379 if let Some(v) = values.get(*ix) {
380 pref.set(v.clone());
381 }
382 },
383 );
384 }
385 watch(
386 move || sig.get(),
387 move |v, _| {
388 if let Some(ix) = values.iter().position(|x| x == v) {
389 index.set_if_changed(ix);
390 }
391 },
392 );
393 Row::new(
394 title,
395 RowKind::Choice {
396 labels,
397 index,
398 style: ChoiceStyle::Menu,
399 },
400 )
401 .id(pref_id(pref))
402 }
403
404 impl Row {
405 pub fn segmented(mut self) -> Self {
407 if let RowKind::Choice { style, .. } = &mut self.kind {
408 *style = ChoiceStyle::Segmented;
409 }
410 self
411 }
412 pub fn step(mut self, s: f64) -> Self {
414 match &mut self.kind {
415 RowKind::Slider { step, .. } => *step = Some(s),
416 RowKind::Stepper { step, .. } => *step = s,
417 _ => {}
418 }
419 self
420 }
421 pub fn value_text(mut self, f: impl Fn(f64) -> String + 'static) -> Self {
423 if let RowKind::Slider { value_text, .. } = &mut self.kind {
424 *value_text = Some(Rc::new(f));
425 }
426 self
427 }
428 pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
430 if let RowKind::Text { placeholder, .. } = &mut self.kind {
431 *placeholder = Some(t.into_text());
432 }
433 self
434 }
435 pub fn secure(mut self) -> Self {
437 if let RowKind::Text { secure, .. } = &mut self.kind {
438 *secure = true;
439 }
440 self
441 }
442 pub fn destructive(mut self) -> Self {
444 if let RowKind::Action { destructive, .. } = &mut self.kind {
445 *destructive = true;
446 }
447 self
448 }
449 pub fn confirm<M>(mut self, message: impl IntoText<M>) -> Self {
452 if let RowKind::Action { confirm, .. } = &mut self.kind {
453 *confirm = Some(message.into_text());
454 }
455 self
456 }
457 pub fn confirm_label<M>(mut self, label: impl IntoText<M>) -> Self {
459 if let RowKind::Action { confirm_label, .. } = &mut self.kind {
460 *confirm_label = Some(label.into_text());
461 }
462 self
463 }
464 pub fn busy<M>(mut self, busy: impl IntoReactive<bool, M>) -> Self {
467 if let RowKind::Action { busy: b, .. } = &mut self.kind {
468 *b = Some(busy.into_reactive());
469 }
470 self
471 }
472 pub fn copyable(mut self) -> Self {
474 if let RowKind::Info { copyable, .. } = &mut self.kind {
475 *copyable = true;
476 }
477 self
478 }
479 }
480
481 pub fn slider<M>(
483 pref: &'static Pref<f64>,
484 title: impl IntoText<M>,
485 range: std::ops::RangeInclusive<f64>,
486 ) -> Row {
487 let sig = pref.signal();
488 Row::new(
489 title,
490 RowKind::Slider {
491 value: sig,
492 range,
493 step: None,
494 value_text: None,
495 },
496 )
497 .id(pref_id(pref))
498 }
499
500 pub fn stepper<M>(
502 pref: &'static Pref<i64>,
503 title: impl IntoText<M>,
504 range: std::ops::RangeInclusive<i64>,
505 ) -> Row {
506 let sig = pref.signal();
507 let value = Signal::global(sig.get_untracked() as f64);
508 watch(move || value.get(), move |v, _| pref.set(v.round() as i64));
509 watch(
510 move || sig.get(),
511 move |v, _| value.set_if_changed(*v as f64),
512 );
513 Row::new(
514 title,
515 RowKind::Stepper {
516 value,
517 range: (*range.start() as f64)..=(*range.end() as f64),
518 step: 1.0,
519 },
520 )
521 .id(pref_id(pref))
522 }
523
524 pub fn text<M>(pref: &'static Pref<String>, title: impl IntoText<M>) -> Row {
526 let sig = pref.signal();
527 Row::new(
528 title,
529 RowKind::Text {
530 value: sig,
531 placeholder: None,
532 secure: false,
533 },
534 )
535 .id(pref_id(pref))
536 }
537
538 pub fn action<M>(title: impl IntoText<M>, on: impl Fn() + 'static) -> Row {
541 Row::new(
542 title,
543 RowKind::Action {
544 on: Rc::new(on),
545 destructive: false,
546 confirm: None,
547 confirm_label: None,
548 busy: None,
549 },
550 )
551 }
552
553 pub fn link<M>(title: impl IntoText<M>, url: impl Into<String>) -> Row {
555 Row::new(title, RowKind::Link(url.into()))
556 }
557
558 pub fn navigate<M, P: Piece>(title: impl IntoText<M>, build: impl Fn() -> P + 'static) -> Row {
560 Row::new(
561 title,
562 RowKind::Navigate(Rc::new(move || AnyPiece::new(build()))),
563 )
564 }
565
566 pub fn info<M, VM>(title: impl IntoText<M>, value: impl IntoText<VM>) -> Row {
568 Row::new(
569 title,
570 RowKind::Info {
571 value: value.into_text(),
572 copyable: false,
573 },
574 )
575 }
576
577 pub fn note<M>(text: impl IntoText<M>) -> Row {
579 Row::new(text, RowKind::Note)
580 }
581
582 pub fn custom<P: Piece>(build: impl Fn() -> P + 'static) -> Row {
584 Row::new("", RowKind::Custom(Rc::new(move || AnyPiece::new(build()))))
585 }
586}
587
588#[derive(Clone, Default)]
595#[must_use]
596pub struct About {
597 name: Option<TextSource>,
598 version: Option<String>,
599 build: Option<String>,
600 tagline: Option<TextSource>,
601 copyright: Option<TextSource>,
602 icon: Option<day_spec::ImageName>,
603 links: Vec<(TextSource, String)>,
604 privacy: Option<String>,
605 credits: Option<TextSource>,
606 licenses: Option<TextSource>,
607 custom: Option<Build>,
608}
609
610impl About {
611 pub fn from_manifest() -> Self {
615 About {
616 version: option_env!("DAY_SETTINGS_APP_VERSION").map(str::to_owned),
617 build: option_env!("DAY_SETTINGS_APP_BUILD").map(str::to_owned),
618 ..Default::default()
619 }
620 }
621 pub fn name<M>(mut self, t: impl IntoText<M>) -> Self {
623 self.name = Some(t.into_text());
624 self
625 }
626 pub fn version(mut self, v: impl Into<String>) -> Self {
627 self.version = Some(v.into());
628 self
629 }
630 pub fn build(mut self, b: impl Into<String>) -> Self {
631 self.build = Some(b.into());
632 self
633 }
634 pub fn tagline<M>(mut self, t: impl IntoText<M>) -> Self {
636 self.tagline = Some(t.into_text());
637 self
638 }
639 pub fn copyright<M>(mut self, t: impl IntoText<M>) -> Self {
640 self.copyright = Some(t.into_text());
641 self
642 }
643 pub fn icon(mut self, icon: impl Into<day_spec::ImageName>) -> Self {
645 self.icon = Some(icon.into());
646 self
647 }
648 pub fn link<M>(mut self, title: impl IntoText<M>, url: impl Into<String>) -> Self {
651 self.links.push((title.into_text(), url.into()));
652 self
653 }
654 pub fn website(self, url: impl Into<String>) -> Self {
656 self.link(day_localization_ui::res::str::day_about_website(), url)
657 }
658 pub fn source(self, url: impl Into<String>) -> Self {
660 self.link(day_localization_ui::res::str::day_about_source(), url)
661 }
662 pub fn privacy(mut self, url: impl Into<String>) -> Self {
664 self.privacy = Some(url.into());
665 self
666 }
667 pub fn credits<M>(mut self, t: impl IntoText<M>) -> Self {
669 self.credits = Some(t.into_text());
670 self
671 }
672 pub fn licenses<M>(mut self, t: impl IntoText<M>) -> Self {
674 self.licenses = Some(t.into_text());
675 self
676 }
677 pub fn custom<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
679 self.custom = Some(Rc::new(move || AnyPiece::new(build())));
680 self
681 }
682
683 pub fn display_name(&self) -> String {
685 match &self.name {
686 Some(n) => n.initial(),
687 None => option_env!("DAY_SETTINGS_APP_TITLE")
688 .map(str::to_owned)
689 .or_else(|| day_core::launch_options().map(|o| o.app_name.unwrap_or(o.title)))
690 .unwrap_or_default(),
691 }
692 }
693 #[must_use]
695 pub fn version_line(&self) -> Option<String> {
696 use std::fmt::Write as _;
697 let version = self
698 .version
699 .clone()
700 .or_else(|| day_core::launch_options().and_then(|o| o.version.clone()))?;
701 let mut line = day_localization_ui::res::str::day_about_version(version).format();
702 if let Some(build) = &self.build
703 && !build.is_empty()
704 {
705 let _ = write!(line, " ({build})");
706 }
707 Some(line)
708 }
709 #[must_use]
710 pub fn version_value(&self) -> Option<&str> {
711 self.version.as_deref()
712 }
713 #[must_use]
714 pub fn build_value(&self) -> Option<&str> {
715 self.build.as_deref()
716 }
717 #[must_use]
718 pub fn links(&self) -> &[(TextSource, String)] {
719 &self.links
720 }
721 #[must_use]
722 pub fn privacy_url(&self) -> Option<&str> {
723 self.privacy.as_deref()
724 }
725 #[must_use]
726 pub fn icon_name(&self) -> Option<&day_spec::ImageName> {
727 self.icon.as_ref()
728 }
729 pub fn tagline_text(&self) -> Option<String> {
730 self.tagline.as_ref().map(TextSource::initial)
731 }
732 pub fn copyright_text(&self) -> Option<String> {
733 self.copyright.as_ref().map(TextSource::initial)
734 }
735 pub fn credits_text(&self) -> Option<String> {
736 self.credits.as_ref().map(TextSource::initial)
737 }
738 pub fn licenses_text(&self) -> Option<String> {
739 self.licenses.as_ref().map(TextSource::initial)
740 }
741 #[must_use]
742 pub fn custom_piece(&self) -> Option<AnyPiece> {
743 self.custom.as_ref().map(|b| b())
744 }
745}
746
747pub struct Provider {
756 pub id: &'static str,
758 pub order: i32,
760 pub available: fn() -> bool,
762 pub group: fn() -> Group,
764 pub startup: Option<fn()>,
767}
768
769#[cfg(not(target_arch = "wasm32"))]
771#[linkme::distributed_slice]
772pub static PROVIDERS: [&'static Provider];
773
774#[macro_export]
783macro_rules! provider {
784 ($(#[$meta:meta])* $vis:vis static $name:ident : Provider = $init:expr ;) => {
785 $(#[$meta])*
786 $vis static $name: $crate::Provider = $init;
787 #[cfg(not(target_arch = "wasm32"))]
789 #[$crate::linkme::distributed_slice($crate::PROVIDERS)]
790 #[linkme(crate = $crate::linkme)]
791 static __DAY_SETTINGS_PROVIDER: &'static $crate::Provider = &$name;
792 };
793}
794
795#[doc(hidden)]
796pub use linkme;
797
798pub fn register_provider(p: &'static Provider) {
801 RUNTIME_PROVIDERS.with(|r| {
802 let mut r = r.borrow_mut();
803 if !r.iter().any(|q| std::ptr::eq(*q, p)) {
804 r.push(p);
805 }
806 });
807}
808
809fn all_providers() -> Vec<&'static Provider> {
810 let mut out: Vec<&'static Provider> = Vec::new();
811 #[cfg(not(target_arch = "wasm32"))]
812 out.extend(PROVIDERS.iter().copied());
813 RUNTIME_PROVIDERS.with(|r| {
814 for p in r.borrow().iter() {
815 if !out.iter().any(|q| std::ptr::eq(*q, *p)) {
816 out.push(p);
817 }
818 }
819 });
820 out
821}
822
823#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
825pub enum Providers {
826 #[default]
828 Registered,
829 None,
831}
832
833#[derive(Clone, Copy, Debug, PartialEq, Eq)]
839pub enum Presentation {
840 Window,
842 Navigation,
845}
846
847#[must_use]
850pub struct Preferences {
851 about: Option<About>,
852 groups: Vec<Group>,
853 providers: Providers,
854 explicit: Vec<&'static Provider>,
855 excluded: Vec<&'static str>,
856 presentation: Option<Presentation>,
857 window_size: day_spec::Size,
858 title: Option<TextSource>,
859}
860
861impl Default for Preferences {
862 fn default() -> Self {
863 Self::new()
864 }
865}
866
867impl Preferences {
868 pub fn new() -> Self {
869 Preferences {
870 about: None,
871 groups: Vec::new(),
872 providers: Providers::Registered,
873 explicit: Vec::new(),
874 excluded: Vec::new(),
875 presentation: None,
876 window_size: day_spec::Size::new(560.0, 640.0),
877 title: None,
878 }
879 }
880 pub fn about(mut self, about: About) -> Self {
882 self.about = Some(about);
883 self
884 }
885 pub fn group(mut self, group: Group) -> Self {
887 self.groups.push(group);
888 self
889 }
890 pub fn providers(mut self, policy: Providers) -> Self {
892 self.providers = policy;
893 self
894 }
895 pub fn provider(mut self, p: &'static Provider) -> Self {
898 self.explicit.push(p);
899 self
900 }
901 pub fn without_provider(mut self, id: &'static str) -> Self {
903 self.excluded.push(id);
904 self
905 }
906 pub fn presentation(mut self, p: Presentation) -> Self {
908 self.presentation = Some(p);
909 self
910 }
911 pub fn window_size(mut self, width: f64, height: f64) -> Self {
913 self.window_size = day_spec::Size::new(width, height);
914 self
915 }
916 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
918 self.title = Some(t.into_text());
919 self
920 }
921
922 pub fn install(self) -> Prefs {
925 let Preferences {
926 about,
927 mut groups,
928 providers,
929 explicit,
930 excluded,
931 presentation,
932 window_size,
933 title,
934 } = self;
935 let mut chosen: Vec<&'static Provider> = Vec::new();
937 if providers == Providers::Registered {
938 chosen.extend(all_providers());
939 }
940 for p in explicit {
941 if !chosen.iter().any(|q| std::ptr::eq(*q, p)) {
942 chosen.push(p);
943 }
944 }
945 chosen.retain(|p| !excluded.contains(&p.id) && (p.available)());
946 for p in &chosen {
947 if let Some(startup) = p.startup {
948 startup();
949 }
950 groups.push((p.group)().order(p.order));
951 }
952 groups.sort_by_key(|g| g.order);
953 let presentation = presentation.unwrap_or_else(default_presentation);
954 let title = title.unwrap_or_else(|| TextSource::Dyn(Rc::new(platform_word)));
955 let installed = Rc::new(Installed {
956 in_nav: Cell::default(),
957 about,
958 groups,
959 presentation,
960 title,
961 selected: Signal::global(String::new()),
962 path: Signal::global(Vec::new()),
963 });
964 INSTALLED.with(|i| *i.borrow_mut() = Some(installed.clone()));
965
966 match presentation {
972 Presentation::Window => {
973 let inst = installed.clone();
974 day_core::register_preferences_with(
975 day_spec::WindowOptions {
976 title: installed.title.initial(),
977 size: window_size,
978 size_to_fit: true,
979 ..day_spec::WindowOptions::default()
980 },
981 move || window_shell(inst.clone()),
982 );
983 }
984 Presentation::Navigation
985 if day_core::capability(Cap::AppMenu) != Support::Unsupported =>
986 {
987 let inst = installed.clone();
988 day_core::register_preferences_with(
989 day_spec::WindowOptions {
990 title: installed.title.initial(),
991 ..day_spec::WindowOptions::default()
992 },
993 move || navigation_shell_with_done(inst.clone()),
994 );
995 }
996 Presentation::Navigation => {}
997 }
998 if installed.about.is_some() {
999 install_about(installed.clone());
1000 }
1001 register_route_controller(installed.clone());
1002 Prefs(installed)
1003 }
1004}
1005
1006struct Installed {
1008 about: Option<About>,
1009 groups: Vec<Group>,
1010 presentation: Presentation,
1011 title: TextSource,
1012 selected: Signal<String>,
1014 path: Signal<Vec<SettingsRoute>>,
1016 in_nav: std::cell::Cell<bool>,
1019}
1020
1021impl Installed {
1022 fn visible_groups(&self) -> Vec<&Group> {
1023 self.groups.iter().filter(|g| g.is_available()).collect()
1024 }
1025 fn group(&self, id: &str) -> Option<&Group> {
1026 self.groups.iter().find(|g| g.id == id && g.is_available())
1027 }
1028}
1029
1030fn platform_word() -> String {
1033 let gnome_or_kde = matches!(day_core::toolkit_key(), Some("gtk" | "qt"));
1034 if gnome_or_kde {
1035 day_localization::t(day_localization::key::day_preferences)
1036 } else {
1037 day_localization::t(day_localization::key::day_settings)
1038 }
1039}
1040
1041fn default_presentation() -> Presentation {
1042 let windows = day_core::capability(Cap::MultiWindow) != Support::Unsupported;
1045 let menu = day_core::capability(Cap::AppMenu) != Support::Unsupported;
1046 if windows && menu {
1047 Presentation::Window
1048 } else {
1049 Presentation::Navigation
1050 }
1051}
1052
1053#[derive(Clone)]
1055pub struct Prefs(Rc<Installed>);
1056
1057impl Prefs {
1058 pub fn open(&self) -> bool {
1061 open()
1062 }
1063 pub fn open_at(&self, route: &str) -> bool {
1065 open_at(route)
1066 }
1067 #[must_use]
1071 pub fn in_nav(&self) -> bool {
1072 self.0.presentation == Presentation::Navigation
1073 && day_core::capability(Cap::AppMenu) == Support::Unsupported
1074 }
1075 pub fn nav_item<K>(&self, key: impl Into<K>) -> Option<NavItem<K>> {
1080 self.in_nav().then(|| self.nav_item_everywhere(key))
1081 }
1082 pub fn nav_item_everywhere<K>(&self, key: impl Into<K>) -> NavItem<K> {
1085 self.0.in_nav.set(true);
1086 let title = self.0.title.clone();
1087 let inst = self.0.clone();
1088 item(key, move || title.initial()).page(move || navigation_shell(inst.clone()))
1089 }
1090 pub fn page(&self) -> AnyPiece {
1093 self.0.in_nav.set(true);
1094 navigation_shell(self.0.clone())
1095 }
1096 pub fn group_page(&self, id: &str) -> AnyPiece {
1098 match self.0.group(id) {
1099 Some(g) => group_page(self.0.clone(), g, false),
1100 None => column(()).any(),
1101 }
1102 }
1103 pub fn group_body(&self, id: &str) -> AnyPiece {
1107 match self.0.group(id) {
1108 Some(g) => group_body(self.0.clone(), g),
1109 None => column(()).any(),
1110 }
1111 }
1112 pub fn about_page(&self) -> AnyPiece {
1114 about_page(self.0.clone())
1115 }
1116 #[must_use]
1118 pub fn title(&self) -> String {
1119 self.0.title.initial()
1120 }
1121}
1122
1123fn installed() -> Option<Rc<Installed>> {
1124 INSTALLED.with(|i| i.borrow().clone())
1125}
1126
1127pub fn open() -> bool {
1129 let Some(inst) = installed() else {
1130 log::warn!("day-piece-settings: open() before Preferences::install()");
1131 return false;
1132 };
1133 match inst.presentation {
1134 Presentation::Window => day_core::open_preferences(),
1135 Presentation::Navigation => day_core::navigate(NAV_KEY) || open_cover(inst),
1136 }
1137}
1138
1139fn open_cover(inst: Rc<Installed>) -> bool {
1142 if day_core::window_by_key(day_core::windows::PREFERENCES_KEY).is_none() {
1146 inst.path.set(Vec::new());
1147 }
1148 day_core::open_window(
1149 day_spec::WindowOptions::default()
1150 .title(inst.title.initial())
1151 .key(day_core::windows::PREFERENCES_KEY)
1152 .kind(day_spec::WindowKind::Preferences),
1153 move || navigation_shell_with_done(inst.clone()),
1154 );
1155 true
1156}
1157
1158pub const NAV_KEY: &str = "settings";
1160
1161pub fn page() -> AnyPiece {
1164 match installed() {
1165 Some(inst) => {
1166 inst.in_nav.set(true);
1169 navigation_shell(inst)
1170 }
1171 None => column(()).any(),
1172 }
1173}
1174
1175pub fn group_page_of(id: &str) -> AnyPiece {
1177 match installed() {
1178 Some(inst) => Prefs(inst).group_page(id),
1179 None => column(()).any(),
1180 }
1181}
1182
1183pub fn open_at(route: &str) -> bool {
1185 let Some(inst) = installed() else {
1186 return false;
1187 };
1188 let (group, _row) = route.split_once('/').unwrap_or((route, ""));
1189 if group == "about" {
1190 return day_core::open_about();
1191 }
1192 if inst.group(group).is_none() {
1193 return false;
1194 }
1195 match inst.presentation {
1196 Presentation::Window => {
1197 inst.selected.set_if_changed(group.to_string());
1198 day_core::open_preferences()
1199 }
1200 Presentation::Navigation => {
1201 let inside = day_core::current_route()
1204 .is_some_and(|r| r == NAV_KEY || r.starts_with(&format!("{NAV_KEY}/")));
1205 let ok = inside || open();
1206 inst.path.set(vec![SettingsRoute::Group(group.to_string())]);
1207 ok
1208 }
1209 }
1210}
1211
1212fn register_route_controller(inst: Rc<Installed>) {
1229 let menu = day_core::capability(Cap::AppMenu) != Support::Unsupported;
1233 if inst.presentation != Presentation::Window && !menu {
1234 register_cover_route_controller(inst);
1235 return;
1236 }
1237 let open_surface = day_core::open_preferences;
1238 let root = inst.clone();
1239 let open_root = open_surface;
1240 let _root_token = day_core::register_nav(day_core::NavController {
1241 push: Box::new(move |route| {
1242 if route == NAV_KEY {
1243 open_root()
1244 } else if route == "about" {
1245 day_core::open_about()
1246 } else if root.group(route).is_some() {
1247 open_at(route)
1248 } else {
1249 false
1250 }
1251 }),
1252 pop: Box::new(|_| false),
1253 current: Box::new(String::new),
1254 enter: Box::new(move |segment| segment == NAV_KEY && open_surface()),
1255 segments: Box::new(Vec::new),
1256 depth: 0,
1257 layer: Box::new(|| 0),
1258 active: Box::new(|| true),
1259 });
1260 let group = inst;
1261 let _group_token = day_core::register_nav(day_core::NavController {
1262 push: Box::new(|_| false),
1263 pop: Box::new(|_| false),
1264 current: Box::new(String::new),
1265 enter: Box::new(move |segment| group.group(segment).is_some() && open_at(segment)),
1266 segments: Box::new(Vec::new),
1267 depth: 0,
1274 layer: Box::new(|| 0),
1275 active: Box::new(|| true),
1276 });
1277}
1278
1279fn register_cover_route_controller(inst: Rc<Installed>) {
1287 let root = inst.clone();
1288 let active = inst.clone();
1289 let enter = inst;
1290 let _token = day_core::register_nav_fallback(day_core::NavController {
1291 push: Box::new(move |route| {
1292 if route == NAV_KEY {
1293 open_cover(root.clone())
1294 } else if route == "about" {
1295 day_core::open_about()
1296 } else if root.group(route).is_some() {
1297 open_cover(root.clone());
1298 root.path.set(vec![SettingsRoute::Group(route.to_string())]);
1299 true
1300 } else {
1301 false
1302 }
1303 }),
1304 pop: Box::new(|_| false),
1305 current: Box::new(String::new),
1306 enter: Box::new(move |segment| {
1308 if enter.group(segment).is_none() {
1309 return false;
1310 }
1311 enter
1312 .path
1313 .set(vec![SettingsRoute::Group(segment.to_string())]);
1314 true
1315 }),
1316 segments: Box::new(Vec::new),
1317 depth: 0,
1318 layer: Box::new(|| 0),
1319 active: Box::new(move || !active.in_nav.get()),
1320 });
1321}
1322
1323fn install_about(inst: Rc<Installed>) {
1324 #[cfg(feature = "gtk")]
1325 {
1326 if gtk_impl::install_about(inst.clone()) {
1327 return;
1328 }
1329 }
1330 let name = inst.about.as_ref().map_or_default(About::display_name);
1331 let title = day_localization_ui::res::str::day_about_app(name);
1332 let cover = day_core::capability(day_spec::Cap::MultiWindow) == day_spec::Support::Unsupported;
1335 day_core::register_about_window(
1336 day_spec::WindowOptions {
1337 title: title.format(),
1338 size: day_spec::Size::new(320.0, 480.0),
1339 size_to_fit: true,
1340 ..day_spec::WindowOptions::default()
1341 },
1342 move || {
1343 if cover {
1344 let title = title.clone();
1345 nav_stack(
1346 Signal::new(Vec::<SettingsRoute>::new()),
1347 about_page(inst.clone()),
1348 )
1349 .title(move || title.format())
1350 .toolbar(
1351 toolbar_button(
1352 day_core::id!(about_done),
1353 day_localization_ui::res::str::day_settings_done(),
1354 )
1355 .action(|| {
1356 if let Some(w) = day_core::window_by_key(day_core::windows::ABOUT_KEY) {
1357 w.close();
1358 }
1359 }),
1360 )
1361 .any()
1362 } else {
1363 about_page(inst.clone())
1364 }
1365 },
1366 );
1367}
1368
1369pref_enum! {
1374 pub enum Appearance { Light = "light", Dark = "dark", System = "system" }
1377}
1378
1379pub static APPEARANCE: Pref<Appearance> =
1381 Pref::new("day.appearance", || Appearance::System).env("DAY_THEME");
1382
1383pub static LANGUAGE: Pref<String> = Pref::new("day.locale", String::new).env("DAY_LOCALE");
1386
1387fn system_locale() -> String {
1388 SYSTEM_LOCALE
1389 .with(|c| c.get().cloned())
1390 .unwrap_or_else(|| day_localization_ui::locale().get_untracked())
1391}
1392
1393fn apply_appearance(a: Appearance) {
1394 if day_core::capability(Cap::Appearance) == Support::Unsupported {
1395 return;
1396 }
1397 day_core::set_appearance(match a {
1398 Appearance::Light => Some(false),
1399 Appearance::Dark => Some(true),
1400 Appearance::System => None,
1401 });
1402}
1403
1404fn apply_language(tag: &str) {
1405 if tag.is_empty() {
1406 day_localization_ui::set_locale(&system_locale());
1407 } else {
1408 day_localization_ui::set_locale(tag);
1409 }
1410}
1411
1412pub fn wire_general() {
1418 if GENERAL_WIRED.with(|w| w.replace(true)) {
1419 return;
1420 }
1421 SYSTEM_LOCALE.with(|c| {
1422 let _ = c.set(day_localization_ui::locale().get_untracked());
1423 });
1424 if !APPEARANCE.env_forced() {
1425 apply_appearance(APPEARANCE.get_untracked());
1426 }
1427 if !LANGUAGE.env_forced() {
1428 let tag = LANGUAGE.get_untracked();
1429 if !tag.is_empty() {
1430 apply_language(&tag);
1431 }
1432 }
1433 let root = day_reactive::Scope::root();
1434 root.enter(|| {
1435 APPEARANCE.watch(|a| apply_appearance(*a));
1436 LANGUAGE.watch(|tag| apply_language(tag));
1437 });
1438}
1439
1440pub fn general_group(locales: LocaleTable) -> Group {
1444 wire_general();
1445 Group::new(
1446 "general",
1447 day_localization_ui::res::str::day_settings_general(),
1448 )
1449 .icon(day_spec::Symbol::Settings)
1450 .row(appearance_row())
1451 .row(language_row(locales))
1452}
1453
1454pub fn appearance_row() -> Row {
1456 wire_general();
1457 rows::choice(
1458 &APPEARANCE,
1459 day_localization_ui::res::str::day_settings_theme(),
1460 [
1461 (
1462 Appearance::Light,
1463 day_localization_ui::res::str::day_theme_light(),
1464 ),
1465 (
1466 Appearance::Dark,
1467 day_localization_ui::res::str::day_theme_dark(),
1468 ),
1469 (
1470 Appearance::System,
1471 day_localization_ui::res::str::day_theme_system(),
1472 ),
1473 ],
1474 )
1475 .segmented()
1476 .id(day_core::id!(theme_picker))
1477 .requires(Cap::Appearance)
1478}
1479
1480pub fn language_row(locales: LocaleTable) -> Row {
1482 wire_general();
1483 let mut options: Vec<(String, TextSource)> = vec![(
1484 String::new(),
1485 day_localization_ui::res::str::day_theme_system().into_text(),
1486 )];
1487 options.extend(
1488 locales
1489 .iter()
1490 .map(|(tag, name)| ((*tag).to_string(), TextSource::Static((*name).to_string()))),
1491 );
1492 choice_text(
1493 &LANGUAGE,
1494 day_localization_ui::res::str::day_settings_language(),
1495 options,
1496 )
1497 .id(day_core::id!(language_picker))
1498}
1499
1500fn choice_text<T: PrefValue, M>(
1503 pref: &'static Pref<T>,
1504 title: impl IntoText<M>,
1505 options: Vec<(T, TextSource)>,
1506) -> Row {
1507 rows::choice(
1508 pref,
1509 title,
1510 options.into_iter().map(|(v, l)| (v, Resolved(l))),
1511 )
1512}
1513
1514struct Resolved(TextSource);
1516struct ResolvedMark;
1517impl IntoText<ResolvedMark> for Resolved {
1518 fn into_text(self) -> TextSource {
1519 self.0
1520 }
1521}
1522
1523#[derive(Clone, PartialEq, Debug)]
1530pub enum SettingsRoute {
1531 About,
1532 Group(String),
1533}
1534
1535impl Route for SettingsRoute {
1536 fn key(&self) -> String {
1537 match self {
1538 SettingsRoute::About => "about".into(),
1539 SettingsRoute::Group(g) => g.clone(),
1540 }
1541 }
1542 fn from_key(key: &str) -> Option<Self> {
1543 Some(match key {
1544 "about" => SettingsRoute::About,
1545 g => SettingsRoute::Group(g.to_string()),
1546 })
1547 }
1548 fn title(&self) -> String {
1550 match self {
1551 SettingsRoute::About => day_localization::t(day_localization::key::day_about),
1552 SettingsRoute::Group(g) => match g.strip_prefix("page:") {
1554 Some(title) => title.to_string(),
1555 None => installed()
1556 .and_then(|i| i.group(g).map(|g| resolve_text(&g.title)))
1557 .unwrap_or_else(|| g.clone()),
1558 },
1559 }
1560 }
1561}
1562
1563fn text_label(t: &TextSource) -> Label {
1564 match t {
1565 TextSource::Static(s) => label(s.clone()),
1566 TextSource::Dyn(f) => {
1567 let f = f.clone();
1568 label(move || f())
1569 }
1570 }
1571}
1572
1573fn text_source_fn(t: &TextSource) -> impl Fn() -> String + 'static {
1577 let t = t.clone();
1578 move || resolve_text(&t)
1579}
1580
1581pub(crate) fn resolve_text(t: &TextSource) -> String {
1583 match t {
1584 TextSource::Static(s) => s.clone(),
1585 TextSource::Dyn(f) => f(),
1586 }
1587}
1588
1589pub(crate) fn choice_picker(
1594 labels: &[TextSource],
1595 index: Signal<usize>,
1596 segmented: bool,
1597 enabled: impl Fn() -> bool + 'static,
1598) -> day_pieces::Picker<usize, day_pieces::Required<Signal<usize>>> {
1599 let options: Vec<(usize, TextSource)> = labels.iter().cloned().enumerate().collect();
1600 let mut p = picker(index, options).enabled(enabled);
1601 if segmented {
1602 p = p.segmented();
1603 }
1604 p
1605}
1606
1607pub(crate) fn stepper_buttons(
1612 v: Signal<f64>,
1613 range: &std::ops::RangeInclusive<f64>,
1614 step: f64,
1615 enabled: impl Fn() -> bool + Clone + 'static,
1616) -> (day_pieces::Button, day_pieces::Button) {
1617 let (lo, hi, st) = (*range.start(), *range.end(), step);
1618 let enabled_inc = enabled.clone();
1619 let dec = button("−")
1620 .action(move || v.set((v.get_untracked() - st).max(lo)))
1621 .enabled(move || enabled() && v.get() > lo);
1622 let inc = button("+")
1623 .action(move || v.set((v.get_untracked() + st).min(hi)))
1624 .enabled(move || enabled_inc() && v.get() < hi);
1625 (dec, inc)
1626}
1627
1628pub(crate) fn stepper_control(
1631 value: Signal<f64>,
1632 dec: day_pieces::Button,
1633 inc: day_pieces::Button,
1634 id: Option<&day_core::ElementId>,
1635) -> AnyPiece {
1636 let value_label = label(move || format!("{}", value.get() as i64)).tabular();
1637 match id {
1638 Some(id) => row((
1639 dec.id(day_core::id!(pref_decrement, id.as_str())),
1640 value_label.id(id.clone()),
1641 inc.id(day_core::id!(pref_increment, id.as_str())),
1642 ))
1643 .spacing(8.0)
1644 .align(VAlign::Center)
1645 .any(),
1646 None => row((dec, value_label, inc))
1647 .spacing(8.0)
1648 .align(VAlign::Center)
1649 .any(),
1650 }
1651}
1652
1653fn window_shell(inst: Rc<Installed>) -> AnyPiece {
1656 #[cfg(all(feature = "appkit", target_os = "macos"))]
1657 {
1658 if let Some(p) = appkit_impl::window_shell(inst.clone()) {
1659 return p;
1660 }
1661 }
1662 #[cfg(feature = "gtk")]
1663 {
1664 if let Some(p) = gtk_impl::window_shell(inst.clone()) {
1665 return p;
1666 }
1667 }
1668 #[cfg(feature = "qt")]
1669 {
1670 if let Some(p) = qt_impl::window_shell(inst.clone()) {
1671 return p;
1672 }
1673 }
1674 composed_window_shell(inst)
1675}
1676
1677#[expect(
1678 clippy::needless_pass_by_value,
1679 reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
1680)]
1681fn composed_window_shell(inst: Rc<Installed>) -> AnyPiece {
1682 let groups = inst.visible_groups();
1683 if groups.len() <= 1 {
1684 return match groups.first() {
1685 Some(g) => group_page(inst.clone(), g, true),
1686 None => column(()).any(),
1687 };
1688 }
1689 if inst.selected.get_untracked().is_empty() {
1690 inst.selected.set(groups[0].id.to_string());
1691 }
1692 let mut nav = nav(inst.selected)
1693 .style(NavStyle::Sidebar)
1694 .local()
1695 .id(day_core::id!(prefs_nav));
1696 for g in groups {
1697 let id = g.id;
1698 let title = text_source_fn(&g.title);
1699 let inst2 = inst.clone();
1700 let build = move || {
1701 let inst = inst2.clone();
1702 match inst.group(id) {
1703 Some(g) => group_page(inst.clone(), g, true),
1704 None => column(()).any(),
1705 }
1706 };
1707 nav = match &g.icon {
1708 Some(GroupIcon::Image(name)) => {
1709 nav.items(item(id, title).icon(name.clone()).page(build))
1710 }
1711 _ => nav.item(id, title, build),
1712 };
1713 }
1714 let nav = nav.any();
1715 #[cfg(all(feature = "xaml", target_os = "windows"))]
1716 let nav = xaml_impl::sidebar_symbols(nav, &inst.visible_groups());
1717 nav
1718}
1719
1720fn group_page(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
1722 if !desktop {
1725 #[cfg(all(feature = "uikit", target_os = "ios"))]
1726 {
1727 if let Some(p) = uikit_impl::group_page(inst.clone(), g) {
1728 return p;
1729 }
1730 }
1731 #[cfg(all(feature = "material", target_os = "android"))]
1732 {
1733 if let Some(p) = android_impl::group_page(inst.clone(), g) {
1734 return p;
1735 }
1736 }
1737 #[cfg(all(feature = "arkui", target_env = "ohos"))]
1738 {
1739 if let Some(p) = arkui_impl::group_page(inst.clone(), g) {
1740 return p;
1741 }
1742 }
1743 }
1744 composed_group_page(inst, g, desktop)
1745}
1746
1747fn group_body(inst: Rc<Installed>, g: &Group) -> AnyPiece {
1750 #[cfg(all(feature = "uikit", target_os = "ios"))]
1751 {
1752 if let Some(p) = uikit_impl::group_body(inst.clone(), g) {
1753 return p;
1754 }
1755 }
1756 #[cfg(all(feature = "material", target_os = "android"))]
1757 {
1758 if let Some(p) = android_impl::group_body(inst.clone(), g) {
1759 return p;
1760 }
1761 }
1762 #[cfg(all(feature = "arkui", target_env = "ohos"))]
1763 {
1764 if let Some(p) = arkui_impl::group_body(inst.clone(), g) {
1765 return p;
1766 }
1767 }
1768 column((composed_group_form(inst, g, false),))
1769 .align(HAlign::Leading)
1770 .padding(16.0)
1771 .grow(Dimension::Width)
1772 .any()
1773}
1774
1775#[expect(
1777 clippy::needless_pass_by_value,
1778 reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
1779)]
1780fn composed_group_form(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
1781 let mut parts: Vec<AnyPiece> = Vec::new();
1782 for s in &g.sections {
1783 if let Some(p) = section_piece(inst.clone(), s, desktop) {
1784 parts.push(p);
1785 }
1786 }
1787 if let Some(custom) = &g.custom {
1788 parts.push(custom());
1789 }
1790 form(parts).id(day_core::id!(prefs_group, g.id)).any()
1791}
1792
1793fn composed_group_page(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
1795 let body = composed_group_form(inst, g, desktop);
1796 if desktop {
1799 hugging_scroll(
1800 column((body,))
1801 .align(HAlign::Leading)
1802 .padding(20.0)
1803 .grow(Dimension::Width),
1804 )
1805 .any()
1806 } else {
1807 scroll(
1808 column((body,))
1809 .align(HAlign::Leading)
1810 .padding(16.0)
1811 .grow(Dimension::Width),
1812 )
1813 .any()
1814 }
1815}
1816
1817#[expect(
1818 clippy::needless_pass_by_value,
1819 reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
1820)]
1821fn section_piece(inst: Rc<Installed>, s: &Section, desktop: bool) -> Option<AnyPiece> {
1822 let rows: Vec<AnyPiece> = s
1823 .rows
1824 .iter()
1825 .filter(|r| r.is_available())
1826 .map(|r| row_piece(inst.clone(), r, desktop))
1827 .collect();
1828 if rows.is_empty() {
1829 return None;
1830 }
1831 let mut sec = section(rows);
1832 if let Some(t) = &s.title {
1833 sec = sec.title(text_source_fn(t));
1834 }
1835 if let Some(f) = &s.footer {
1836 sec = sec.footer(text_source_fn(f));
1837 }
1838 Some(sec.any())
1839}
1840
1841fn row_piece(inst: Rc<Installed>, r: &Row, desktop: bool) -> AnyPiece {
1844 #[cfg(feature = "gtk")]
1845 {
1846 if let Some(p) = gtk_impl::row_piece(inst.clone(), r, desktop) {
1847 return p;
1848 }
1849 }
1850 #[cfg(all(feature = "uikit", target_os = "ios"))]
1851 {
1852 if let Some(p) = uikit_impl::row_piece(inst.clone(), r, desktop) {
1853 return p;
1854 }
1855 }
1856 #[cfg(all(feature = "material", target_os = "android"))]
1857 {
1858 if let Some(p) = android_impl::row_piece(inst.clone(), r, desktop) {
1859 return p;
1860 }
1861 }
1862 #[cfg(all(feature = "xaml", target_os = "windows"))]
1863 {
1864 if let Some(p) = xaml_impl::row_piece(inst.clone(), r, desktop) {
1865 return p;
1866 }
1867 }
1868 #[cfg(all(feature = "arkui", target_env = "ohos"))]
1869 {
1870 if let Some(p) = arkui_impl::row_piece(inst.clone(), r, desktop) {
1871 return p;
1872 }
1873 }
1874 composed_row(inst, r, desktop)
1875}
1876
1877fn title_column(r: &Row) -> AnyPiece {
1879 let title = text_label(&r.title);
1880 match &r.caption {
1881 Some(c) => column((
1882 title,
1883 text_label(c).font(day_spec::Font::Footnote).secondary(),
1884 ))
1885 .spacing(2.0)
1886 .align(HAlign::Leading)
1887 .any(),
1888 None => title.any(),
1889 }
1890}
1891
1892fn trailing_row(titles: AnyPiece, control: AnyPiece) -> AnyPiece {
1895 row((titles.max_width(TITLE_COLUMN_MAX), spacer(), control))
1898 .spacing(12.0)
1899 .align(VAlign::Center)
1900 .grow(Dimension::Width)
1901 .any()
1902}
1903
1904const TITLE_COLUMN_MAX: f64 = 360.0;
1906const SLIDER_WIDTH: f64 = 200.0;
1908const VALUE_WIDTH: f64 = 52.0;
1910
1911fn composed_row(inst: Rc<Installed>, r: &Row, _desktop: bool) -> AnyPiece {
1912 let id = r.id.clone();
1913 let enabled = r.enabled.clone();
1914 let with_id = |p: AnyPiece| match &id {
1915 Some(id) => p.id(id.clone()).any(),
1916 None => p,
1917 };
1918 let enabled_fn = move || enabled.as_ref().is_none_or(day_pieces::Reactive::get);
1919 match &r.kind {
1920 RowKind::Toggle(sig) => {
1921 let ctl = with_id(toggle(*sig).enabled(enabled_fn).any());
1922 trailing_row(title_column(r), ctl)
1923 }
1924 RowKind::Choice {
1925 labels,
1926 index,
1927 style,
1928 } => {
1929 let p = choice_picker(labels, *index, *style == ChoiceStyle::Segmented, enabled_fn);
1930 trailing_row(title_column(r), with_id(p.any()))
1931 }
1932 RowKind::Slider {
1933 value,
1934 range,
1935 step,
1936 value_text,
1937 } => {
1938 let mut s = slider(*value).range(range.clone()).enabled(enabled_fn);
1939 if let Some(st) = step {
1940 s = s.step(*st);
1941 }
1942 let ctl = match &id {
1947 Some(i) => s
1948 .id(i.clone())
1949 .min_width(SLIDER_WIDTH)
1950 .max_width(SLIDER_WIDTH)
1951 .any(),
1952 None => s.min_width(SLIDER_WIDTH).max_width(SLIDER_WIDTH).any(),
1953 };
1954 let ctl = match value_text {
1955 Some(f) => {
1956 let f = f.clone();
1957 let v = *value;
1958 let value_label = label(move || f(v.get()))
1961 .tabular()
1962 .secondary()
1963 .single_line()
1964 .align(day_spec::props::TextAlign::Trailing);
1965 let value_label = match &id {
1966 Some(i) => value_label
1967 .id(day_core::id!(pref_value, i.as_str()))
1968 .min_width(VALUE_WIDTH)
1969 .max_width(VALUE_WIDTH)
1970 .any(),
1971 None => value_label
1972 .min_width(VALUE_WIDTH)
1973 .max_width(VALUE_WIDTH)
1974 .any(),
1975 };
1976 row((ctl, value_label))
1977 .spacing(8.0)
1978 .align(VAlign::Center)
1979 .any()
1980 }
1981 None => ctl,
1982 };
1983 trailing_row(title_column(r), ctl)
1984 }
1985 RowKind::Stepper { value, range, step } => {
1986 let v = *value;
1987 let (dec, inc) = stepper_buttons(v, range, *step, enabled_fn);
1988 let ctl = stepper_control(v, dec, inc, id.as_ref());
1989 trailing_row(title_column(r), ctl)
1990 }
1991 RowKind::Text {
1992 value,
1993 placeholder,
1994 secure,
1995 } => {
1996 let mut f = if *secure {
1997 secure_field(*value)
1998 } else {
1999 text_field(*value)
2000 };
2001 if let Some(ph) = placeholder {
2002 f = f.placeholder(text_source_fn(ph));
2003 }
2004 let f = f.enabled(enabled_fn);
2005 let ctl = match &id {
2006 Some(i) => f
2007 .id(i.clone())
2008 .grow(Dimension::Width)
2009 .min_width(160.0)
2010 .any(),
2011 None => f.grow(Dimension::Width).min_width(160.0).any(),
2012 };
2013 trailing_row(title_column(r), ctl)
2014 }
2015 RowKind::Action {
2016 on,
2017 destructive: _,
2018 confirm,
2019 confirm_label,
2020 busy,
2021 } => {
2022 let on = on.clone();
2023 let title = text_source_fn(&r.title);
2024 let confirm = confirm.clone();
2025 let confirm_label = confirm_label.clone();
2026 let busy = busy.clone();
2027 let run = move || {
2028 let on = on.clone();
2029 match &confirm {
2030 Some(message) => {
2031 let message = message.initial();
2032 let title = title();
2033 let label = confirm_label.as_ref().map(TextSource::initial);
2034 day_core::task(async move {
2035 if crate::confirm_dialog(&title, &message, label).await {
2036 on();
2037 }
2038 });
2039 }
2040 None => on(),
2041 }
2042 };
2043 let busy_gate = busy.clone();
2044 let b = button(text_source_fn(&r.title))
2045 .action(run)
2046 .enabled(move || {
2047 enabled_fn() && !busy_gate.as_ref().is_some_and(day_pieces::Reactive::get)
2048 });
2049 let ctl = with_id(b.any());
2050 let ctl = match busy {
2051 Some(b) => row((when(move || b.get(), spinner), ctl))
2052 .spacing(8.0)
2053 .align(VAlign::Center)
2054 .any(),
2055 None => ctl,
2056 };
2057 match &r.caption {
2060 Some(c) => trailing_row(caption_only(c), ctl),
2061 None => ctl,
2062 }
2063 }
2064 RowKind::Link(url) => {
2065 let url = url.clone();
2066 let l = link(text_source_fn(&r.title), url);
2067 match &r.caption {
2068 Some(c) => trailing_row(caption_only(c), with_id(l.any())),
2069 None => with_id(l.any()),
2070 }
2071 }
2072 RowKind::Navigate(build) => {
2073 let build = build.clone();
2074 let title = text_source_fn(&r.title);
2075 let open = move || {
2076 let build = build.clone();
2077 let title = title();
2078 push_subpage(inst.clone(), title, build);
2079 };
2080 with_id(
2081 row((title_column(r), spacer(), label("›").secondary()))
2082 .spacing(12.0)
2083 .align(VAlign::Center)
2084 .grow(Dimension::Width)
2085 .on_tap(open)
2086 .any(),
2087 )
2088 }
2089 RowKind::Info { value, copyable } => {
2090 let v = text_label(value).secondary();
2091 let v = if *copyable {
2092 let text = value.clone();
2094 row((
2095 v,
2096 button("")
2097 .icon(day_spec::Symbol::Copy)
2098 .icon_only()
2099 .plain()
2100 .action(move || {
2101 let _ = day_part_clipboard::set_text(&text.initial());
2102 }),
2103 ))
2104 .spacing(4.0)
2105 .align(VAlign::Center)
2106 .any()
2107 } else {
2108 v.any()
2109 };
2110 trailing_row(title_column(r), with_id(v))
2111 }
2112 RowKind::Note => with_id(
2113 text_label(&r.title)
2114 .font(day_spec::Font::Footnote)
2115 .secondary()
2116 .any(),
2117 ),
2118 RowKind::Custom(build) => with_id(build()),
2119 }
2120}
2121
2122#[expect(
2125 clippy::needless_pass_by_value,
2126 reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2127)]
2128fn push_subpage(inst: Rc<Installed>, title: String, build: Build) {
2129 SUBPAGES.with(|s| s.borrow_mut().insert(title.clone(), build.clone()));
2130 #[cfg(feature = "gtk")]
2131 {
2132 if gtk_impl::push_subpage(inst.clone(), title.clone(), build.clone()) {
2134 return;
2135 }
2136 }
2137 if inst.presentation == Presentation::Navigation {
2138 inst.path
2139 .update(|p| p.push(SettingsRoute::Group(format!("page:{title}"))));
2140 } else {
2141 day_core::open_window(
2142 day_spec::WindowOptions::default()
2143 .key(format!("day.settings.{title}"))
2144 .title(title)
2145 .size(480.0, 560.0)
2146 .size_to_fit()
2147 .kind(day_spec::WindowKind::Preferences),
2148 move || build(),
2149 );
2150 }
2151}
2152
2153async fn confirm_dialog(title: &str, message: &str, label: Option<String>) -> bool {
2154 let dialog = confirm(title.to_string())
2155 .message(message.to_string())
2156 .destructive();
2157 match label {
2158 Some(l) => dialog.confirm_label(l).await,
2159 None => dialog.await,
2160 }
2161}
2162
2163fn caption_only(c: &TextSource) -> AnyPiece {
2165 text_label(c)
2166 .font(day_spec::Font::Footnote)
2167 .secondary()
2168 .any()
2169}
2170
2171fn navigation_shell(inst: Rc<Installed>) -> AnyPiece {
2173 navigation_stack(inst, false)
2174}
2175
2176fn navigation_shell_with_done(inst: Rc<Installed>) -> AnyPiece {
2178 navigation_stack(inst, true)
2179}
2180
2181#[expect(
2182 clippy::needless_pass_by_value,
2183 reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2184)]
2185fn navigation_stack(inst: Rc<Installed>, done: bool) -> AnyPiece {
2186 let root_inst = inst.clone();
2187 let dest_inst = inst.clone();
2188 let mut stack = nav_stack(inst.path, root_page(root_inst))
2189 .title(text_source_fn(&inst.title))
2190 .destination(move |r: &SettingsRoute| destination(dest_inst.clone(), r));
2191 if done {
2192 stack = stack.toolbar(
2193 toolbar_button(
2194 day_core::id!(settings_done),
2195 day_localization_ui::res::str::day_settings_done(),
2196 )
2197 .action(|| {
2198 if let Some(w) = day_core::window_by_key(day_core::windows::PREFERENCES_KEY) {
2199 w.close();
2200 }
2201 })
2202 .placement(day_spec::ToolbarPlacement::Primary),
2205 );
2206 }
2207 stack.id(day_core::id!(settings_stack)).any()
2208}
2209
2210fn destination(inst: Rc<Installed>, r: &SettingsRoute) -> AnyPiece {
2211 match r {
2212 SettingsRoute::About => about_page(inst),
2213 SettingsRoute::Group(g) => {
2214 if let Some(title) = g.strip_prefix("page:") {
2215 return SUBPAGES
2216 .with(|s| s.borrow().get(title).cloned())
2217 .map_or_else(|| column(()).any(), |b| b());
2218 }
2219 match inst.group(g) {
2220 Some(group) => group_page(inst.clone(), group, false),
2221 None => column(()).any(),
2222 }
2223 }
2224 }
2225}
2226
2227#[allow(dead_code)]
2233pub(crate) struct RootEntry {
2234 pub id: String,
2236 pub title: TextSource,
2237 pub subtitle: Option<TextSource>,
2238 pub icon: Option<GroupIcon>,
2239 pub open: Rc<dyn Fn()>,
2241}
2242
2243#[allow(dead_code)]
2246pub(crate) fn root_entries(inst: &Rc<Installed>) -> (Option<RootEntry>, Vec<RootEntry>) {
2247 let path = inst.path;
2248 let about = inst.about.as_ref().map(|about| RootEntry {
2249 id: "about".into(),
2250 title: TextSource::Static(about.display_name()),
2251 subtitle: about.version_line().map(TextSource::Static),
2252 icon: about.icon_name().cloned().map(GroupIcon::Image),
2253 open: Rc::new(move || path.update(|p| p.push(SettingsRoute::About))),
2254 });
2255 let groups = inst
2256 .visible_groups()
2257 .into_iter()
2258 .map(|g| {
2259 let id = g.id;
2260 RootEntry {
2261 id: id.to_string(),
2262 title: g.title.clone(),
2263 subtitle: g.subtitle.clone(),
2264 icon: g.icon.clone(),
2265 open: Rc::new(move || {
2266 path.update(|p| p.push(SettingsRoute::Group(id.to_string())));
2267 }),
2268 }
2269 })
2270 .collect();
2271 (about, groups)
2272}
2273
2274fn root_page(inst: Rc<Installed>) -> AnyPiece {
2276 #[cfg(all(feature = "uikit", target_os = "ios"))]
2277 {
2278 if let Some(p) = uikit_impl::root_page(inst.clone()) {
2279 return p;
2280 }
2281 }
2282 #[cfg(all(feature = "material", target_os = "android"))]
2283 {
2284 if let Some(p) = android_impl::root_page(inst.clone()) {
2285 return p;
2286 }
2287 }
2288 #[cfg(all(feature = "arkui", target_env = "ohos"))]
2289 {
2290 if let Some(p) = arkui_impl::root_page(inst.clone()) {
2291 return p;
2292 }
2293 }
2294 composed_root_page(inst)
2295}
2296
2297#[expect(
2300 clippy::needless_pass_by_value,
2301 reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2302)]
2303fn composed_root_page(inst: Rc<Installed>) -> AnyPiece {
2304 let mut parts: Vec<AnyPiece> = Vec::new();
2305 if let Some(about) = &inst.about {
2306 parts.push(about_header(inst.clone(), about));
2307 }
2308 let groups = inst.visible_groups();
2309 if groups.len() == 1 {
2310 let g = groups[0];
2311 for s in &g.sections {
2312 if let Some(p) = section_piece(inst.clone(), s, false) {
2313 parts.push(p);
2314 }
2315 }
2316 if let Some(custom) = &g.custom {
2317 parts.push(custom());
2318 }
2319 } else {
2320 let rows: Vec<AnyPiece> = groups
2321 .iter()
2322 .map(|g| {
2323 let id = g.id;
2324 let path = inst.path;
2325 let titles = match &g.subtitle {
2326 Some(sub) => column((
2327 text_label(&g.title),
2328 text_label(sub).font(day_spec::Font::Footnote).secondary(),
2329 ))
2330 .spacing(2.0)
2331 .align(HAlign::Leading)
2332 .any(),
2333 None => text_label(&g.title).any(),
2334 };
2335 let leading = match &g.icon {
2344 Some(GroupIcon::Image(name)) => {
2345 image(name.clone()).template().frame(24.0, 24.0).any()
2346 }
2347 Some(GroupIcon::Symbol(sym)) => match sym.outline_svg() {
2348 Some(svg) => image(svg.into_bytes()).template().frame(24.0, 24.0).any(),
2349 None => spacer().frame(24.0, 24.0).any(),
2350 },
2351 None => spacer().frame(24.0, 24.0).any(),
2352 };
2353 row((leading, titles, spacer(), label("›").secondary()))
2354 .spacing(12.0)
2355 .align(VAlign::Center)
2356 .grow(Dimension::Width)
2357 .on_tap(move || path.update(|p| p.push(SettingsRoute::Group(id.to_string()))))
2358 .id(day_core::id!(prefs_group, id))
2359 .any()
2360 })
2361 .collect();
2362 parts.push(section(rows).any());
2363 }
2364 scroll(
2365 form(parts)
2366 .padding(16.0)
2367 .grow(Dimension::Width)
2368 .id(day_core::id!(settings_root)),
2369 )
2370 .any()
2371}
2372
2373#[expect(
2375 clippy::needless_pass_by_value,
2376 reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2377)]
2378fn about_header(inst: Rc<Installed>, about: &About) -> AnyPiece {
2379 let path = inst.path;
2380 let name = about.display_name();
2381 let version = about.version_line().unwrap_or_default();
2382 let icon = match about.icon_name() {
2383 Some(n) => image(n.clone()).frame(48.0, 48.0).corner_radius(10.0).any(),
2384 None => column(()).any(),
2385 };
2386 section((row((
2387 icon,
2388 column((
2389 label(name).bold(),
2390 label(version).font(day_spec::Font::Footnote).secondary(),
2391 ))
2392 .spacing(2.0)
2393 .align(HAlign::Leading),
2394 spacer(),
2395 label("›").secondary(),
2396 ))
2397 .spacing(12.0)
2398 .align(VAlign::Center)
2399 .grow(Dimension::Width)
2400 .on_tap(move || path.update(|p| p.push(SettingsRoute::About)))
2401 .id(day_core::id!(settings_about)),))
2402 .any()
2403}
2404
2405#[expect(
2407 clippy::needless_pass_by_value,
2408 reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2409)]
2410fn about_page(inst: Rc<Installed>) -> AnyPiece {
2411 let Some(about) = &inst.about else {
2412 return column(()).any();
2413 };
2414 if let Some(custom) = about.custom_piece() {
2415 return custom;
2416 }
2417 if inst.presentation == Presentation::Navigation {
2418 #[cfg(all(feature = "uikit", target_os = "ios"))]
2419 {
2420 if let Some(p) = uikit_impl::about_page(inst.clone()) {
2421 return p;
2422 }
2423 }
2424 #[cfg(all(feature = "material", target_os = "android"))]
2425 {
2426 if let Some(p) = android_impl::about_page(inst.clone()) {
2427 return p;
2428 }
2429 }
2430 }
2431 let mut head: Vec<AnyPiece> = Vec::new();
2432 if let Some(n) = about.icon_name() {
2433 head.push(image(n.clone()).frame(96.0, 96.0).corner_radius(20.0).any());
2434 }
2435 head.push(
2436 label(about.display_name())
2437 .font(day_spec::Font::Title2)
2438 .bold()
2439 .id(day_core::id!(about_name))
2440 .any(),
2441 );
2442 if let Some(v) = about.version_line() {
2443 head.push(label(v).secondary().id(day_core::id!(about_version)).any());
2444 }
2445 if let Some(t) = about.tagline_text() {
2446 head.push(label(t).id(day_core::id!(about_tagline)).any());
2447 }
2448 let mut parts: Vec<AnyPiece> = vec![
2449 column(head)
2450 .spacing(6.0)
2451 .align(HAlign::Center)
2452 .grow(Dimension::Width)
2453 .any(),
2454 ];
2455 let mut links: Vec<AnyPiece> = about
2457 .links()
2458 .iter()
2459 .enumerate()
2460 .map(|(i, (t, url))| {
2461 link(text_source_fn(t), url.clone())
2462 .id(day_core::id!(about_link, i))
2463 .any()
2464 })
2465 .collect();
2466 if let Some(p) = about.privacy_url() {
2467 links.push(
2468 link(
2469 day_localization_ui::res::str::day_about_privacy(),
2470 p.to_string(),
2471 )
2472 .id(day_core::id!(about_privacy))
2473 .any(),
2474 );
2475 }
2476 if !links.is_empty() {
2477 parts.push(section(links).any());
2478 }
2479 let mut notes: Vec<AnyPiece> = Vec::new();
2480 if let Some(c) = about.credits_text() {
2481 let credits = c.clone();
2482 notes.push(
2483 rows::navigate(
2484 day_localization_ui::res::str::day_about_acknowledgements(),
2485 move || scroll(label(credits.clone()).padding(16.0)),
2486 )
2487 .into_piece(inst.clone()),
2488 );
2489 }
2490 if let Some(l) = about.licenses_text() {
2491 let licenses = l.clone();
2492 notes.push(
2493 rows::navigate(
2494 day_localization_ui::res::str::day_about_licenses(),
2495 move || scroll(label(licenses.clone()).monospace().padding(16.0)),
2496 )
2497 .into_piece(inst.clone()),
2498 );
2499 }
2500 if !notes.is_empty() {
2501 parts.push(section(notes).any());
2502 }
2503 if let Some(c) = about.copyright_text() {
2504 parts.push(
2505 label(c)
2506 .font(day_spec::Font::Footnote)
2507 .secondary()
2508 .id(day_core::id!(about_copyright))
2509 .any(),
2510 );
2511 }
2512 let body = form(parts)
2513 .padding(20.0)
2514 .grow(Dimension::Width)
2515 .id(day_core::id!(about_page));
2516 if inst.presentation == Presentation::Window {
2519 hugging_scroll(body).any()
2520 } else {
2521 scroll(body).any()
2522 }
2523}
2524
2525fn hugging_scroll<P: Piece>(child: P) -> impl Piece {
2530 day_core::piece_fn(move |cx: &mut day_core::BuildCx| {
2531 let node = cx.native(
2532 day_spec::kinds::SCROLL,
2533 &day_spec::props::ScrollProps {
2534 horizontal: false,
2535 ..Default::default()
2536 },
2537 Rc::new(HuggingScrollLayout),
2538 day_core::Flex {
2539 grow_w: true,
2540 ..Default::default()
2541 },
2542 day_core::Boundary::Yes,
2543 );
2544 cx.under(node, |cx| {
2545 let _ = child.build(cx);
2546 });
2547 node
2548 })
2549}
2550
2551struct HuggingScrollLayout;
2554
2555impl day_core::Layout for HuggingScrollLayout {
2556 fn measure(
2557 &self,
2558 cx: &mut dyn day_core::LayoutOps,
2559 children: &[day_core::RNode],
2560 p: day_spec::Proposal,
2561 ) -> day_spec::Size {
2562 let cs = match children.first() {
2563 Some(&c) => cx.measure_child(c, day_spec::Proposal::new(p.width, None)),
2564 None => day_spec::Size::ZERO,
2565 };
2566 let height = match p.height {
2567 Some(h) => cs.height.min(h),
2568 None => cs.height,
2569 };
2570 day_spec::Size::new(p.width.unwrap_or(cs.width), height)
2571 }
2572 fn place(
2573 &self,
2574 cx: &mut dyn day_core::LayoutOps,
2575 children: &[day_core::RNode],
2576 bounds: day_spec::Rect,
2577 ) {
2578 let Some(&c) = children.first() else {
2579 return;
2580 };
2581 let mut width = bounds.size.width;
2582 let mut cs = cx.measure_child(c, day_spec::Proposal::new(Some(width), None));
2583 if cs.height > bounds.size.height {
2584 let inset = cx.scroll_bar_inset(true);
2586 if inset > 0.0 {
2587 width = (width - inset).max(0.0);
2588 cs = cx.measure_child(c, day_spec::Proposal::new(Some(width), None));
2589 }
2590 }
2591 let content = day_spec::Size::new(width, cs.height.max(bounds.size.height));
2592 cx.place_child(c, day_spec::Rect::from_size(content));
2593 cx.set_scroll_content(content);
2594 }
2595}
2596
2597impl Row {
2598 fn into_piece(self, inst: Rc<Installed>) -> AnyPiece {
2600 let desktop = inst.presentation == Presentation::Window;
2601 row_piece(inst, &self, desktop)
2602 }
2603}
2604
2605#[cfg(feature = "conformance")]
2611pub mod conformance {
2612 struct SharedTestStore(std::rc::Rc<super::MemoryStore>);
2614 impl super::Store for SharedTestStore {
2615 fn get(&self, key: &str) -> Option<String> {
2616 self.0.get(key)
2617 }
2618 fn set(&self, key: &str, value: &str) -> bool {
2619 self.0.set(key, value)
2620 }
2621 fn remove(&self, key: &str) -> bool {
2622 self.0.remove(key)
2623 }
2624 }
2625
2626 use day_core::conformance::{Case, Drive};
2627 use day_spec::Cap;
2628
2629 use super::*;
2630
2631 static SOUND: Pref<bool> = Pref::new("conformance.sound", || true);
2632 static SCALE: Pref<f64> = Pref::new("conformance.scale", || 100.0);
2633
2634 #[cfg(all(feature = "xaml", target_os = "windows"))]
2637 #[day_macros::test(day_core)]
2638 fn settings_card_keeps_header_readable() -> Case {
2639 Case::new()
2640 .proves("day-piece-settings.row")
2641 .page(|| {
2642 let inst = Rc::new(Installed {
2643 in_nav: Default::default(),
2644 about: None,
2645 groups: Vec::new(),
2646 presentation: Presentation::Window,
2647 title: TextSource::Static("Settings".into()),
2648 selected: Signal::new(String::new()),
2649 path: Signal::new(Vec::new()),
2650 });
2651 let narrow = xaml_impl::row_piece(
2652 inst.clone(),
2653 &appearance_row().id(day_core::id!(settings::narrow_theme)),
2654 true,
2655 )
2656 .unwrap();
2657 let wide = xaml_impl::row_piece(
2658 inst,
2659 &appearance_row().id(day_core::id!(settings::wide_theme)),
2660 true,
2661 )
2662 .unwrap();
2663 column((
2664 narrow.id(day_core::id!(settings::narrow_card)).width(250.0),
2665 wide.id(day_core::id!(settings::wide_card)).width(520.0),
2666 ))
2667 })
2668 .drive(|d: Drive| async move {
2669 for (card_id, control_id, stacked) in [
2670 ("settings::narrow_card", "settings::narrow_theme", true),
2671 ("settings::wide_card", "settings::wide_theme", false),
2672 ] {
2673 d.assert_frame(card_id, day_core::conformance::FrameExpect {
2674 width: Some(if stacked { 250.0 } else { 520.0 }),
2675 ..Default::default()
2676 }).await?;
2677 let (card, control) = day_core::with_tree(|t| {
2678 let card = t
2679 .read_native(t.find_by_id(card_id).unwrap())
2680 .unwrap()
2681 .frame
2682 .unwrap();
2683 let control = t
2684 .read_native(t.find_by_id(control_id).unwrap())
2685 .unwrap()
2686 .frame
2687 .unwrap();
2688 (card, control)
2689 });
2690 let y = control.origin.y - card.origin.y;
2691 d.check(
2692 if stacked { y >= 48.0 } else { y < 40.0 },
2693 "the theme control must move below its header only in a narrow card",
2694 )?;
2695 d.check(
2696 control.origin.x >= card.origin.x + 15.0
2697 && control.origin.x + control.size.width
2698 <= card.origin.x + card.size.width - 15.0,
2699 &format!("the theme control must remain within the card padding: {card:?}, {control:?}"),
2700 )?;
2701 }
2702 d.select("settings::narrow_theme", 1).await?;
2703 d.check(
2704 APPEARANCE.get_untracked() == Appearance::Dark,
2705 "reflowed theme control must remain interactive",
2706 )?;
2707 d.select("settings::narrow_theme", 2).await
2708 })
2709 }
2710
2711 #[day_macros::test(day_core)]
2713 fn settings_theme_applies_and_persists() -> Case {
2714 let store = Rc::new(MemoryStore::default());
2715 let page_store = store.clone();
2716 Case::new()
2717 .proves_cap(Cap::Appearance)
2718 .proves_duty("set_appearance")
2719 .requires(Cap::Appearance)
2720 .page(move || {
2721 install_store(SharedTestStore(page_store.clone()));
2722 let inst = Rc::new(Installed {
2723 in_nav: Cell::default(),
2724 about: None,
2725 groups: vec![Group::new("general", "General").row(appearance_row())],
2726 presentation: Presentation::Window,
2727 title: TextSource::Static("Settings".into()),
2728 selected: Signal::new(String::new()),
2729 path: Signal::new(Vec::new()),
2730 });
2731 let g = inst.groups[0].clone();
2732 column((group_page(inst, &g, true),))
2733 })
2734 .drive(move |d: Drive| {
2735 let store = store.clone();
2736 async move {
2737 d.select(day_core::id!(theme_picker).as_str(), 1).await?;
2738 d.wait_idle().await?;
2739 d.check(
2740 store.get("day.appearance").as_deref() == Some("dark"),
2741 "dark not saved",
2742 )?;
2743 d.select(day_core::id!(theme_picker).as_str(), 2).await?;
2744 d.wait_idle().await?;
2745 d.check(
2746 store.get("day.appearance").is_none(),
2747 "System (the default) did not clear the key",
2748 )
2749 }
2750 })
2751 }
2752
2753 #[day_macros::test(day_core)]
2755 fn settings_rows_persist() -> Case {
2756 let store = Rc::new(MemoryStore::default());
2757 let page_store = store.clone();
2758 Case::new()
2759 .page(move || {
2760 install_store(SharedTestStore(page_store.clone()));
2761 let inst = Rc::new(Installed {
2762 in_nav: Cell::default(),
2763 about: None,
2764 groups: vec![
2765 Group::new("sound", "Sound")
2766 .row(rows::toggle(&SOUND, "Sounds"))
2767 .row(rows::slider(&SCALE, "Scale", 50.0..=200.0).step(10.0)),
2768 ],
2769 presentation: Presentation::Window,
2770 title: TextSource::Static("Settings".into()),
2771 selected: Signal::new(String::new()),
2772 path: Signal::new(Vec::new()),
2773 });
2774 let g = inst.groups[0].clone();
2775 column((group_page(inst, &g, true),))
2776 })
2777 .drive(move |d: Drive| {
2778 let store = store.clone();
2779 async move {
2780 d.toggle(day_core::id!(pref, "conformance.sound").as_str(), false)
2781 .await?;
2782 d.wait_idle().await?;
2783 d.check(!SOUND.get_untracked(), "toggle did not write the pref")?;
2784 d.check(
2785 store.get("conformance.sound").as_deref() == Some("false"),
2786 "toggle did not persist",
2787 )?;
2788 d.set_value(day_core::id!(pref, "conformance.scale").as_str(), 150.0)
2789 .await?;
2790 d.wait_idle().await?;
2791 d.check(
2792 (SCALE.get_untracked() - 150.0).abs() < 0.5,
2793 "slider did not write the pref",
2794 )?;
2795 SOUND.reset();
2796 d.check(
2797 store.get("conformance.sound").is_none(),
2798 "reset did not remove the key",
2799 )
2800 }
2801 })
2802 }
2803
2804 static COUNT: Pref<i64> = Pref::new("conformance.count", || 3);
2805
2806 #[day_macros::test(day_core)]
2809 fn settings_row_enabled_gates_stepper() -> Case {
2810 let gate = Signal::new(false);
2811 Case::new()
2812 .page(move || {
2813 let inst = Rc::new(Installed {
2814 in_nav: Cell::default(),
2815 about: None,
2816 groups: vec![
2817 Group::new("counts", "Counts")
2818 .row(rows::stepper(&COUNT, "Count", 0..=10).enabled(gate)),
2819 ],
2820 presentation: Presentation::Window,
2821 title: TextSource::Static("Settings".into()),
2822 selected: Signal::new(String::new()),
2823 path: Signal::new(Vec::new()),
2824 });
2825 let g = inst.groups[0].clone();
2826 column((
2827 group_page(inst, &g, true),
2828 button("Enable")
2829 .action(move || gate.set(true))
2830 .id(day_core::id!(settings::enable)),
2831 ))
2832 })
2833 .drive(|d: Drive| async move {
2834 let count = day_core::id!(pref, "conformance.count");
2835 let increment = day_core::id!(pref_increment, count.as_str());
2836 let decrement = day_core::id!(pref_decrement, count.as_str());
2837 d.assert_enabled(increment.as_str(), false).await?;
2838 d.assert_enabled(decrement.as_str(), false).await?;
2839 d.tap("settings::enable").await?;
2840 d.wait_idle().await?;
2841 d.assert_enabled(increment.as_str(), true).await?;
2842 d.assert_enabled(decrement.as_str(), true).await?;
2843 let initial = COUNT.get_untracked();
2844 d.assert_text(count.as_str(), &initial.to_string()).await?;
2845 d.tap(increment.as_str()).await?;
2846 d.assert_text(count.as_str(), &(initial + 1).to_string())
2847 .await?;
2848 d.tap(decrement.as_str()).await?;
2849 d.assert_text(count.as_str(), &initial.to_string()).await
2850 })
2851 }
2852}