use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use day_core::{AnyPiece, Piece};
use day_pieces::prelude::*;
use day_pieces::{Label, TextSource};
use day_reactive::{Signal, watch};
use day_spec::{Cap, Support};
day_pieces::glue_modules!(appkit, gtk, qt, uikit, material, arkui);
#[cfg(all(feature = "xaml", target_os = "windows"))]
#[path = "lib-xaml.rs"]
mod xaml_impl;
pub type LocaleTable = &'static [(&'static str, &'static str)];
pub mod prelude {
pub use crate::{
APPEARANCE, About, Appearance, Group, LANGUAGE, Pref, PrefValue, Preferences, Prefs,
Presentation, Providers, Row, Section, appearance_row, general_group, language_row,
pref_enum, rows,
};
}
pub use day_part_preferences::{
MemoryStore, NativeStore, Pref, PrefValue, Store, install_store, persistence_failures,
pref_enum,
};
day_core::tls_group! {
static INSTALLED: RefCell<Option<Rc<Installed>>> = const { RefCell::new(None) };
static RUNTIME_PROVIDERS: RefCell<Vec<&'static Provider>> = const { RefCell::new(Vec::new()) };
static GENERAL_WIRED: Cell<bool> = const { Cell::new(false) };
static SYSTEM_LOCALE: std::cell::OnceCell<String> = const { std::cell::OnceCell::new() };
static SUBPAGES: RefCell<HashMap<String, Build>> = RefCell::new(HashMap::new());
}
#[derive(Clone, Debug, PartialEq)]
pub enum GroupIcon {
Image(day_spec::ImageName),
Symbol(day_spec::Symbol),
}
impl From<day_spec::Symbol> for GroupIcon {
fn from(s: day_spec::Symbol) -> Self {
GroupIcon::Symbol(s)
}
}
impl From<day_spec::ImageName> for GroupIcon {
fn from(n: day_spec::ImageName) -> Self {
GroupIcon::Image(n)
}
}
impl From<day_spec::VectorName> for GroupIcon {
fn from(n: day_spec::VectorName) -> Self {
GroupIcon::Image(n.into())
}
}
type Build = Rc<dyn Fn() -> AnyPiece>;
type Avail = Rc<dyn Fn() -> bool>;
#[derive(Clone)]
#[must_use]
pub struct Group {
id: &'static str,
title: TextSource,
subtitle: Option<TextSource>,
icon: Option<GroupIcon>,
sections: Vec<Section>,
custom: Option<Build>,
order: i32,
available: Option<Avail>,
}
impl Group {
pub fn new<M>(id: &'static str, title: impl IntoText<M>) -> Self {
Group {
id,
title: title.into_text(),
subtitle: None,
icon: None,
sections: Vec::new(),
custom: None,
order: 0,
available: None,
}
}
pub fn icon(mut self, icon: impl Into<GroupIcon>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn subtitle<M>(mut self, t: impl IntoText<M>) -> Self {
self.subtitle = Some(t.into_text());
self
}
pub fn section(mut self, section: Section) -> Self {
self.sections.push(section);
self
}
pub fn row(mut self, row: Row) -> Self {
match self.sections.last_mut() {
Some(s) if s.title.is_none() && s.footer.is_none() => s.rows.push(row),
_ => self.sections.push(Section::new().row(row)),
}
self
}
pub fn custom<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
self.custom = Some(Rc::new(move || AnyPiece::new(build())));
self
}
pub fn order(mut self, order: i32) -> Self {
self.order = order;
self
}
pub fn available(mut self, f: impl Fn() -> bool + 'static) -> Self {
self.available = Some(Rc::new(f));
self
}
pub fn requires(self, cap: Cap) -> Self {
self.available(move || day_core::capability(cap) != Support::Unsupported)
}
#[must_use]
pub fn id(&self) -> &'static str {
self.id
}
fn is_available(&self) -> bool {
self.available.as_ref().is_none_or(|f| f())
}
}
#[derive(Clone, Default)]
#[must_use]
pub struct Section {
title: Option<TextSource>,
footer: Option<TextSource>,
rows: Vec<Row>,
}
impl Section {
pub fn new() -> Self {
Section::default()
}
pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
self.title = Some(t.into_text());
self
}
pub fn footer<M>(mut self, t: impl IntoText<M>) -> Self {
self.footer = Some(t.into_text());
self
}
pub fn row(mut self, row: Row) -> Self {
self.rows.push(row);
self
}
pub fn rows(mut self, rows: impl IntoIterator<Item = Row>) -> Self {
self.rows.extend(rows);
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ChoiceStyle {
#[default]
Menu,
Segmented,
}
#[derive(Clone)]
enum RowKind {
Toggle(Signal<bool>),
Choice {
labels: Vec<TextSource>,
index: Signal<usize>,
style: ChoiceStyle,
},
Slider {
value: Signal<f64>,
range: std::ops::RangeInclusive<f64>,
step: Option<f64>,
value_text: Option<Rc<dyn Fn(f64) -> String>>,
},
Stepper {
value: Signal<f64>,
range: std::ops::RangeInclusive<f64>,
step: f64,
},
Text {
value: Signal<String>,
placeholder: Option<TextSource>,
secure: bool,
},
Action {
on: Rc<dyn Fn()>,
destructive: bool,
confirm: Option<TextSource>,
confirm_label: Option<TextSource>,
busy: Option<Reactive<bool>>,
},
Link(String),
Navigate(Build),
Info {
value: TextSource,
copyable: bool,
},
Note,
Custom(Build),
}
#[derive(Clone)]
#[must_use]
pub struct Row {
title: TextSource,
caption: Option<TextSource>,
id: Option<day_core::ElementId>,
enabled: Option<Reactive<bool>>,
available: Option<Avail>,
kind: RowKind,
}
impl Row {
fn new<M>(title: impl IntoText<M>, kind: RowKind) -> Self {
Row {
title: title.into_text(),
caption: None,
id: None,
enabled: None,
available: None,
kind,
}
}
pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
self.title = t.into_text();
self
}
pub fn caption<M>(mut self, t: impl IntoText<M>) -> Self {
self.caption = Some(t.into_text());
self
}
pub fn id(mut self, id: day_core::ElementId) -> Self {
self.id = Some(id);
self
}
pub fn enabled<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
self.enabled = Some(enabled.into_reactive());
self
}
pub fn available(mut self, f: impl Fn() -> bool + 'static) -> Self {
self.available = Some(Rc::new(f));
self
}
pub fn requires(self, cap: Cap) -> Self {
self.available(move || day_core::capability(cap) != Support::Unsupported)
}
fn is_available(&self) -> bool {
self.available.as_ref().is_none_or(|f| f())
}
}
pub mod rows {
use super::*;
fn pref_id<T: PrefValue>(p: &Pref<T>) -> day_core::ElementId {
day_core::id!(pref, p.key())
}
pub fn toggle<M>(pref: &'static Pref<bool>, title: impl IntoText<M>) -> Row {
Row::new(title, RowKind::Toggle(pref.signal())).id(pref_id(pref))
}
pub fn choice<T: PrefValue, M, L, LM>(
pref: &'static Pref<T>,
title: impl IntoText<M>,
options: impl IntoIterator<Item = (T, L)>,
) -> Row
where
L: IntoText<LM>,
{
let (values, labels): (Vec<T>, Vec<TextSource>) =
options.into_iter().map(|(v, l)| (v, l.into_text())).unzip();
let sig = pref.signal();
let current = sig.get_untracked();
let index = Signal::global(values.iter().position(|v| *v == current).unwrap_or(0));
{
let values = values.clone();
watch(
move || index.get(),
move |ix, _| {
if let Some(v) = values.get(*ix) {
pref.set(v.clone());
}
},
);
}
watch(
move || sig.get(),
move |v, _| {
if let Some(ix) = values.iter().position(|x| x == v) {
index.set_if_changed(ix);
}
},
);
Row::new(
title,
RowKind::Choice {
labels,
index,
style: ChoiceStyle::Menu,
},
)
.id(pref_id(pref))
}
impl Row {
pub fn segmented(mut self) -> Self {
if let RowKind::Choice { style, .. } = &mut self.kind {
*style = ChoiceStyle::Segmented;
}
self
}
pub fn step(mut self, s: f64) -> Self {
match &mut self.kind {
RowKind::Slider { step, .. } => *step = Some(s),
RowKind::Stepper { step, .. } => *step = s,
_ => {}
}
self
}
pub fn value_text(mut self, f: impl Fn(f64) -> String + 'static) -> Self {
if let RowKind::Slider { value_text, .. } = &mut self.kind {
*value_text = Some(Rc::new(f));
}
self
}
pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
if let RowKind::Text { placeholder, .. } = &mut self.kind {
*placeholder = Some(t.into_text());
}
self
}
pub fn secure(mut self) -> Self {
if let RowKind::Text { secure, .. } = &mut self.kind {
*secure = true;
}
self
}
pub fn destructive(mut self) -> Self {
if let RowKind::Action { destructive, .. } = &mut self.kind {
*destructive = true;
}
self
}
pub fn confirm<M>(mut self, message: impl IntoText<M>) -> Self {
if let RowKind::Action { confirm, .. } = &mut self.kind {
*confirm = Some(message.into_text());
}
self
}
pub fn confirm_label<M>(mut self, label: impl IntoText<M>) -> Self {
if let RowKind::Action { confirm_label, .. } = &mut self.kind {
*confirm_label = Some(label.into_text());
}
self
}
pub fn busy<M>(mut self, busy: impl IntoReactive<bool, M>) -> Self {
if let RowKind::Action { busy: b, .. } = &mut self.kind {
*b = Some(busy.into_reactive());
}
self
}
pub fn copyable(mut self) -> Self {
if let RowKind::Info { copyable, .. } = &mut self.kind {
*copyable = true;
}
self
}
}
pub fn slider<M>(
pref: &'static Pref<f64>,
title: impl IntoText<M>,
range: std::ops::RangeInclusive<f64>,
) -> Row {
let sig = pref.signal();
Row::new(
title,
RowKind::Slider {
value: sig,
range,
step: None,
value_text: None,
},
)
.id(pref_id(pref))
}
pub fn stepper<M>(
pref: &'static Pref<i64>,
title: impl IntoText<M>,
range: std::ops::RangeInclusive<i64>,
) -> Row {
let sig = pref.signal();
let value = Signal::global(sig.get_untracked() as f64);
watch(move || value.get(), move |v, _| pref.set(v.round() as i64));
watch(
move || sig.get(),
move |v, _| value.set_if_changed(*v as f64),
);
Row::new(
title,
RowKind::Stepper {
value,
range: (*range.start() as f64)..=(*range.end() as f64),
step: 1.0,
},
)
.id(pref_id(pref))
}
pub fn text<M>(pref: &'static Pref<String>, title: impl IntoText<M>) -> Row {
let sig = pref.signal();
Row::new(
title,
RowKind::Text {
value: sig,
placeholder: None,
secure: false,
},
)
.id(pref_id(pref))
}
pub fn action<M>(title: impl IntoText<M>, on: impl Fn() + 'static) -> Row {
Row::new(
title,
RowKind::Action {
on: Rc::new(on),
destructive: false,
confirm: None,
confirm_label: None,
busy: None,
},
)
}
pub fn link<M>(title: impl IntoText<M>, url: impl Into<String>) -> Row {
Row::new(title, RowKind::Link(url.into()))
}
pub fn navigate<M, P: Piece>(title: impl IntoText<M>, build: impl Fn() -> P + 'static) -> Row {
Row::new(
title,
RowKind::Navigate(Rc::new(move || AnyPiece::new(build()))),
)
}
pub fn info<M, VM>(title: impl IntoText<M>, value: impl IntoText<VM>) -> Row {
Row::new(
title,
RowKind::Info {
value: value.into_text(),
copyable: false,
},
)
}
pub fn note<M>(text: impl IntoText<M>) -> Row {
Row::new(text, RowKind::Note)
}
pub fn custom<P: Piece>(build: impl Fn() -> P + 'static) -> Row {
Row::new("", RowKind::Custom(Rc::new(move || AnyPiece::new(build()))))
}
}
#[derive(Clone, Default)]
#[must_use]
pub struct About {
name: Option<TextSource>,
version: Option<String>,
build: Option<String>,
tagline: Option<TextSource>,
copyright: Option<TextSource>,
icon: Option<day_spec::ImageName>,
links: Vec<(TextSource, String)>,
privacy: Option<String>,
credits: Option<TextSource>,
licenses: Option<TextSource>,
custom: Option<Build>,
}
impl About {
pub fn from_manifest() -> Self {
About {
version: option_env!("DAY_SETTINGS_APP_VERSION").map(str::to_owned),
build: option_env!("DAY_SETTINGS_APP_BUILD").map(str::to_owned),
..Default::default()
}
}
pub fn name<M>(mut self, t: impl IntoText<M>) -> Self {
self.name = Some(t.into_text());
self
}
pub fn version(mut self, v: impl Into<String>) -> Self {
self.version = Some(v.into());
self
}
pub fn build(mut self, b: impl Into<String>) -> Self {
self.build = Some(b.into());
self
}
pub fn tagline<M>(mut self, t: impl IntoText<M>) -> Self {
self.tagline = Some(t.into_text());
self
}
pub fn copyright<M>(mut self, t: impl IntoText<M>) -> Self {
self.copyright = Some(t.into_text());
self
}
pub fn icon(mut self, icon: impl Into<day_spec::ImageName>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn link<M>(mut self, title: impl IntoText<M>, url: impl Into<String>) -> Self {
self.links.push((title.into_text(), url.into()));
self
}
pub fn website(self, url: impl Into<String>) -> Self {
self.link(day_localization_ui::res::str::day_about_website(), url)
}
pub fn source(self, url: impl Into<String>) -> Self {
self.link(day_localization_ui::res::str::day_about_source(), url)
}
pub fn privacy(mut self, url: impl Into<String>) -> Self {
self.privacy = Some(url.into());
self
}
pub fn credits<M>(mut self, t: impl IntoText<M>) -> Self {
self.credits = Some(t.into_text());
self
}
pub fn licenses<M>(mut self, t: impl IntoText<M>) -> Self {
self.licenses = Some(t.into_text());
self
}
pub fn custom<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
self.custom = Some(Rc::new(move || AnyPiece::new(build())));
self
}
pub fn display_name(&self) -> String {
match &self.name {
Some(n) => n.initial(),
None => option_env!("DAY_SETTINGS_APP_TITLE")
.map(str::to_owned)
.or_else(|| day_core::launch_options().map(|o| o.app_name.unwrap_or(o.title)))
.unwrap_or_default(),
}
}
#[must_use]
pub fn version_line(&self) -> Option<String> {
use std::fmt::Write as _;
let version = self
.version
.clone()
.or_else(|| day_core::launch_options().and_then(|o| o.version.clone()))?;
let mut line = day_localization_ui::res::str::day_about_version(version).format();
if let Some(build) = &self.build
&& !build.is_empty()
{
let _ = write!(line, " ({build})");
}
Some(line)
}
#[must_use]
pub fn version_value(&self) -> Option<&str> {
self.version.as_deref()
}
#[must_use]
pub fn build_value(&self) -> Option<&str> {
self.build.as_deref()
}
#[must_use]
pub fn links(&self) -> &[(TextSource, String)] {
&self.links
}
#[must_use]
pub fn privacy_url(&self) -> Option<&str> {
self.privacy.as_deref()
}
#[must_use]
pub fn icon_name(&self) -> Option<&day_spec::ImageName> {
self.icon.as_ref()
}
pub fn tagline_text(&self) -> Option<String> {
self.tagline.as_ref().map(TextSource::initial)
}
pub fn copyright_text(&self) -> Option<String> {
self.copyright.as_ref().map(TextSource::initial)
}
pub fn credits_text(&self) -> Option<String> {
self.credits.as_ref().map(TextSource::initial)
}
pub fn licenses_text(&self) -> Option<String> {
self.licenses.as_ref().map(TextSource::initial)
}
#[must_use]
pub fn custom_piece(&self) -> Option<AnyPiece> {
self.custom.as_ref().map(|b| b())
}
}
pub struct Provider {
pub id: &'static str,
pub order: i32,
pub available: fn() -> bool,
pub group: fn() -> Group,
pub startup: Option<fn()>,
}
#[cfg(not(target_arch = "wasm32"))]
#[linkme::distributed_slice]
pub static PROVIDERS: [&'static Provider];
#[macro_export]
macro_rules! provider {
($(#[$meta:meta])* $vis:vis static $name:ident : Provider = $init:expr ;) => {
$(#[$meta])*
$vis static $name: $crate::Provider = $init;
#[cfg(not(target_arch = "wasm32"))]
#[$crate::linkme::distributed_slice($crate::PROVIDERS)]
#[linkme(crate = $crate::linkme)]
static __DAY_SETTINGS_PROVIDER: &'static $crate::Provider = &$name;
};
}
#[doc(hidden)]
pub use linkme;
pub fn register_provider(p: &'static Provider) {
RUNTIME_PROVIDERS.with(|r| {
let mut r = r.borrow_mut();
if !r.iter().any(|q| std::ptr::eq(*q, p)) {
r.push(p);
}
});
}
fn all_providers() -> Vec<&'static Provider> {
let mut out: Vec<&'static Provider> = Vec::new();
#[cfg(not(target_arch = "wasm32"))]
out.extend(PROVIDERS.iter().copied());
RUNTIME_PROVIDERS.with(|r| {
for p in r.borrow().iter() {
if !out.iter().any(|q| std::ptr::eq(*q, *p)) {
out.push(p);
}
}
});
out
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Providers {
#[default]
Registered,
None,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presentation {
Window,
Navigation,
}
#[must_use]
pub struct Preferences {
about: Option<About>,
groups: Vec<Group>,
providers: Providers,
explicit: Vec<&'static Provider>,
excluded: Vec<&'static str>,
presentation: Option<Presentation>,
window_size: day_spec::Size,
title: Option<TextSource>,
}
impl Default for Preferences {
fn default() -> Self {
Self::new()
}
}
impl Preferences {
pub fn new() -> Self {
Preferences {
about: None,
groups: Vec::new(),
providers: Providers::Registered,
explicit: Vec::new(),
excluded: Vec::new(),
presentation: None,
window_size: day_spec::Size::new(560.0, 640.0),
title: None,
}
}
pub fn about(mut self, about: About) -> Self {
self.about = Some(about);
self
}
pub fn group(mut self, group: Group) -> Self {
self.groups.push(group);
self
}
pub fn providers(mut self, policy: Providers) -> Self {
self.providers = policy;
self
}
pub fn provider(mut self, p: &'static Provider) -> Self {
self.explicit.push(p);
self
}
pub fn without_provider(mut self, id: &'static str) -> Self {
self.excluded.push(id);
self
}
pub fn presentation(mut self, p: Presentation) -> Self {
self.presentation = Some(p);
self
}
pub fn window_size(mut self, width: f64, height: f64) -> Self {
self.window_size = day_spec::Size::new(width, height);
self
}
pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
self.title = Some(t.into_text());
self
}
pub fn install(self) -> Prefs {
let Preferences {
about,
mut groups,
providers,
explicit,
excluded,
presentation,
window_size,
title,
} = self;
let mut chosen: Vec<&'static Provider> = Vec::new();
if providers == Providers::Registered {
chosen.extend(all_providers());
}
for p in explicit {
if !chosen.iter().any(|q| std::ptr::eq(*q, p)) {
chosen.push(p);
}
}
chosen.retain(|p| !excluded.contains(&p.id) && (p.available)());
for p in &chosen {
if let Some(startup) = p.startup {
startup();
}
groups.push((p.group)().order(p.order));
}
groups.sort_by_key(|g| g.order);
let presentation = presentation.unwrap_or_else(default_presentation);
let title = title.unwrap_or_else(|| TextSource::Dyn(Rc::new(platform_word)));
let installed = Rc::new(Installed {
in_nav: Cell::default(),
about,
groups,
presentation,
title,
selected: Signal::global(String::new()),
path: Signal::global(Vec::new()),
});
INSTALLED.with(|i| *i.borrow_mut() = Some(installed.clone()));
match presentation {
Presentation::Window => {
let inst = installed.clone();
day_core::register_preferences_with(
day_spec::WindowOptions {
title: installed.title.initial(),
size: window_size,
size_to_fit: true,
..day_spec::WindowOptions::default()
},
move || window_shell(inst.clone()),
);
}
Presentation::Navigation
if day_core::capability(Cap::AppMenu) != Support::Unsupported =>
{
let inst = installed.clone();
day_core::register_preferences_with(
day_spec::WindowOptions {
title: installed.title.initial(),
..day_spec::WindowOptions::default()
},
move || navigation_shell_with_done(inst.clone()),
);
}
Presentation::Navigation => {}
}
if installed.about.is_some() {
install_about(installed.clone());
}
register_route_controller(installed.clone());
Prefs(installed)
}
}
struct Installed {
about: Option<About>,
groups: Vec<Group>,
presentation: Presentation,
title: TextSource,
selected: Signal<String>,
path: Signal<Vec<SettingsRoute>>,
in_nav: std::cell::Cell<bool>,
}
impl Installed {
fn visible_groups(&self) -> Vec<&Group> {
self.groups.iter().filter(|g| g.is_available()).collect()
}
fn group(&self, id: &str) -> Option<&Group> {
self.groups.iter().find(|g| g.id == id && g.is_available())
}
}
fn platform_word() -> String {
let gnome_or_kde = matches!(day_core::toolkit_key(), Some("gtk" | "qt"));
if gnome_or_kde {
day_localization::t(day_localization::key::day_preferences)
} else {
day_localization::t(day_localization::key::day_settings)
}
}
fn default_presentation() -> Presentation {
let windows = day_core::capability(Cap::MultiWindow) != Support::Unsupported;
let menu = day_core::capability(Cap::AppMenu) != Support::Unsupported;
if windows && menu {
Presentation::Window
} else {
Presentation::Navigation
}
}
#[derive(Clone)]
pub struct Prefs(Rc<Installed>);
impl Prefs {
pub fn open(&self) -> bool {
open()
}
pub fn open_at(&self, route: &str) -> bool {
open_at(route)
}
#[must_use]
pub fn in_nav(&self) -> bool {
self.0.presentation == Presentation::Navigation
&& day_core::capability(Cap::AppMenu) == Support::Unsupported
}
pub fn nav_item<K>(&self, key: impl Into<K>) -> Option<NavItem<K>> {
self.in_nav().then(|| self.nav_item_everywhere(key))
}
pub fn nav_item_everywhere<K>(&self, key: impl Into<K>) -> NavItem<K> {
self.0.in_nav.set(true);
let title = self.0.title.clone();
let inst = self.0.clone();
item(key, move || title.initial()).page(move || navigation_shell(inst.clone()))
}
pub fn page(&self) -> AnyPiece {
self.0.in_nav.set(true);
navigation_shell(self.0.clone())
}
pub fn group_page(&self, id: &str) -> AnyPiece {
match self.0.group(id) {
Some(g) => group_page(self.0.clone(), g, false),
None => column(()).any(),
}
}
pub fn group_body(&self, id: &str) -> AnyPiece {
match self.0.group(id) {
Some(g) => group_body(self.0.clone(), g),
None => column(()).any(),
}
}
pub fn about_page(&self) -> AnyPiece {
about_page(self.0.clone())
}
#[must_use]
pub fn title(&self) -> String {
self.0.title.initial()
}
}
fn installed() -> Option<Rc<Installed>> {
INSTALLED.with(|i| i.borrow().clone())
}
pub fn open() -> bool {
let Some(inst) = installed() else {
log::warn!("day-piece-settings: open() before Preferences::install()");
return false;
};
match inst.presentation {
Presentation::Window => day_core::open_preferences(),
Presentation::Navigation => day_core::navigate(NAV_KEY) || open_cover(inst),
}
}
fn open_cover(inst: Rc<Installed>) -> bool {
if day_core::window_by_key(day_core::windows::PREFERENCES_KEY).is_none() {
inst.path.set(Vec::new());
}
day_core::open_window(
day_spec::WindowOptions::default()
.title(inst.title.initial())
.key(day_core::windows::PREFERENCES_KEY)
.kind(day_spec::WindowKind::Preferences),
move || navigation_shell_with_done(inst.clone()),
);
true
}
pub const NAV_KEY: &str = "settings";
pub fn page() -> AnyPiece {
match installed() {
Some(inst) => {
inst.in_nav.set(true);
navigation_shell(inst)
}
None => column(()).any(),
}
}
pub fn group_page_of(id: &str) -> AnyPiece {
match installed() {
Some(inst) => Prefs(inst).group_page(id),
None => column(()).any(),
}
}
pub fn open_at(route: &str) -> bool {
let Some(inst) = installed() else {
return false;
};
let (group, _row) = route.split_once('/').unwrap_or((route, ""));
if group == "about" {
return day_core::open_about();
}
if inst.group(group).is_none() {
return false;
}
match inst.presentation {
Presentation::Window => {
inst.selected.set_if_changed(group.to_string());
day_core::open_preferences()
}
Presentation::Navigation => {
let inside = day_core::current_route()
.is_some_and(|r| r == NAV_KEY || r.starts_with(&format!("{NAV_KEY}/")));
let ok = inside || open();
inst.path.set(vec![SettingsRoute::Group(group.to_string())]);
ok
}
}
}
fn register_route_controller(inst: Rc<Installed>) {
let menu = day_core::capability(Cap::AppMenu) != Support::Unsupported;
if inst.presentation != Presentation::Window && !menu {
register_cover_route_controller(inst);
return;
}
let open_surface = day_core::open_preferences;
let root = inst.clone();
let open_root = open_surface;
let _root_token = day_core::register_nav(day_core::NavController {
push: Box::new(move |route| {
if route == NAV_KEY {
open_root()
} else if route == "about" {
day_core::open_about()
} else if root.group(route).is_some() {
open_at(route)
} else {
false
}
}),
pop: Box::new(|_| false),
current: Box::new(String::new),
enter: Box::new(move |segment| segment == NAV_KEY && open_surface()),
segments: Box::new(Vec::new),
depth: 0,
layer: Box::new(|| 0),
active: Box::new(|| true),
});
let group = inst;
let _group_token = day_core::register_nav(day_core::NavController {
push: Box::new(|_| false),
pop: Box::new(|_| false),
current: Box::new(String::new),
enter: Box::new(move |segment| group.group(segment).is_some() && open_at(segment)),
segments: Box::new(Vec::new),
depth: 0,
layer: Box::new(|| 0),
active: Box::new(|| true),
});
}
fn register_cover_route_controller(inst: Rc<Installed>) {
let root = inst.clone();
let active = inst.clone();
let enter = inst;
let _token = day_core::register_nav_fallback(day_core::NavController {
push: Box::new(move |route| {
if route == NAV_KEY {
open_cover(root.clone())
} else if route == "about" {
day_core::open_about()
} else if root.group(route).is_some() {
open_cover(root.clone());
root.path.set(vec![SettingsRoute::Group(route.to_string())]);
true
} else {
false
}
}),
pop: Box::new(|_| false),
current: Box::new(String::new),
enter: Box::new(move |segment| {
if enter.group(segment).is_none() {
return false;
}
enter
.path
.set(vec![SettingsRoute::Group(segment.to_string())]);
true
}),
segments: Box::new(Vec::new),
depth: 0,
layer: Box::new(|| 0),
active: Box::new(move || !active.in_nav.get()),
});
}
fn install_about(inst: Rc<Installed>) {
#[cfg(feature = "gtk")]
{
if gtk_impl::install_about(inst.clone()) {
return;
}
}
let name = inst.about.as_ref().map_or_default(About::display_name);
let title = day_localization_ui::res::str::day_about_app(name);
let cover = day_core::capability(day_spec::Cap::MultiWindow) == day_spec::Support::Unsupported;
day_core::register_about_window(
day_spec::WindowOptions {
title: title.format(),
size: day_spec::Size::new(320.0, 480.0),
size_to_fit: true,
..day_spec::WindowOptions::default()
},
move || {
if cover {
let title = title.clone();
nav_stack(
Signal::new(Vec::<SettingsRoute>::new()),
about_page(inst.clone()),
)
.title(move || title.format())
.toolbar(
toolbar_button(
day_core::id!(about_done),
day_localization_ui::res::str::day_settings_done(),
)
.action(|| {
if let Some(w) = day_core::window_by_key(day_core::windows::ABOUT_KEY) {
w.close();
}
}),
)
.any()
} else {
about_page(inst.clone())
}
},
);
}
pref_enum! {
pub enum Appearance { Light = "light", Dark = "dark", System = "system" }
}
pub static APPEARANCE: Pref<Appearance> =
Pref::new("day.appearance", || Appearance::System).env("DAY_THEME");
pub static LANGUAGE: Pref<String> = Pref::new("day.locale", String::new).env("DAY_LOCALE");
fn system_locale() -> String {
SYSTEM_LOCALE
.with(|c| c.get().cloned())
.unwrap_or_else(|| day_localization_ui::locale().get_untracked())
}
fn apply_appearance(a: Appearance) {
if day_core::capability(Cap::Appearance) == Support::Unsupported {
return;
}
day_core::set_appearance(match a {
Appearance::Light => Some(false),
Appearance::Dark => Some(true),
Appearance::System => None,
});
}
fn apply_language(tag: &str) {
if tag.is_empty() {
day_localization_ui::set_locale(&system_locale());
} else {
day_localization_ui::set_locale(tag);
}
}
pub fn wire_general() {
if GENERAL_WIRED.with(|w| w.replace(true)) {
return;
}
SYSTEM_LOCALE.with(|c| {
let _ = c.set(day_localization_ui::locale().get_untracked());
});
if !APPEARANCE.env_forced() {
apply_appearance(APPEARANCE.get_untracked());
}
if !LANGUAGE.env_forced() {
let tag = LANGUAGE.get_untracked();
if !tag.is_empty() {
apply_language(&tag);
}
}
let root = day_reactive::Scope::root();
root.enter(|| {
APPEARANCE.watch(|a| apply_appearance(*a));
LANGUAGE.watch(|tag| apply_language(tag));
});
}
pub fn general_group(locales: LocaleTable) -> Group {
wire_general();
Group::new(
"general",
day_localization_ui::res::str::day_settings_general(),
)
.icon(day_spec::Symbol::Settings)
.row(appearance_row())
.row(language_row(locales))
}
pub fn appearance_row() -> Row {
wire_general();
rows::choice(
&APPEARANCE,
day_localization_ui::res::str::day_settings_theme(),
[
(
Appearance::Light,
day_localization_ui::res::str::day_theme_light(),
),
(
Appearance::Dark,
day_localization_ui::res::str::day_theme_dark(),
),
(
Appearance::System,
day_localization_ui::res::str::day_theme_system(),
),
],
)
.segmented()
.id(day_core::id!(theme_picker))
.requires(Cap::Appearance)
}
pub fn language_row(locales: LocaleTable) -> Row {
wire_general();
let mut options: Vec<(String, TextSource)> = vec![(
String::new(),
day_localization_ui::res::str::day_theme_system().into_text(),
)];
options.extend(
locales
.iter()
.map(|(tag, name)| ((*tag).to_string(), TextSource::Static((*name).to_string()))),
);
choice_text(
&LANGUAGE,
day_localization_ui::res::str::day_settings_language(),
options,
)
.id(day_core::id!(language_picker))
}
fn choice_text<T: PrefValue, M>(
pref: &'static Pref<T>,
title: impl IntoText<M>,
options: Vec<(T, TextSource)>,
) -> Row {
rows::choice(
pref,
title,
options.into_iter().map(|(v, l)| (v, Resolved(l))),
)
}
struct Resolved(TextSource);
struct ResolvedMark;
impl IntoText<ResolvedMark> for Resolved {
fn into_text(self) -> TextSource {
self.0
}
}
#[derive(Clone, PartialEq, Debug)]
pub enum SettingsRoute {
About,
Group(String),
}
impl Route for SettingsRoute {
fn key(&self) -> String {
match self {
SettingsRoute::About => "about".into(),
SettingsRoute::Group(g) => g.clone(),
}
}
fn from_key(key: &str) -> Option<Self> {
Some(match key {
"about" => SettingsRoute::About,
g => SettingsRoute::Group(g.to_string()),
})
}
fn title(&self) -> String {
match self {
SettingsRoute::About => day_localization::t(day_localization::key::day_about),
SettingsRoute::Group(g) => match g.strip_prefix("page:") {
Some(title) => title.to_string(),
None => installed()
.and_then(|i| i.group(g).map(|g| resolve_text(&g.title)))
.unwrap_or_else(|| g.clone()),
},
}
}
}
fn text_label(t: &TextSource) -> Label {
match t {
TextSource::Static(s) => label(s.clone()),
TextSource::Dyn(f) => {
let f = f.clone();
label(move || f())
}
}
}
fn text_source_fn(t: &TextSource) -> impl Fn() -> String + 'static {
let t = t.clone();
move || resolve_text(&t)
}
pub(crate) fn resolve_text(t: &TextSource) -> String {
match t {
TextSource::Static(s) => s.clone(),
TextSource::Dyn(f) => f(),
}
}
pub(crate) fn choice_picker(
labels: &[TextSource],
index: Signal<usize>,
segmented: bool,
enabled: impl Fn() -> bool + 'static,
) -> day_pieces::Picker<usize, day_pieces::Required<Signal<usize>>> {
let options: Vec<(usize, TextSource)> = labels.iter().cloned().enumerate().collect();
let mut p = picker(index, options).enabled(enabled);
if segmented {
p = p.segmented();
}
p
}
pub(crate) fn stepper_buttons(
v: Signal<f64>,
range: &std::ops::RangeInclusive<f64>,
step: f64,
enabled: impl Fn() -> bool + Clone + 'static,
) -> (day_pieces::Button, day_pieces::Button) {
let (lo, hi, st) = (*range.start(), *range.end(), step);
let enabled_inc = enabled.clone();
let dec = button("−")
.action(move || v.set((v.get_untracked() - st).max(lo)))
.enabled(move || enabled() && v.get() > lo);
let inc = button("+")
.action(move || v.set((v.get_untracked() + st).min(hi)))
.enabled(move || enabled_inc() && v.get() < hi);
(dec, inc)
}
pub(crate) fn stepper_control(
value: Signal<f64>,
dec: day_pieces::Button,
inc: day_pieces::Button,
id: Option<&day_core::ElementId>,
) -> AnyPiece {
let value_label = label(move || format!("{}", value.get() as i64)).tabular();
match id {
Some(id) => row((
dec.id(day_core::id!(pref_decrement, id.as_str())),
value_label.id(id.clone()),
inc.id(day_core::id!(pref_increment, id.as_str())),
))
.spacing(8.0)
.align(VAlign::Center)
.any(),
None => row((dec, value_label, inc))
.spacing(8.0)
.align(VAlign::Center)
.any(),
}
}
fn window_shell(inst: Rc<Installed>) -> AnyPiece {
#[cfg(all(feature = "appkit", target_os = "macos"))]
{
if let Some(p) = appkit_impl::window_shell(inst.clone()) {
return p;
}
}
#[cfg(feature = "gtk")]
{
if let Some(p) = gtk_impl::window_shell(inst.clone()) {
return p;
}
}
#[cfg(feature = "qt")]
{
if let Some(p) = qt_impl::window_shell(inst.clone()) {
return p;
}
}
composed_window_shell(inst)
}
#[expect(
clippy::needless_pass_by_value,
reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn composed_window_shell(inst: Rc<Installed>) -> AnyPiece {
let groups = inst.visible_groups();
if groups.len() <= 1 {
return match groups.first() {
Some(g) => group_page(inst.clone(), g, true),
None => column(()).any(),
};
}
if inst.selected.get_untracked().is_empty() {
inst.selected.set(groups[0].id.to_string());
}
let mut nav = nav(inst.selected)
.style(NavStyle::Sidebar)
.local()
.id(day_core::id!(prefs_nav));
for g in groups {
let id = g.id;
let title = text_source_fn(&g.title);
let inst2 = inst.clone();
let build = move || {
let inst = inst2.clone();
match inst.group(id) {
Some(g) => group_page(inst.clone(), g, true),
None => column(()).any(),
}
};
nav = match &g.icon {
Some(GroupIcon::Image(name)) => {
nav.items(item(id, title).icon(name.clone()).page(build))
}
_ => nav.item(id, title, build),
};
}
let nav = nav.any();
#[cfg(all(feature = "xaml", target_os = "windows"))]
let nav = xaml_impl::sidebar_symbols(nav, &inst.visible_groups());
nav
}
fn group_page(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
if !desktop {
#[cfg(all(feature = "uikit", target_os = "ios"))]
{
if let Some(p) = uikit_impl::group_page(inst.clone(), g) {
return p;
}
}
#[cfg(all(feature = "material", target_os = "android"))]
{
if let Some(p) = android_impl::group_page(inst.clone(), g) {
return p;
}
}
#[cfg(all(feature = "arkui", target_env = "ohos"))]
{
if let Some(p) = arkui_impl::group_page(inst.clone(), g) {
return p;
}
}
}
composed_group_page(inst, g, desktop)
}
fn group_body(inst: Rc<Installed>, g: &Group) -> AnyPiece {
#[cfg(all(feature = "uikit", target_os = "ios"))]
{
if let Some(p) = uikit_impl::group_body(inst.clone(), g) {
return p;
}
}
#[cfg(all(feature = "material", target_os = "android"))]
{
if let Some(p) = android_impl::group_body(inst.clone(), g) {
return p;
}
}
#[cfg(all(feature = "arkui", target_env = "ohos"))]
{
if let Some(p) = arkui_impl::group_body(inst.clone(), g) {
return p;
}
}
column((composed_group_form(inst, g, false),))
.align(HAlign::Leading)
.padding(16.0)
.grow(Dimension::Width)
.any()
}
#[expect(
clippy::needless_pass_by_value,
reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn composed_group_form(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
let mut parts: Vec<AnyPiece> = Vec::new();
for s in &g.sections {
if let Some(p) = section_piece(inst.clone(), s, desktop) {
parts.push(p);
}
}
if let Some(custom) = &g.custom {
parts.push(custom());
}
form(parts).id(day_core::id!(prefs_group, g.id)).any()
}
fn composed_group_page(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
let body = composed_group_form(inst, g, desktop);
if desktop {
hugging_scroll(
column((body,))
.align(HAlign::Leading)
.padding(20.0)
.grow(Dimension::Width),
)
.any()
} else {
scroll(
column((body,))
.align(HAlign::Leading)
.padding(16.0)
.grow(Dimension::Width),
)
.any()
}
}
#[expect(
clippy::needless_pass_by_value,
reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn section_piece(inst: Rc<Installed>, s: &Section, desktop: bool) -> Option<AnyPiece> {
let rows: Vec<AnyPiece> = s
.rows
.iter()
.filter(|r| r.is_available())
.map(|r| row_piece(inst.clone(), r, desktop))
.collect();
if rows.is_empty() {
return None;
}
let mut sec = section(rows);
if let Some(t) = &s.title {
sec = sec.title(text_source_fn(t));
}
if let Some(f) = &s.footer {
sec = sec.footer(text_source_fn(f));
}
Some(sec.any())
}
fn row_piece(inst: Rc<Installed>, r: &Row, desktop: bool) -> AnyPiece {
#[cfg(feature = "gtk")]
{
if let Some(p) = gtk_impl::row_piece(inst.clone(), r, desktop) {
return p;
}
}
#[cfg(all(feature = "uikit", target_os = "ios"))]
{
if let Some(p) = uikit_impl::row_piece(inst.clone(), r, desktop) {
return p;
}
}
#[cfg(all(feature = "material", target_os = "android"))]
{
if let Some(p) = android_impl::row_piece(inst.clone(), r, desktop) {
return p;
}
}
#[cfg(all(feature = "xaml", target_os = "windows"))]
{
if let Some(p) = xaml_impl::row_piece(inst.clone(), r, desktop) {
return p;
}
}
#[cfg(all(feature = "arkui", target_env = "ohos"))]
{
if let Some(p) = arkui_impl::row_piece(inst.clone(), r, desktop) {
return p;
}
}
composed_row(inst, r, desktop)
}
fn title_column(r: &Row) -> AnyPiece {
let title = text_label(&r.title);
match &r.caption {
Some(c) => column((
title,
text_label(c).font(day_spec::Font::Footnote).secondary(),
))
.spacing(2.0)
.align(HAlign::Leading)
.any(),
None => title.any(),
}
}
fn trailing_row(titles: AnyPiece, control: AnyPiece) -> AnyPiece {
row((titles.max_width(TITLE_COLUMN_MAX), spacer(), control))
.spacing(12.0)
.align(VAlign::Center)
.grow(Dimension::Width)
.any()
}
const TITLE_COLUMN_MAX: f64 = 360.0;
const SLIDER_WIDTH: f64 = 200.0;
const VALUE_WIDTH: f64 = 52.0;
fn composed_row(inst: Rc<Installed>, r: &Row, _desktop: bool) -> AnyPiece {
let id = r.id.clone();
let enabled = r.enabled.clone();
let with_id = |p: AnyPiece| match &id {
Some(id) => p.id(id.clone()).any(),
None => p,
};
let enabled_fn = move || enabled.as_ref().is_none_or(day_pieces::Reactive::get);
match &r.kind {
RowKind::Toggle(sig) => {
let ctl = with_id(toggle(*sig).enabled(enabled_fn).any());
trailing_row(title_column(r), ctl)
}
RowKind::Choice {
labels,
index,
style,
} => {
let p = choice_picker(labels, *index, *style == ChoiceStyle::Segmented, enabled_fn);
trailing_row(title_column(r), with_id(p.any()))
}
RowKind::Slider {
value,
range,
step,
value_text,
} => {
let mut s = slider(*value).range(range.clone()).enabled(enabled_fn);
if let Some(st) = step {
s = s.step(*st);
}
let ctl = match &id {
Some(i) => s
.id(i.clone())
.min_width(SLIDER_WIDTH)
.max_width(SLIDER_WIDTH)
.any(),
None => s.min_width(SLIDER_WIDTH).max_width(SLIDER_WIDTH).any(),
};
let ctl = match value_text {
Some(f) => {
let f = f.clone();
let v = *value;
let value_label = label(move || f(v.get()))
.tabular()
.secondary()
.single_line()
.align(day_spec::props::TextAlign::Trailing);
let value_label = match &id {
Some(i) => value_label
.id(day_core::id!(pref_value, i.as_str()))
.min_width(VALUE_WIDTH)
.max_width(VALUE_WIDTH)
.any(),
None => value_label
.min_width(VALUE_WIDTH)
.max_width(VALUE_WIDTH)
.any(),
};
row((ctl, value_label))
.spacing(8.0)
.align(VAlign::Center)
.any()
}
None => ctl,
};
trailing_row(title_column(r), ctl)
}
RowKind::Stepper { value, range, step } => {
let v = *value;
let (dec, inc) = stepper_buttons(v, range, *step, enabled_fn);
let ctl = stepper_control(v, dec, inc, id.as_ref());
trailing_row(title_column(r), ctl)
}
RowKind::Text {
value,
placeholder,
secure,
} => {
let mut f = if *secure {
secure_field(*value)
} else {
text_field(*value)
};
if let Some(ph) = placeholder {
f = f.placeholder(text_source_fn(ph));
}
let f = f.enabled(enabled_fn);
let ctl = match &id {
Some(i) => f
.id(i.clone())
.grow(Dimension::Width)
.min_width(160.0)
.any(),
None => f.grow(Dimension::Width).min_width(160.0).any(),
};
trailing_row(title_column(r), ctl)
}
RowKind::Action {
on,
destructive: _,
confirm,
confirm_label,
busy,
} => {
let on = on.clone();
let title = text_source_fn(&r.title);
let confirm = confirm.clone();
let confirm_label = confirm_label.clone();
let busy = busy.clone();
let run = move || {
let on = on.clone();
match &confirm {
Some(message) => {
let message = message.initial();
let title = title();
let label = confirm_label.as_ref().map(TextSource::initial);
day_core::task(async move {
if crate::confirm_dialog(&title, &message, label).await {
on();
}
});
}
None => on(),
}
};
let busy_gate = busy.clone();
let b = button(text_source_fn(&r.title))
.action(run)
.enabled(move || {
enabled_fn() && !busy_gate.as_ref().is_some_and(day_pieces::Reactive::get)
});
let ctl = with_id(b.any());
let ctl = match busy {
Some(b) => row((when(move || b.get(), spinner), ctl))
.spacing(8.0)
.align(VAlign::Center)
.any(),
None => ctl,
};
match &r.caption {
Some(c) => trailing_row(caption_only(c), ctl),
None => ctl,
}
}
RowKind::Link(url) => {
let url = url.clone();
let l = link(text_source_fn(&r.title), url);
match &r.caption {
Some(c) => trailing_row(caption_only(c), with_id(l.any())),
None => with_id(l.any()),
}
}
RowKind::Navigate(build) => {
let build = build.clone();
let title = text_source_fn(&r.title);
let open = move || {
let build = build.clone();
let title = title();
push_subpage(inst.clone(), title, build);
};
with_id(
row((title_column(r), spacer(), label("›").secondary()))
.spacing(12.0)
.align(VAlign::Center)
.grow(Dimension::Width)
.on_tap(open)
.any(),
)
}
RowKind::Info { value, copyable } => {
let v = text_label(value).secondary();
let v = if *copyable {
let text = value.clone();
row((
v,
button("")
.icon(day_spec::Symbol::Copy)
.icon_only()
.plain()
.action(move || {
let _ = day_part_clipboard::set_text(&text.initial());
}),
))
.spacing(4.0)
.align(VAlign::Center)
.any()
} else {
v.any()
};
trailing_row(title_column(r), with_id(v))
}
RowKind::Note => with_id(
text_label(&r.title)
.font(day_spec::Font::Footnote)
.secondary()
.any(),
),
RowKind::Custom(build) => with_id(build()),
}
}
#[expect(
clippy::needless_pass_by_value,
reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn push_subpage(inst: Rc<Installed>, title: String, build: Build) {
SUBPAGES.with(|s| s.borrow_mut().insert(title.clone(), build.clone()));
#[cfg(feature = "gtk")]
{
if gtk_impl::push_subpage(inst.clone(), title.clone(), build.clone()) {
return;
}
}
if inst.presentation == Presentation::Navigation {
inst.path
.update(|p| p.push(SettingsRoute::Group(format!("page:{title}"))));
} else {
day_core::open_window(
day_spec::WindowOptions::default()
.key(format!("day.settings.{title}"))
.title(title)
.size(480.0, 560.0)
.size_to_fit()
.kind(day_spec::WindowKind::Preferences),
move || build(),
);
}
}
async fn confirm_dialog(title: &str, message: &str, label: Option<String>) -> bool {
let dialog = confirm(title.to_string())
.message(message.to_string())
.destructive();
match label {
Some(l) => dialog.confirm_label(l).await,
None => dialog.await,
}
}
fn caption_only(c: &TextSource) -> AnyPiece {
text_label(c)
.font(day_spec::Font::Footnote)
.secondary()
.any()
}
fn navigation_shell(inst: Rc<Installed>) -> AnyPiece {
navigation_stack(inst, false)
}
fn navigation_shell_with_done(inst: Rc<Installed>) -> AnyPiece {
navigation_stack(inst, true)
}
#[expect(
clippy::needless_pass_by_value,
reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn navigation_stack(inst: Rc<Installed>, done: bool) -> AnyPiece {
let root_inst = inst.clone();
let dest_inst = inst.clone();
let mut stack = nav_stack(inst.path, root_page(root_inst))
.title(text_source_fn(&inst.title))
.destination(move |r: &SettingsRoute| destination(dest_inst.clone(), r));
if done {
stack = stack.toolbar(
toolbar_button(
day_core::id!(settings_done),
day_localization_ui::res::str::day_settings_done(),
)
.action(|| {
if let Some(w) = day_core::window_by_key(day_core::windows::PREFERENCES_KEY) {
w.close();
}
})
.placement(day_spec::ToolbarPlacement::Primary),
);
}
stack.id(day_core::id!(settings_stack)).any()
}
fn destination(inst: Rc<Installed>, r: &SettingsRoute) -> AnyPiece {
match r {
SettingsRoute::About => about_page(inst),
SettingsRoute::Group(g) => {
if let Some(title) = g.strip_prefix("page:") {
return SUBPAGES
.with(|s| s.borrow().get(title).cloned())
.map_or_else(|| column(()).any(), |b| b());
}
match inst.group(g) {
Some(group) => group_page(inst.clone(), group, false),
None => column(()).any(),
}
}
}
}
#[allow(dead_code)]
pub(crate) struct RootEntry {
pub id: String,
pub title: TextSource,
pub subtitle: Option<TextSource>,
pub icon: Option<GroupIcon>,
pub open: Rc<dyn Fn()>,
}
#[allow(dead_code)]
pub(crate) fn root_entries(inst: &Rc<Installed>) -> (Option<RootEntry>, Vec<RootEntry>) {
let path = inst.path;
let about = inst.about.as_ref().map(|about| RootEntry {
id: "about".into(),
title: TextSource::Static(about.display_name()),
subtitle: about.version_line().map(TextSource::Static),
icon: about.icon_name().cloned().map(GroupIcon::Image),
open: Rc::new(move || path.update(|p| p.push(SettingsRoute::About))),
});
let groups = inst
.visible_groups()
.into_iter()
.map(|g| {
let id = g.id;
RootEntry {
id: id.to_string(),
title: g.title.clone(),
subtitle: g.subtitle.clone(),
icon: g.icon.clone(),
open: Rc::new(move || {
path.update(|p| p.push(SettingsRoute::Group(id.to_string())));
}),
}
})
.collect();
(about, groups)
}
fn root_page(inst: Rc<Installed>) -> AnyPiece {
#[cfg(all(feature = "uikit", target_os = "ios"))]
{
if let Some(p) = uikit_impl::root_page(inst.clone()) {
return p;
}
}
#[cfg(all(feature = "material", target_os = "android"))]
{
if let Some(p) = android_impl::root_page(inst.clone()) {
return p;
}
}
#[cfg(all(feature = "arkui", target_env = "ohos"))]
{
if let Some(p) = arkui_impl::root_page(inst.clone()) {
return p;
}
}
composed_root_page(inst)
}
#[expect(
clippy::needless_pass_by_value,
reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn composed_root_page(inst: Rc<Installed>) -> AnyPiece {
let mut parts: Vec<AnyPiece> = Vec::new();
if let Some(about) = &inst.about {
parts.push(about_header(inst.clone(), about));
}
let groups = inst.visible_groups();
if groups.len() == 1 {
let g = groups[0];
for s in &g.sections {
if let Some(p) = section_piece(inst.clone(), s, false) {
parts.push(p);
}
}
if let Some(custom) = &g.custom {
parts.push(custom());
}
} else {
let rows: Vec<AnyPiece> = groups
.iter()
.map(|g| {
let id = g.id;
let path = inst.path;
let titles = match &g.subtitle {
Some(sub) => column((
text_label(&g.title),
text_label(sub).font(day_spec::Font::Footnote).secondary(),
))
.spacing(2.0)
.align(HAlign::Leading)
.any(),
None => text_label(&g.title).any(),
};
let leading = match &g.icon {
Some(GroupIcon::Image(name)) => {
image(name.clone()).template().frame(24.0, 24.0).any()
}
Some(GroupIcon::Symbol(sym)) => match sym.outline_svg() {
Some(svg) => image(svg.into_bytes()).template().frame(24.0, 24.0).any(),
None => spacer().frame(24.0, 24.0).any(),
},
None => spacer().frame(24.0, 24.0).any(),
};
row((leading, titles, spacer(), label("›").secondary()))
.spacing(12.0)
.align(VAlign::Center)
.grow(Dimension::Width)
.on_tap(move || path.update(|p| p.push(SettingsRoute::Group(id.to_string()))))
.id(day_core::id!(prefs_group, id))
.any()
})
.collect();
parts.push(section(rows).any());
}
scroll(
form(parts)
.padding(16.0)
.grow(Dimension::Width)
.id(day_core::id!(settings_root)),
)
.any()
}
#[expect(
clippy::needless_pass_by_value,
reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn about_header(inst: Rc<Installed>, about: &About) -> AnyPiece {
let path = inst.path;
let name = about.display_name();
let version = about.version_line().unwrap_or_default();
let icon = match about.icon_name() {
Some(n) => image(n.clone()).frame(48.0, 48.0).corner_radius(10.0).any(),
None => column(()).any(),
};
section((row((
icon,
column((
label(name).bold(),
label(version).font(day_spec::Font::Footnote).secondary(),
))
.spacing(2.0)
.align(HAlign::Leading),
spacer(),
label("›").secondary(),
))
.spacing(12.0)
.align(VAlign::Center)
.grow(Dimension::Width)
.on_tap(move || path.update(|p| p.push(SettingsRoute::About)))
.id(day_core::id!(settings_about)),))
.any()
}
#[expect(
clippy::needless_pass_by_value,
reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn about_page(inst: Rc<Installed>) -> AnyPiece {
let Some(about) = &inst.about else {
return column(()).any();
};
if let Some(custom) = about.custom_piece() {
return custom;
}
if inst.presentation == Presentation::Navigation {
#[cfg(all(feature = "uikit", target_os = "ios"))]
{
if let Some(p) = uikit_impl::about_page(inst.clone()) {
return p;
}
}
#[cfg(all(feature = "material", target_os = "android"))]
{
if let Some(p) = android_impl::about_page(inst.clone()) {
return p;
}
}
}
let mut head: Vec<AnyPiece> = Vec::new();
if let Some(n) = about.icon_name() {
head.push(image(n.clone()).frame(96.0, 96.0).corner_radius(20.0).any());
}
head.push(
label(about.display_name())
.font(day_spec::Font::Title2)
.bold()
.id(day_core::id!(about_name))
.any(),
);
if let Some(v) = about.version_line() {
head.push(label(v).secondary().id(day_core::id!(about_version)).any());
}
if let Some(t) = about.tagline_text() {
head.push(label(t).id(day_core::id!(about_tagline)).any());
}
let mut parts: Vec<AnyPiece> = vec![
column(head)
.spacing(6.0)
.align(HAlign::Center)
.grow(Dimension::Width)
.any(),
];
let mut links: Vec<AnyPiece> = about
.links()
.iter()
.enumerate()
.map(|(i, (t, url))| {
link(text_source_fn(t), url.clone())
.id(day_core::id!(about_link, i))
.any()
})
.collect();
if let Some(p) = about.privacy_url() {
links.push(
link(
day_localization_ui::res::str::day_about_privacy(),
p.to_string(),
)
.id(day_core::id!(about_privacy))
.any(),
);
}
if !links.is_empty() {
parts.push(section(links).any());
}
let mut notes: Vec<AnyPiece> = Vec::new();
if let Some(c) = about.credits_text() {
let credits = c.clone();
notes.push(
rows::navigate(
day_localization_ui::res::str::day_about_acknowledgements(),
move || scroll(label(credits.clone()).padding(16.0)),
)
.into_piece(inst.clone()),
);
}
if let Some(l) = about.licenses_text() {
let licenses = l.clone();
notes.push(
rows::navigate(
day_localization_ui::res::str::day_about_licenses(),
move || scroll(label(licenses.clone()).monospace().padding(16.0)),
)
.into_piece(inst.clone()),
);
}
if !notes.is_empty() {
parts.push(section(notes).any());
}
if let Some(c) = about.copyright_text() {
parts.push(
label(c)
.font(day_spec::Font::Footnote)
.secondary()
.id(day_core::id!(about_copyright))
.any(),
);
}
let body = form(parts)
.padding(20.0)
.grow(Dimension::Width)
.id(day_core::id!(about_page));
if inst.presentation == Presentation::Window {
hugging_scroll(body).any()
} else {
scroll(body).any()
}
}
fn hugging_scroll<P: Piece>(child: P) -> impl Piece {
day_core::piece_fn(move |cx: &mut day_core::BuildCx| {
let node = cx.native(
day_spec::kinds::SCROLL,
&day_spec::props::ScrollProps {
horizontal: false,
..Default::default()
},
Rc::new(HuggingScrollLayout),
day_core::Flex {
grow_w: true,
..Default::default()
},
day_core::Boundary::Yes,
);
cx.under(node, |cx| {
let _ = child.build(cx);
});
node
})
}
struct HuggingScrollLayout;
impl day_core::Layout for HuggingScrollLayout {
fn measure(
&self,
cx: &mut dyn day_core::LayoutOps,
children: &[day_core::RNode],
p: day_spec::Proposal,
) -> day_spec::Size {
let cs = match children.first() {
Some(&c) => cx.measure_child(c, day_spec::Proposal::new(p.width, None)),
None => day_spec::Size::ZERO,
};
let height = match p.height {
Some(h) => cs.height.min(h),
None => cs.height,
};
day_spec::Size::new(p.width.unwrap_or(cs.width), height)
}
fn place(
&self,
cx: &mut dyn day_core::LayoutOps,
children: &[day_core::RNode],
bounds: day_spec::Rect,
) {
let Some(&c) = children.first() else {
return;
};
let mut width = bounds.size.width;
let mut cs = cx.measure_child(c, day_spec::Proposal::new(Some(width), None));
if cs.height > bounds.size.height {
let inset = cx.scroll_bar_inset(true);
if inset > 0.0 {
width = (width - inset).max(0.0);
cs = cx.measure_child(c, day_spec::Proposal::new(Some(width), None));
}
}
let content = day_spec::Size::new(width, cs.height.max(bounds.size.height));
cx.place_child(c, day_spec::Rect::from_size(content));
cx.set_scroll_content(content);
}
}
impl Row {
fn into_piece(self, inst: Rc<Installed>) -> AnyPiece {
let desktop = inst.presentation == Presentation::Window;
row_piece(inst, &self, desktop)
}
}
#[cfg(feature = "conformance")]
pub mod conformance {
struct SharedTestStore(std::rc::Rc<super::MemoryStore>);
impl super::Store for SharedTestStore {
fn get(&self, key: &str) -> Option<String> {
self.0.get(key)
}
fn set(&self, key: &str, value: &str) -> bool {
self.0.set(key, value)
}
fn remove(&self, key: &str) -> bool {
self.0.remove(key)
}
}
use day_core::conformance::{Case, Drive};
use day_spec::Cap;
use super::*;
static SOUND: Pref<bool> = Pref::new("conformance.sound", || true);
static SCALE: Pref<f64> = Pref::new("conformance.scale", || 100.0);
#[cfg(all(feature = "xaml", target_os = "windows"))]
#[day_macros::test(day_core)]
fn settings_card_keeps_header_readable() -> Case {
Case::new()
.proves("day-piece-settings.row")
.page(|| {
let inst = Rc::new(Installed {
in_nav: Default::default(),
about: None,
groups: Vec::new(),
presentation: Presentation::Window,
title: TextSource::Static("Settings".into()),
selected: Signal::new(String::new()),
path: Signal::new(Vec::new()),
});
let narrow = xaml_impl::row_piece(
inst.clone(),
&appearance_row().id(day_core::id!(settings::narrow_theme)),
true,
)
.unwrap();
let wide = xaml_impl::row_piece(
inst,
&appearance_row().id(day_core::id!(settings::wide_theme)),
true,
)
.unwrap();
column((
narrow.id(day_core::id!(settings::narrow_card)).width(250.0),
wide.id(day_core::id!(settings::wide_card)).width(520.0),
))
})
.drive(|d: Drive| async move {
for (card_id, control_id, stacked) in [
("settings::narrow_card", "settings::narrow_theme", true),
("settings::wide_card", "settings::wide_theme", false),
] {
d.assert_frame(card_id, day_core::conformance::FrameExpect {
width: Some(if stacked { 250.0 } else { 520.0 }),
..Default::default()
}).await?;
let (card, control) = day_core::with_tree(|t| {
let card = t
.read_native(t.find_by_id(card_id).unwrap())
.unwrap()
.frame
.unwrap();
let control = t
.read_native(t.find_by_id(control_id).unwrap())
.unwrap()
.frame
.unwrap();
(card, control)
});
let y = control.origin.y - card.origin.y;
d.check(
if stacked { y >= 48.0 } else { y < 40.0 },
"the theme control must move below its header only in a narrow card",
)?;
d.check(
control.origin.x >= card.origin.x + 15.0
&& control.origin.x + control.size.width
<= card.origin.x + card.size.width - 15.0,
&format!("the theme control must remain within the card padding: {card:?}, {control:?}"),
)?;
}
d.select("settings::narrow_theme", 1).await?;
d.check(
APPEARANCE.get_untracked() == Appearance::Dark,
"reflowed theme control must remain interactive",
)?;
d.select("settings::narrow_theme", 2).await
})
}
#[day_macros::test(day_core)]
fn settings_theme_applies_and_persists() -> Case {
let store = Rc::new(MemoryStore::default());
let page_store = store.clone();
Case::new()
.proves_cap(Cap::Appearance)
.proves_duty("set_appearance")
.requires(Cap::Appearance)
.page(move || {
install_store(SharedTestStore(page_store.clone()));
let inst = Rc::new(Installed {
in_nav: Cell::default(),
about: None,
groups: vec![Group::new("general", "General").row(appearance_row())],
presentation: Presentation::Window,
title: TextSource::Static("Settings".into()),
selected: Signal::new(String::new()),
path: Signal::new(Vec::new()),
});
let g = inst.groups[0].clone();
column((group_page(inst, &g, true),))
})
.drive(move |d: Drive| {
let store = store.clone();
async move {
d.select(day_core::id!(theme_picker).as_str(), 1).await?;
d.wait_idle().await?;
d.check(
store.get("day.appearance").as_deref() == Some("dark"),
"dark not saved",
)?;
d.select(day_core::id!(theme_picker).as_str(), 2).await?;
d.wait_idle().await?;
d.check(
store.get("day.appearance").is_none(),
"System (the default) did not clear the key",
)
}
})
}
#[day_macros::test(day_core)]
fn settings_rows_persist() -> Case {
let store = Rc::new(MemoryStore::default());
let page_store = store.clone();
Case::new()
.page(move || {
install_store(SharedTestStore(page_store.clone()));
let inst = Rc::new(Installed {
in_nav: Cell::default(),
about: None,
groups: vec![
Group::new("sound", "Sound")
.row(rows::toggle(&SOUND, "Sounds"))
.row(rows::slider(&SCALE, "Scale", 50.0..=200.0).step(10.0)),
],
presentation: Presentation::Window,
title: TextSource::Static("Settings".into()),
selected: Signal::new(String::new()),
path: Signal::new(Vec::new()),
});
let g = inst.groups[0].clone();
column((group_page(inst, &g, true),))
})
.drive(move |d: Drive| {
let store = store.clone();
async move {
d.toggle(day_core::id!(pref, "conformance.sound").as_str(), false)
.await?;
d.wait_idle().await?;
d.check(!SOUND.get_untracked(), "toggle did not write the pref")?;
d.check(
store.get("conformance.sound").as_deref() == Some("false"),
"toggle did not persist",
)?;
d.set_value(day_core::id!(pref, "conformance.scale").as_str(), 150.0)
.await?;
d.wait_idle().await?;
d.check(
(SCALE.get_untracked() - 150.0).abs() < 0.5,
"slider did not write the pref",
)?;
SOUND.reset();
d.check(
store.get("conformance.sound").is_none(),
"reset did not remove the key",
)
}
})
}
static COUNT: Pref<i64> = Pref::new("conformance.count", || 3);
#[day_macros::test(day_core)]
fn settings_row_enabled_gates_stepper() -> Case {
let gate = Signal::new(false);
Case::new()
.page(move || {
let inst = Rc::new(Installed {
in_nav: Cell::default(),
about: None,
groups: vec![
Group::new("counts", "Counts")
.row(rows::stepper(&COUNT, "Count", 0..=10).enabled(gate)),
],
presentation: Presentation::Window,
title: TextSource::Static("Settings".into()),
selected: Signal::new(String::new()),
path: Signal::new(Vec::new()),
});
let g = inst.groups[0].clone();
column((
group_page(inst, &g, true),
button("Enable")
.action(move || gate.set(true))
.id(day_core::id!(settings::enable)),
))
})
.drive(|d: Drive| async move {
let count = day_core::id!(pref, "conformance.count");
let increment = day_core::id!(pref_increment, count.as_str());
let decrement = day_core::id!(pref_decrement, count.as_str());
d.assert_enabled(increment.as_str(), false).await?;
d.assert_enabled(decrement.as_str(), false).await?;
d.tap("settings::enable").await?;
d.wait_idle().await?;
d.assert_enabled(increment.as_str(), true).await?;
d.assert_enabled(decrement.as_str(), true).await?;
let initial = COUNT.get_untracked();
d.assert_text(count.as_str(), &initial.to_string()).await?;
d.tap(increment.as_str()).await?;
d.assert_text(count.as_str(), &(initial + 1).to_string())
.await?;
d.tap(decrement.as_str()).await?;
d.assert_text(count.as_str(), &initial.to_string()).await
})
}
}