use super::*;
use day_core::{Boundary, BuildCx, Flex, Layout, LayoutOps, RNode, with_tree};
use day_toolkit_gtk::{Gtk, gtk};
use day_spec::ffi_guard;
use day_spec::{Event, NodeId, Proposal, Rect, Size};
use gtk4::glib;
use gtk4::prelude::*;
use libadwaita as adw;
use libadwaita::prelude::*;
const ROW_KIND: &str = "day-piece-settings.row";
const ACTIVATE_TAG: &str = "day-piece-settings:activate";
const TRAILING_INSET: f64 = 12.0;
const GAP: f64 = 12.0;
const CONTROL_PAD: f64 = 6.0;
const ROW_MIN_H: f64 = 48.0;
#[derive(Clone, Debug, PartialEq)]
struct RowProps {
key: u64,
title: String,
subtitle: String,
activatable: bool,
suffix_icon: Option<&'static str>,
secondary_title: bool,
enabled: bool,
}
#[derive(Clone, Debug, PartialEq)]
enum RowPatch {
Title(String),
Subtitle(String),
Enabled(bool),
}
struct RowState {
row: adw::ActionRow,
reserve: gtk4::Box,
key: u64,
}
day_core::tls_group! {
static ROWS: RefCell<HashMap<usize, RowState>> = RefCell::new(HashMap::new());
static RESERVES: RefCell<HashMap<u64, gtk4::Box>> = RefCell::new(HashMap::new());
static NEXT_KEY: Cell<u64> = const { Cell::new(0) };
static CSS_INSTALLED: Cell<bool> = const { Cell::new(false) };
static SHELLS: RefCell<HashMap<usize, Rc<ShellState>>> = RefCell::new(HashMap::new());
static SHELL_BY_NODE: RefCell<HashMap<NodeId, Rc<ShellState>>> = RefCell::new(HashMap::new());
static OPEN_SHELL: RefCell<Option<OpenShell>> = const { RefCell::new(None) };
static SLOT_WIDGETS: RefCell<HashMap<u64, gtk4::Widget>> = RefCell::new(HashMap::new());
static SLOT_KEYS: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
static FILL_WIDTHS: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
}
fn next_key() -> u64 {
NEXT_KEY.with(|k| {
let v = k.get() + 1;
k.set(v);
v
})
}
fn reserve_width(st: &RowState) -> f64 {
f64::from(st.reserve.width_request().max(0))
}
fn set_reserve(key: u64, w: f64) {
RESERVES.with(|m| {
if let Some(b) = m.borrow().get(&key) {
let w = w.round() as i32;
if b.width_request() != w {
b.set_size_request(w, -1);
}
}
});
}
fn key(w: >k4::Widget) -> usize {
w.as_ptr() as usize
}
fn install_css() {
if CSS_INSTALLED.with(|c| c.replace(true)) {
return;
}
let provider = gtk4::CssProvider::new();
provider.load_from_data(
"list.day-settings-list { background: none; }\n\
list.day-settings-list > row { border-radius: 6px; }\n\
list.day-settings-list > row.activatable:hover { background-color: alpha(currentColor, 0.07); }\n\
list.day-settings-list > row.activatable:active { background-color: alpha(currentColor, 0.16); }\n\
list.day-settings-list > row.day-settings-caption-only .title { font-size: smaller; opacity: 0.55; }",
);
if let Some(display) = gtk4::gdk::Display::default() {
gtk4::style_context_add_provider_for_display(
&display,
&provider,
gtk4::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
}
}
fn make(_backend: &mut Gtk, p: &RowProps, id: NodeId) -> gtk4::Widget {
install_css();
let row = adw::ActionRow::new();
row.set_use_markup(false);
row.set_title(&p.title);
row.set_title_lines(if p.secondary_title { 2 } else { 1 });
row.set_subtitle_lines(2);
if !p.subtitle.is_empty() {
row.set_subtitle(&p.subtitle);
}
row.set_activatable(p.activatable);
row.set_sensitive(p.enabled);
row.add_css_class("day-settings-row");
if p.secondary_title {
row.add_css_class("day-settings-caption-only");
}
if let Some(icon) = p.suffix_icon {
let image = gtk4::Image::from_icon_name(icon);
image.add_css_class("dim-label");
row.add_suffix(&image);
}
let reserve = gtk4::Box::new(gtk4::Orientation::Horizontal, 0);
row.add_suffix(&reserve);
RESERVES.with(|m| m.borrow_mut().insert(p.key, reserve.clone()));
let list = gtk4::ListBox::new();
list.set_selection_mode(gtk4::SelectionMode::None);
list.add_css_class("day-settings-list");
list.append(&row);
if p.activatable {
list.connect_row_activated(move |_, _| {
day_toolkit_gtk::emit(id, Event::custom(ACTIVATE_TAG, ""));
});
}
let host = gtk4::Fixed::new();
host.put(&list, 0.0, 0.0);
host.bind_property("width-request", &list, "width-request")
.sync_create()
.build();
host.bind_property("height-request", &list, "height-request")
.sync_create()
.build();
let w: gtk4::Widget = host.upcast();
ROWS.with(|m| {
m.borrow_mut().insert(
key(&w),
RowState {
row,
reserve,
key: p.key,
},
)
});
w
}
fn update(_backend: &mut Gtk, h: >k4::Widget, patch: &RowPatch) {
ROWS.with(|m| {
let m = m.borrow();
let Some(st) = m.get(&key(h)) else {
return;
};
match patch {
RowPatch::Title(t) => st.row.set_title(t),
RowPatch::Subtitle(s) => st.row.set_subtitle(s),
RowPatch::Enabled(on) => st.row.set_sensitive(*on),
}
});
}
fn measure(_backend: &mut Gtk, h: >k4::Widget, p: Proposal) -> Size {
let Some((row, reserve)) = ROWS.with(|m| {
m.borrow()
.get(&key(h))
.map(|s| (s.row.clone(), reserve_width(s)))
}) else {
return Size::new(p.width.unwrap_or(0.0), ROW_MIN_H);
};
let (min_w, nat_w, _, _) = row.measure(gtk4::Orientation::Horizontal, -1);
let for_w = match p.width {
Some(w) => ((w + reserve).round() as i32).max(min_w),
None => -1,
};
let (_, nat_h, _, _) = row.measure(gtk4::Orientation::Vertical, for_w);
Size::new(
(f64::from(nat_w) - reserve).max(0.0),
f64::from(nat_h).max(ROW_MIN_H),
)
}
fn release(_backend: &mut Gtk, h: >k4::Widget) {
let taken = ROWS.with(|m| m.borrow_mut().remove(&key(h)));
if let Some(st) = taken {
RESERVES.with(|m| {
m.borrow_mut().remove(&st.key);
});
}
}
day_spec::renderer!(day_toolkit_gtk::RENDERERS, Gtk,
kind: ROW_KIND, props: RowProps, patch: RowPatch,
make: make, update: update, measure: measure, release: release);
struct RowLayout {
stretch: Option<f64>,
key: u64,
}
impl RowLayout {
fn control_size(&self, cx: &mut dyn LayoutOps, c: RNode, width: Option<f64>) -> Size {
let proposal = match self.stretch {
Some(min) => {
let text_w = cx.measure_leaf(Proposal::new(None, None)).width;
let w = width
.map(|w| (w - text_w - GAP - TRAILING_INSET).max(min))
.unwrap_or(min);
Proposal::new(Some(w), None)
}
None => Proposal::new(None, None),
};
cx.measure_child(c, proposal)
}
fn text_proposal(width: Option<f64>, ctl_w: f64) -> Proposal {
Proposal::new(width.map(|w| (w - ctl_w - GAP).max(0.0)), None)
}
}
impl Layout for RowLayout {
fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
let ctl = children
.first()
.map(|&c| self.control_size(cx, c, p.width))
.unwrap_or(Size::ZERO);
let leaf = cx.measure_leaf(Self::text_proposal(p.width, ctl.width));
let width = p
.width
.unwrap_or(leaf.width + GAP + ctl.width + TRAILING_INSET);
let height = leaf.height.max(ctl.height + 2.0 * CONTROL_PAD);
Size::new(width, height)
}
fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
let Some(&c) = children.first() else {
return;
};
let width = bounds.size.width;
let s = self.control_size(cx, c, Some(width));
set_reserve(self.key, s.width + GAP);
let x = (width - TRAILING_INSET - s.width).max(0.0);
let y = ((bounds.size.height - s.height) / 2.0).max(0.0);
cx.place_child(c, Rect::new(x, y, s.width, s.height));
}
}
struct NativeRow {
props: RowProps,
title: TextSource,
caption: Option<TextSource>,
enabled: Option<Reactive<bool>>,
control: Option<AnyPiece>,
stretch: Option<f64>,
on_activate: Option<Rc<dyn Fn()>>,
}
fn patch(node: RNode, p: RowPatch, affects_size: bool) {
with_tree(|t| t.patch(node, Box::new(p), affects_size));
}
impl Piece for NativeRow {
fn build(self, cx: &mut BuildCx) -> RNode {
let NativeRow {
mut props,
title,
caption,
enabled,
control,
stretch,
on_activate,
} = self;
let key = next_key();
props.key = key;
let node = cx.native(
ROW_KIND,
&props,
Rc::new(RowLayout { stretch, key }),
Flex {
grow_w: true,
..Default::default()
},
Boundary::No,
);
if let Some(control) = control {
cx.under(node, |cx| {
let _ = control.build(cx);
});
}
if let TextSource::Dyn(f) = title {
watch(
move || f(),
move |t, _| patch(node, RowPatch::Title(t.clone()), true),
);
}
if let Some(TextSource::Dyn(f)) = caption {
watch(
move || f(),
move |t, _| patch(node, RowPatch::Subtitle(t.clone()), true),
);
}
if let Some(enabled) = enabled {
watch(
move || enabled.get(),
move |on, _| patch(node, RowPatch::Enabled(*on), false),
);
}
if let Some(on) = on_activate {
cx.on(node, move |ev| match ev {
Event::Custom { tag, .. } if *tag == ACTIVATE_TAG => on(),
Event::Tap(_) => on(),
_ => {}
});
}
node
}
}
pub(super) fn row_piece(inst: Rc<Installed>, r: &Row, _desktop: bool) -> Option<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(|e| e.get());
let enabled_now = enabled_fn();
let props = |activatable: bool, suffix_icon: Option<&'static str>| RowProps {
key: 0,
title: r.title.initial(),
subtitle: r
.caption
.as_ref()
.map_or_default(TextSource::initial),
activatable,
suffix_icon,
secondary_title: false,
enabled: enabled_now,
};
let caption_only_props = |c: &TextSource| RowProps {
key: 0,
title: c.initial(),
subtitle: String::new(),
activatable: false,
suffix_icon: None,
secondary_title: true,
enabled: enabled_now,
};
let native = |props: RowProps,
control: Option<AnyPiece>,
stretch: Option<f64>,
on_activate: Option<Rc<dyn Fn()>>| {
AnyPiece::new(NativeRow {
props,
title: r.title.clone(),
caption: r.caption.clone(),
enabled: r.enabled.clone(),
control,
stretch,
on_activate,
})
};
let native_caption_only = |c: &TextSource, control: AnyPiece| {
AnyPiece::new(NativeRow {
props: caption_only_props(c),
title: c.clone(),
caption: None,
enabled: r.enabled.clone(),
control: Some(control),
stretch: None,
on_activate: None,
})
};
let piece = match &r.kind {
RowKind::Toggle(sig) => {
let ctl = with_id(toggle(*sig).enabled(enabled_fn.clone()).any());
let sig = *sig;
let flip = move || {
if enabled_fn() {
sig.set(!sig.get_untracked());
}
};
native(props(true, None), Some(ctl), None, Some(Rc::new(flip)))
}
RowKind::Choice {
labels,
index,
style,
} => {
let p = choice_picker(labels, *index, *style == ChoiceStyle::Segmented, enabled_fn);
native(props(false, None), Some(with_id(p.any())), None, None)
}
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()).grow(Dimension::Width).min_width(140.0).any(),
None => s.grow(Dimension::Width).min_width(140.0).any(),
};
let ctl = match value_text {
Some(f) => {
let f = f.clone();
let v = *value;
row((ctl, label(move || f(v.get())).tabular().secondary()))
.spacing(8.0)
.align(VAlign::Center)
.grow(Dimension::Width)
.any()
}
None => ctl,
};
native(props(false, None), Some(ctl), Some(160.0), None)
}
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());
native(props(false, None), Some(ctl), None, None)
}
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 ctl = match &id {
Some(i) => f
.enabled(enabled_fn)
.id(i.clone())
.grow(Dimension::Width)
.min_width(160.0)
.any(),
None => f.enabled(enabled_fn).grow(Dimension::Width).min_width(160.0).any(),
};
native(props(false, None), Some(ctl), Some(160.0), None)
}
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 busy_gate = 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 b = button(text_source_fn(&r.title))
.action(run)
.enabled(move || enabled_fn() && !busy_gate.as_ref().is_some_and(|b| b.get()));
let destructive = *destructive;
let b = b.tweak(gtk(move |w, _| {
if destructive {
w.add_css_class("destructive-action");
}
}));
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) => native_caption_only(c, ctl),
None => native(props(false, None), Some(ctl), None, None),
}
}
RowKind::Link(url) => {
let url = url.clone();
match &r.caption {
Some(c) => {
let l = with_id(link(text_source_fn(&r.title), url).any());
native_caption_only(c, l)
}
None => {
let open: Rc<dyn Fn()> = Rc::new(move || day_core::open_url(&url));
with_id(native(
props(true, Some("adw-external-link-symbolic")),
None,
None,
Some(open),
))
}
}
}
RowKind::Navigate(build) => {
let build = build.clone();
let title = text_source_fn(&r.title);
let open: Rc<dyn Fn()> = Rc::new(move || {
push_subpage(inst.clone(), title(), build.clone());
});
with_id(native(
props(true, Some("go-next-symbolic")),
None,
None,
Some(open),
))
}
RowKind::Info { value, copyable } => {
let v = text_label(value).secondary();
let v = if *copyable {
let text = value.clone();
v.on_tap(move || {
let _ = day_part_clipboard::set_text(&text.initial());
})
.any()
} else {
v.any()
};
native(props(false, None), Some(with_id(v)), None, None)
}
RowKind::Note | RowKind::Custom(_) => return None,
};
Some(piece)
}
pub(super) fn install_about(inst: Rc<Installed>) -> bool {
let Some(about) = inst.about.as_ref() else {
return false;
};
if about.custom.is_some() {
return false;
}
day_core::register_about(move || present_about(&inst));
true
}
fn parent_window() -> Option<gtk4::Window> {
let windows: Vec<gtk4::Window> = gtk4::Window::list_toplevels()
.into_iter()
.filter_map(|w| w.downcast::<gtk4::Window>().ok())
.filter(|w| w.is_visible())
.collect();
windows
.iter()
.find(|w| w.is_active())
.or(windows.first())
.cloned()
}
fn present_about(inst: &Installed) {
let Some(about) = inst.about.as_ref() else {
return;
};
let dialog = adw::AboutDialog::new();
dialog.set_application_name(&about.display_name());
let version = about
.version_value()
.map(str::to_owned)
.or_else(|| day_core::launch_options().and_then(|o| o.version.clone()));
if let Some(v) = version {
let v = match about.build_value() {
Some(b) if !b.is_empty() => format!("{v} ({b})"),
_ => v,
};
dialog.set_version(&v);
}
if let Some(t) = about.tagline_text() {
dialog.set_comments(&t);
}
if let Some(c) = about.copyright_text() {
dialog.set_copyright(&c);
}
if let Ok(icon) = std::env::var("DAY_ICON_NAME")
&& !icon.is_empty()
{
dialog.set_application_icon(&icon);
}
let website = day_localization::t(day_localization::key::day_about_website);
for (title, url) in about.links() {
let title = title.initial();
if title == website {
dialog.set_website(url);
} else {
dialog.add_link(&title, url);
}
}
if let Some(p) = about.privacy_url() {
dialog.add_link(&day_localization::t(day_localization::key::day_about_privacy), p);
}
if let Some(credits) = about.credits_text() {
let people: Vec<&str> = credits
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.collect();
if !people.is_empty() {
dialog.add_acknowledgement_section(
Some(&day_localization::t(day_localization::key::day_about_acknowledgements)),
&people,
);
}
}
if let Some(licenses) = about.licenses_text() {
dialog.add_legal_section(
&day_localization::t(day_localization::key::day_about_licenses),
None,
gtk4::License::Custom,
Some(&licenses),
);
}
dialog.present(parent_window().as_ref());
}
const SHELL_KIND: &str = "day-piece-settings.panel";
const SLOT_KIND: &str = "day-piece-settings.slot";
const SELECT_TAG: &str = "day-piece-settings:select";
const ROW_TAG: &str = "day-piece-settings:row";
const FILL_TAG: &str = "day-piece-settings:fill";
const SUFFIX_CONTROL_W: f64 = 180.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SlotKind {
Suffix,
Fill,
Marker,
}
struct SlotShared {
key: u64,
kind: SlotKind,
width: Cell<Option<f64>>,
node: Cell<Option<RNode>>,
}
#[derive(Clone, Debug, PartialEq)]
struct SlotProps {
key: u64,
kind: SlotKind,
}
#[derive(Clone, Debug, PartialEq)]
struct ShellRow {
key: u64,
title: String,
subtitle: String,
activatable: bool,
suffix_icon: Option<&'static str>,
destructive: bool,
enabled: bool,
kind: ShellRowKind,
}
#[derive(Clone, Debug, PartialEq)]
enum ShellRowKind {
Row { slot: Option<u64> },
Custom { slot: u64 },
Note,
}
#[derive(Clone, Debug, PartialEq)]
struct ShellGroup {
key: u64,
title: String,
description: String,
rows: Vec<ShellRow>,
}
#[derive(Clone, Debug, PartialEq)]
struct ShellPage {
id: String,
title: String,
icon: Option<String>,
groups: Vec<ShellGroup>,
custom: Option<u64>,
}
#[derive(Clone, Debug, PartialEq)]
struct ShellProps {
root: NodeId,
pages: Vec<ShellPage>,
selected: String,
}
#[derive(Clone, Debug, PartialEq)]
enum ShellPatch {
Select(String),
PageTitle(String, String),
GroupTitle(u64, String),
GroupDescription(u64, String),
RowTitle(u64, String),
RowSubtitle(u64, String),
RowEnabled(u64, bool),
Note(u64, String),
}
enum SlotTarget {
Suffix(adw::ActionRow),
Fill(SlotHost),
}
enum ShellHost {
Dialog(adw::PreferencesDialog),
Stack(adw::ViewStack),
}
impl ShellHost {
fn visible_page_name(&self) -> Option<String> {
match self {
ShellHost::Dialog(d) => d.visible_page_name().map(|n| n.to_string()),
ShellHost::Stack(s) => s.visible_child_name().map(|n| n.to_string()),
}
}
fn set_visible_page_name(&self, name: &str) {
match self {
ShellHost::Dialog(d) => d.set_visible_page_name(name),
ShellHost::Stack(s) => s.set_visible_child_name(name),
}
}
}
struct ShellState {
node: NodeId,
host: ShellHost,
pages: HashMap<String, adw::PreferencesPage>,
groups: HashMap<u64, adw::PreferencesGroup>,
rows: HashMap<u64, adw::ActionRow>,
custom_rows: HashMap<u64, adw::PreferencesRow>,
notes: HashMap<u64, gtk4::Label>,
pending: RefCell<Vec<(u64, SlotTarget)>>,
suppress: Cell<bool>,
}
struct OpenShell {
node: RNode,
owner: day_reactive::Scope,
fills: Rc<RefCell<Vec<Rc<SlotShared>>>>,
state: Rc<ShellState>,
}
mod slot_host {
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use gtk4::glib;
use gtk4::prelude::*;
use gtk4::subclass::prelude::*;
type WidthHook = Rc<dyn Fn(i32)>;
#[derive(Default)]
pub struct SlotHostImp {
pub natural_height: Cell<bool>,
pub on_width: RefCell<Option<WidthHook>>,
}
#[glib::object_subclass]
impl ObjectSubclass for SlotHostImp {
const NAME: &'static str = "DaySettingsSlotHost";
type Type = super::SlotHost;
type ParentType = gtk4::Widget;
}
impl ObjectImpl for SlotHostImp {
fn dispose(&self) {
while let Some(child) = self.obj().first_child() {
child.unparent();
}
}
}
impl WidgetImpl for SlotHostImp {
fn measure(&self, orientation: gtk4::Orientation, for_size: i32) -> (i32, i32, i32, i32) {
if orientation == gtk4::Orientation::Vertical
&& self.natural_height.get()
&& let Some(child) = self.obj().first_child()
{
let (min, nat, _, _) = child.measure(orientation, for_size);
return (min, nat, -1, -1);
}
(0, 0, -1, -1)
}
fn size_allocate(&self, width: i32, height: i32, baseline: i32) {
if let Some(child) = self.obj().first_child() {
let (min_w, ..) = child.measure(gtk4::Orientation::Horizontal, -1);
let (min_h, ..) = child.measure(gtk4::Orientation::Vertical, -1);
child.allocate(width.max(min_w), height.max(min_h), baseline, None);
}
let hook = self.on_width.borrow().clone();
if let Some(hook) = hook {
day_spec::ffi_guard::contain((), || hook(width));
}
}
}
}
glib::wrapper! {
pub struct SlotHost(ObjectSubclass<slot_host::SlotHostImp>)
@extends gtk4::Widget,
@implements gtk4::Accessible, gtk4::Buildable, gtk4::ConstraintTarget;
}
impl SlotHost {
fn new(natural_height: bool) -> Self {
use gtk4::subclass::prelude::ObjectSubclassIsExt;
let host: Self = glib::Object::new();
host.imp().natural_height.set(natural_height);
host
}
fn set_child(&self, child: >k4::Widget) {
child.set_parent(self);
}
fn on_width(&self, f: impl Fn(i32) + 'static) {
use gtk4::subclass::prelude::ObjectSubclassIsExt;
*self.imp().on_width.borrow_mut() = Some(Rc::new(f));
}
}
struct SlotLayout {
shared: Rc<SlotShared>,
}
impl Layout for SlotLayout {
fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
let Some(&c) = children.first() else {
return Size::new(1.0, 1.0);
};
let width = match self.shared.kind {
SlotKind::Fill => self.shared.width.get().or(p.width),
_ => None,
};
let s = cx.measure_child(c, Proposal::new(width, None));
Size::new(width.unwrap_or(s.width), s.height)
}
fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
if let Some(&c) = children.first() {
cx.place_child(
c,
Rect::new(0.0, 0.0, bounds.size.width, bounds.size.height),
);
}
}
}
struct Slot {
shared: Rc<SlotShared>,
child: Option<AnyPiece>,
on_tap: Option<Rc<dyn Fn()>>,
id: Option<day_core::ElementId>,
}
impl Piece for Slot {
fn build(self, cx: &mut BuildCx) -> RNode {
let Slot {
shared,
child,
on_tap,
id,
} = self;
let node = cx.native(
SLOT_KIND,
&SlotProps {
key: shared.key,
kind: shared.kind,
},
Rc::new(SlotLayout {
shared: shared.clone(),
}),
Flex::default(),
Boundary::No,
);
shared.node.set(Some(node));
if let Some(id) = id {
with_tree(|t| t.set_id(node, id.as_str().to_owned()));
}
if let Some(child) = child {
cx.under(node, |cx| {
let _ = child.build(cx);
});
}
if let Some(on) = on_tap {
cx.on(node, move |ev| {
if let Event::Tap(_) = ev {
on();
}
});
}
node
}
}
fn slot_make(_backend: &mut Gtk, p: &SlotProps, _id: NodeId) -> gtk4::Widget {
let fixed = gtk4::Fixed::new();
if p.kind == SlotKind::Marker {
fixed.set_visible(false);
fixed.set_can_target(false);
fixed.set_can_focus(false);
}
let w: gtk4::Widget = fixed.upcast();
SLOT_WIDGETS.with(|m| m.borrow_mut().insert(p.key, w.clone()));
SLOT_KEYS.with(|m| m.borrow_mut().insert(key(&w), p.key));
w
}
fn slot_update(_backend: &mut Gtk, _h: >k4::Widget, _patch: &()) {}
fn slot_release(_backend: &mut Gtk, h: >k4::Widget) {
if let Some(k) = SLOT_KEYS.with(|m| m.borrow_mut().remove(&key(h))) {
SLOT_WIDGETS.with(|m| m.borrow_mut().remove(&k));
}
}
mod slot_renderer {
use super::*;
day_spec::renderer!(day_toolkit_gtk::RENDERERS, Gtk,
kind: SLOT_KIND, props: SlotProps, patch: (),
make: slot_make, update: slot_update, measure: day_spec::fill_measure, release: slot_release);
}
fn find_scrolled(w: >k4::Widget) -> Option<gtk4::ScrolledWindow> {
if let Some(sw) = w.downcast_ref::<gtk4::ScrolledWindow>() {
return Some(sw.clone());
}
let mut child = w.first_child();
while let Some(c) = child {
if let Some(sw) = find_scrolled(&c) {
return Some(sw);
}
child = c.next_sibling();
}
None
}
fn page_content_height(page: >k4::Widget, for_w: i32) -> i32 {
let Some(sw) = find_scrolled(page) else {
return 0;
};
let Some(viewport) = sw.child() else {
return 0;
};
let (_, nat, _, _) = viewport.measure(gtk4::Orientation::Vertical, for_w);
nat
}
fn make_action_row(r: &ShellRow, node: NodeId) -> adw::ActionRow {
let row = adw::ActionRow::new();
row.set_use_markup(false);
row.set_title(&r.title);
row.set_title_lines(1);
row.set_subtitle_lines(2);
if !r.subtitle.is_empty() {
row.set_subtitle(&r.subtitle);
}
row.set_activatable(r.activatable);
row.set_sensitive(r.enabled);
if r.destructive {
row.add_css_class("error");
}
if let Some(icon) = r.suffix_icon {
let image = gtk4::Image::from_icon_name(icon);
image.add_css_class("dim-label");
row.add_suffix(&image);
}
if r.activatable {
let k = r.key;
row.connect_activated(move |_| {
day_toolkit_gtk::emit(node, Event::custom(ROW_TAG, k.to_string()));
});
}
row
}
fn shell_make(_backend: &mut Gtk, p: &ShellProps, id: NodeId) -> gtk4::Widget {
let mut pages = HashMap::new();
let mut groups = HashMap::new();
let mut rows = HashMap::new();
let mut custom_rows = HashMap::new();
let mut notes = HashMap::new();
let mut pending = Vec::new();
let mut pending_fill: Vec<(u64, SlotTarget)> = Vec::new();
for page in &p.pages {
let pp = adw::PreferencesPage::new();
pp.set_title(&page.title);
pp.set_name(Some(&page.id));
if let Some(icon) = &page.icon {
pp.set_icon_name(Some(icon));
}
for g in &page.groups {
let group = adw::PreferencesGroup::new();
if !g.title.is_empty() {
group.set_title(&g.title);
}
if !g.description.is_empty() {
group.set_description(Some(&g.description));
}
for r in &g.rows {
match &r.kind {
ShellRowKind::Row { slot } => {
let row = make_action_row(r, id);
if let Some(slot) = slot {
pending.push((*slot, SlotTarget::Suffix(row.clone())));
}
group.add(&row);
rows.insert(r.key, row);
}
ShellRowKind::Custom { slot } => {
let row = adw::PreferencesRow::new();
row.set_activatable(false);
row.set_sensitive(r.enabled);
let host = SlotHost::new(true);
host.set_hexpand(true);
host.set_margin_start(12);
host.set_margin_end(12);
host.set_margin_top(6);
host.set_margin_bottom(6);
row.set_child(Some(&host));
pending_fill.push((*slot, SlotTarget::Fill(host)));
group.add(&row);
custom_rows.insert(r.key, row);
}
ShellRowKind::Note => {
let label = gtk4::Label::new(Some(&r.title));
label.set_wrap(true);
label.set_xalign(0.0);
label.add_css_class("dim-label");
label.add_css_class("caption");
group.add(&label);
notes.insert(r.key, label);
}
}
}
pp.add(&group);
groups.insert(g.key, group);
}
if let Some(slot) = page.custom {
let group = adw::PreferencesGroup::new();
let host = SlotHost::new(true);
host.set_hexpand(true);
group.add(&host);
pending_fill.push((slot, SlotTarget::Fill(host)));
pp.add(&group);
}
if let Some(sw) = find_scrolled(pp.upcast_ref::<gtk4::Widget>()) {
sw.set_vexpand(true);
}
pages.insert(page.id.clone(), pp);
}
pending.extend(pending_fill);
let host = gtk4::Fixed::new();
host.set_overflow(gtk4::Overflow::Hidden);
let shell_host = match day_toolkit_gtk::preferences_dialog_of(p.root) {
Some(dialog) => {
for page in &p.pages {
if let Some(pp) = pages.get(&page.id) {
dialog.add(pp);
}
}
dialog.set_search_enabled(pages.len() > 1);
if pages.contains_key(&p.selected) {
dialog.set_visible_page_name(&p.selected);
}
ShellHost::Dialog(dialog)
}
None => {
let stack = adw::ViewStack::new();
for page in &p.pages {
if let Some(pp) = pages.get(&page.id) {
let sp = stack.add_titled(pp, Some(&page.id), &page.title);
if let Some(icon) = &page.icon {
sp.set_icon_name(Some(icon));
}
}
}
if pages.contains_key(&p.selected) {
stack.set_visible_child_name(&p.selected);
}
let column = gtk4::Box::new(gtk4::Orientation::Vertical, 0);
if pages.len() > 1 {
let switcher = adw::ViewSwitcher::new();
switcher.set_policy(adw::ViewSwitcherPolicy::Wide);
switcher.set_stack(Some(&stack));
switcher.set_margin_top(6);
switcher.set_margin_bottom(6);
column.append(&switcher);
}
stack.set_vexpand(true);
column.append(&stack);
let wrapper = SlotHost::new(false);
wrapper.set_child(column.upcast_ref());
host.put(&wrapper, 0.0, 0.0);
host.bind_property("width-request", &wrapper, "width-request")
.sync_create()
.build();
host.bind_property("height-request", &wrapper, "height-request")
.sync_create()
.build();
ShellHost::Stack(stack)
}
};
let w: gtk4::Widget = host.upcast();
let state = Rc::new(ShellState {
node: id,
host: shell_host,
pages,
groups,
rows,
custom_rows,
notes,
pending: RefCell::new(pending),
suppress: Cell::new(false),
});
let select = {
let st = state.clone();
move || {
if st.suppress.get() {
return;
}
if let Some(name) = st.host.visible_page_name() {
day_toolkit_gtk::emit(id, Event::custom(SELECT_TAG, name));
}
}
};
match &state.host {
ShellHost::Dialog(d) => {
d.connect_visible_page_notify(move |_| select());
}
ShellHost::Stack(s) => {
s.connect_visible_child_name_notify(move |_| select());
}
}
SHELLS.with(|m| m.borrow_mut().insert(key(&w), state.clone()));
SHELL_BY_NODE.with(|m| m.borrow_mut().insert(id, state));
w
}
fn settle(st: &ShellState, host: >k4::Widget) {
let Some(fixed) = host.downcast_ref::<gtk4::Fixed>() else {
return;
};
let mut pending = st.pending.borrow_mut();
pending.retain(|(k, target)| {
let Some(slot) = SLOT_WIDGETS.with(|m| m.borrow().get(k).cloned()) else {
return true;
};
if slot.parent().as_ref() != Some(host) {
return true;
}
fixed.remove(&slot);
match target {
SlotTarget::Suffix(row) => {
slot.set_valign(gtk4::Align::Center);
row.add_suffix(&slot);
}
SlotTarget::Fill(fill) => {
let shared_key = *k;
let node = st.node;
fill.set_child(&slot);
fill.on_width(move |w| {
let changed = FILL_WIDTHS.with(|m| {
let mut m = m.borrow_mut();
let w = f64::from(w);
if m.get(&shared_key) == Some(&w) {
false
} else {
m.insert(shared_key, w);
true
}
});
if changed {
glib::idle_add_local_once(move || {
ffi_guard::contain((), || {
day_toolkit_gtk::emit(node, Event::custom(FILL_TAG, shared_key.to_string()))
})
});
}
});
}
}
false
});
}
fn shell_update(_backend: &mut Gtk, h: >k4::Widget, patch: &ShellPatch) {
let Some(st) = SHELLS.with(|m| m.borrow().get(&key(h)).cloned()) else {
return;
};
settle(&st, h);
match patch {
ShellPatch::Select(id) => {
if st.pages.contains_key(id) && st.host.visible_page_name().as_deref() != Some(id) {
st.suppress.set(true);
st.host.set_visible_page_name(id);
st.suppress.set(false);
}
}
ShellPatch::PageTitle(id, t) => {
if let Some(pp) = st.pages.get(id) {
pp.set_title(t);
if let ShellHost::Stack(s) = &st.host {
s.page(pp).set_title(Some(t));
}
}
}
ShellPatch::GroupTitle(k, t) => {
if let Some(g) = st.groups.get(k) {
g.set_title(t);
}
}
ShellPatch::GroupDescription(k, t) => {
if let Some(g) = st.groups.get(k) {
g.set_description((!t.is_empty()).then_some(t.as_str()));
}
}
ShellPatch::RowTitle(k, t) => {
if let Some(r) = st.rows.get(k) {
r.set_title(t);
}
}
ShellPatch::RowSubtitle(k, t) => {
if let Some(r) = st.rows.get(k) {
r.set_subtitle(t);
}
}
ShellPatch::RowEnabled(k, on) => {
if let Some(r) = st.rows.get(k) {
r.set_sensitive(*on);
}
if let Some(r) = st.custom_rows.get(k) {
r.set_sensitive(*on);
}
}
ShellPatch::Note(k, t) => {
if let Some(l) = st.notes.get(k) {
l.set_text(t);
}
}
}
}
fn shell_measure(_backend: &mut Gtk, h: >k4::Widget, p: Proposal) -> Size {
let Some(st) = SHELLS.with(|m| m.borrow().get(&key(h)).cloned()) else {
return Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0));
};
settle(&st, h);
let nat_w = st
.pages
.values()
.map(|pp| pp.measure(gtk4::Orientation::Horizontal, -1).1)
.max()
.unwrap_or(0);
let for_w = p.width.map(|w| w.round() as i32).unwrap_or(-1);
let nat_h = st
.pages
.values()
.map(|pp| page_content_height(pp.upcast_ref(), for_w))
.max()
.unwrap_or(0);
Size::new(p.width.unwrap_or(f64::from(nat_w)), f64::from(nat_h))
}
fn shell_release(_backend: &mut Gtk, h: >k4::Widget) {
let Some(st) = SHELLS.with(|m| m.borrow_mut().remove(&key(h))) else {
return;
};
SHELL_BY_NODE.with(|m| m.borrow_mut().remove(&st.node));
OPEN_SHELL.with(|o| {
let mut o = o.borrow_mut();
if o.as_ref().is_some_and(|s| Rc::ptr_eq(&s.state, &st)) {
*o = None;
}
});
}
mod shell_renderer {
use super::*;
day_spec::renderer!(day_toolkit_gtk::RENDERERS, Gtk,
kind: SHELL_KIND, props: ShellProps, patch: ShellPatch,
make: shell_make, update: shell_update, measure: shell_measure, release: shell_release);
}
struct ShellLayout;
impl Layout for ShellLayout {
fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
for &c in children {
let _ = cx.measure_child(c, Proposal::new(None, None));
}
let leaf = cx.measure_leaf(p);
let height = match p.height {
Some(h) => h.min(leaf.height),
None => leaf.height,
};
Size::new(p.width.unwrap_or(leaf.width), height)
}
fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], _bounds: Rect) {
for &c in children {
let s = cx.measure_child(c, Proposal::new(None, None));
cx.place_child_native(c, Rect::new(0.0, 0.0, s.width, s.height));
}
}
}
enum DynText {
PageTitle(String),
GroupTitle(u64),
GroupDescription(u64),
RowTitle(u64),
RowSubtitle(u64),
Note(u64),
}
impl DynText {
fn patch(&self, t: String) -> ShellPatch {
match self {
DynText::PageTitle(id) => ShellPatch::PageTitle(id.clone(), t),
DynText::GroupTitle(k) => ShellPatch::GroupTitle(*k, t),
DynText::GroupDescription(k) => ShellPatch::GroupDescription(*k, t),
DynText::RowTitle(k) => ShellPatch::RowTitle(*k, t),
DynText::RowSubtitle(k) => ShellPatch::RowSubtitle(*k, t),
DynText::Note(k) => ShellPatch::Note(*k, t),
}
}
}
fn on_navigation_stack(page: &adw::NavigationPage) -> bool {
let Some(view) = page
.parent()
.and_then(|p| p.downcast::<adw::NavigationView>().ok())
else {
return false;
};
let stack = view.navigation_stack();
(0..stack.n_items()).any(|i| {
stack
.item(i)
.is_some_and(|o| o.downcast_ref::<adw::NavigationPage>() == Some(page))
})
}
#[derive(Default)]
struct ShellBuild {
slots: Vec<Slot>,
actions: HashMap<u64, Rc<dyn Fn()>>,
dyns: Vec<(TextSource, DynText)>,
enabled: Vec<(u64, Reactive<bool>)>,
}
impl ShellBuild {
fn slot(
&mut self,
kind: SlotKind,
child: Option<AnyPiece>,
on_tap: Option<Rc<dyn Fn()>>,
id: Option<day_core::ElementId>,
) -> u64 {
let key = next_key();
self.slots.push(Slot {
shared: Rc::new(SlotShared {
key,
kind,
width: Cell::new(None),
node: Cell::new(None),
}),
child,
on_tap,
id,
});
key
}
fn text(&mut self, src: &TextSource, target: DynText) {
if matches!(src, TextSource::Dyn(_)) {
self.dyns.push((src.clone(), target));
}
}
}
fn shell_row(inst: Rc<Installed>, r: &Row, b: &mut ShellBuild) -> ShellRow {
let key = next_key();
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(|e| e.get());
let enabled_now = enabled_fn();
if let Some(sig) = r.enabled.clone() {
b.enabled.push((key, sig));
}
b.text(&r.title, DynText::RowTitle(key));
if let Some(c) = &r.caption {
b.text(c, DynText::RowSubtitle(key));
}
let mk_row =
|activatable: bool, suffix_icon: Option<&'static str>, kind: ShellRowKind| ShellRow {
key,
title: r.title.initial(),
subtitle: r
.caption
.as_ref()
.map_or_default(TextSource::initial),
activatable,
suffix_icon,
destructive: false,
enabled: enabled_now,
kind,
};
match &r.kind {
RowKind::Toggle(sig) => {
let ctl = with_id(toggle(*sig).enabled(enabled_fn.clone()).any());
let slot = b.slot(SlotKind::Suffix, Some(ctl), None, None);
let sig = *sig;
b.actions.insert(
key,
Rc::new(move || {
if enabled_fn() {
sig.set(!sig.get_untracked());
}
}),
);
mk_row(true, None, ShellRowKind::Row { slot: Some(slot) })
}
RowKind::Choice {
labels,
index,
style,
} => {
let p = choice_picker(labels, *index, *style == ChoiceStyle::Segmented, enabled_fn);
let slot = b.slot(SlotKind::Suffix, Some(with_id(p.any())), None, None);
mk_row(false, None, ShellRowKind::Row { slot: Some(slot) })
}
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(SUFFIX_CONTROL_W)
.max_width(SUFFIX_CONTROL_W)
.any(),
None => s
.min_width(SUFFIX_CONTROL_W)
.max_width(SUFFIX_CONTROL_W)
.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,
};
let slot = b.slot(SlotKind::Suffix, Some(ctl), None, None);
mk_row(false, None, ShellRowKind::Row { slot: Some(slot) })
}
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());
let slot = b.slot(SlotKind::Suffix, Some(ctl), None, None);
mk_row(false, None, ShellRowKind::Row { slot: Some(slot) })
}
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())
.min_width(SUFFIX_CONTROL_W)
.max_width(SUFFIX_CONTROL_W)
.any(),
None => f
.min_width(SUFFIX_CONTROL_W)
.max_width(SUFFIX_CONTROL_W)
.any(),
};
let slot = b.slot(SlotKind::Suffix, Some(ctl), None, None);
mk_row(false, None, ShellRowKind::Row { slot: Some(slot) })
}
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 (enabled_run, busy_run) = (enabled_fn.clone(), busy.clone());
let run: Rc<dyn Fn()> = Rc::new(move || {
if !enabled_run() || busy_run.as_ref().is_some_and(|b| b.get_untracked()) {
return;
}
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(),
}
});
b.actions.insert(key, run.clone());
let slot = match (&id, busy.clone()) {
(None, None) => None,
(_, Some(b_sig)) => Some(b.slot(
SlotKind::Suffix,
Some(
when(move || b_sig.get(), spinner)
.min_width(1.0)
.min_height(1.0)
.any(),
),
Some(run.clone()),
id.clone(),
)),
(Some(_), None) => {
Some(b.slot(SlotKind::Marker, None, Some(run.clone()), id.clone()))
}
};
if let Some(b_sig) = busy {
let sig = Signal::global(enabled_fn() && !b_sig.get_untracked());
day_reactive::Scope::root().enter(|| {
watch(
move || enabled_fn() && !b_sig.get(),
move |v, _| sig.set_if_changed(*v),
);
});
b.enabled.retain(|(k, _)| *k != key);
b.enabled.push((key, sig.into_reactive()));
}
let mut sr = mk_row(true, None, ShellRowKind::Row { slot });
sr.destructive = *destructive;
sr
}
RowKind::Link(url) => {
let url = url.clone();
let open: Rc<dyn Fn()> = Rc::new(move || day_core::open_url(&url));
b.actions.insert(key, open.clone());
let slot = id
.as_ref()
.map(|_| b.slot(SlotKind::Marker, None, Some(open.clone()), id.clone()));
mk_row(
true,
Some("adw-external-link-symbolic"),
ShellRowKind::Row { slot },
)
}
RowKind::Navigate(build) => {
let build = build.clone();
let title = text_source_fn(&r.title);
let open: Rc<dyn Fn()> = Rc::new(move || {
push_subpage(inst.clone(), title(), build.clone());
});
b.actions.insert(key, open.clone());
let slot = id
.as_ref()
.map(|_| b.slot(SlotKind::Marker, None, Some(open.clone()), id.clone()));
mk_row(true, Some("go-next-symbolic"), ShellRowKind::Row { slot })
}
RowKind::Info { value, copyable } => {
let v = text_label(value).secondary();
let v = if *copyable {
let text = value.clone();
v.on_tap(move || {
let _ = day_part_clipboard::set_text(&text.initial());
})
.any()
} else {
v.any()
};
let slot = b.slot(SlotKind::Suffix, Some(with_id(v)), None, None);
mk_row(false, None, ShellRowKind::Row { slot: Some(slot) })
}
RowKind::Note => {
b.text(&r.title, DynText::Note(key));
mk_row(false, None, ShellRowKind::Note)
}
RowKind::Custom(build) => {
let slot = b.slot(SlotKind::Fill, Some(with_id(build())), None, None);
mk_row(false, None, ShellRowKind::Custom { slot })
}
}
}
struct Shell {
inst: Rc<Installed>,
}
impl Piece for Shell {
fn build(self, cx: &mut BuildCx) -> RNode {
let inst = self.inst;
let mut b = ShellBuild::default();
let mut pages = Vec::new();
for g in inst.visible_groups() {
let mut groups = Vec::new();
for s in &g.sections {
let rows: Vec<&Row> = s.rows.iter().filter(|r| r.is_available()).collect();
if rows.is_empty() {
continue;
}
let gkey = next_key();
if let Some(t) = &s.title {
b.text(t, DynText::GroupTitle(gkey));
}
if let Some(f) = &s.footer {
b.text(f, DynText::GroupDescription(gkey));
}
let rows = rows
.into_iter()
.map(|r| shell_row(inst.clone(), r, &mut b))
.collect();
groups.push(ShellGroup {
key: gkey,
title: s
.title
.as_ref()
.map_or_default(TextSource::initial),
description: s
.footer
.as_ref()
.map_or_default(TextSource::initial),
rows,
});
}
let custom = g
.custom
.as_ref()
.map(|build| b.slot(SlotKind::Fill, Some(build()), None, None));
let icon = match &g.icon {
Some(GroupIcon::Symbol(s)) => day_toolkit_gtk::symbol_icon_name(*s),
Some(GroupIcon::Image(n)) => day_toolkit_gtk::vector_icon_name(n.as_str()),
None => None,
};
b.text(&g.title, DynText::PageTitle(g.id.to_string()));
pages.push(ShellPage {
id: g.id.to_string(),
title: g.title.initial(),
icon,
groups,
custom,
});
}
let ShellBuild {
slots,
actions,
dyns,
enabled,
} = b;
let fills: Rc<RefCell<Vec<Rc<SlotShared>>>> = Rc::new(RefCell::new(
slots
.iter()
.filter(|s| s.shared.kind == SlotKind::Fill)
.map(|s| s.shared.clone())
.collect(),
));
let node = cx.native(
SHELL_KIND,
&ShellProps {
root: day_core::rnode_to_id(cx.parent()),
pages,
selected: inst.selected.get_untracked(),
},
Rc::new(ShellLayout),
Flex {
grow_w: true,
grow_h: true,
..Default::default()
},
Boundary::Yes,
);
cx.under(node, |cx| {
for s in slots {
let _ = s.build(cx);
}
});
if let Some(state) =
SHELL_BY_NODE.with(|m| m.borrow().get(&day_core::rnode_to_id(node)).cloned())
{
OPEN_SHELL.with(|o| {
*o.borrow_mut() = Some(OpenShell {
node,
owner: day_reactive::Scope::current(),
fills: fills.clone(),
state,
})
});
}
let i = inst.clone();
let fill_slots = fills.clone();
cx.on(node, move |ev| {
if let Event::Custom { tag, text, .. } = ev {
match *tag {
SELECT_TAG => i.selected.set_if_changed(text.clone()),
ROW_TAG => {
if let Some(run) = text.parse::<u64>().ok().and_then(|k| actions.get(&k)) {
run();
}
}
FILL_TAG => {
let k = text.parse::<u64>().ok();
for s in fill_slots.borrow().iter() {
if k.is_some_and(|k| k != s.key) {
continue;
}
let w = FILL_WIDTHS.with(|m| m.borrow().get(&s.key).copied());
s.width.set(w);
if let Some(n) = s.node.get() {
day_core::invalidate_size(n);
}
}
}
_ => {}
}
}
});
let i = inst.clone();
watch(
move || i.selected.get(),
move |id, _| {
let id = id.clone();
with_tree(|t| t.patch(node, Box::new(ShellPatch::Select(id)), false));
},
);
for (src, target) in dyns {
if let TextSource::Dyn(f) = src {
watch(
move || f(),
move |t, prev| {
if prev.is_some() {
let affects_size = true;
with_tree(|tree| {
tree.patch(node, Box::new(target.patch(t.clone())), affects_size)
});
}
},
);
}
}
for (k, sig) in enabled {
watch(
move || sig.get(),
move |on, _| {
with_tree(|t| t.patch(node, Box::new(ShellPatch::RowEnabled(k, *on)), false));
},
);
}
node
}
}
pub(super) fn window_shell(inst: Rc<Installed>) -> Option<AnyPiece> {
let groups = inst.visible_groups();
if groups.is_empty() {
return None;
}
let selected = inst.selected.get_untracked();
if !groups.iter().any(|g| g.id == selected) {
inst.selected.set(groups[0].id.to_string());
}
Some(AnyPiece::new(Shell { inst }))
}
pub(super) fn push_subpage(inst: Rc<Installed>, title: String, build: Build) -> bool {
if inst.presentation != Presentation::Window {
return false;
}
let Some((node, owner, fills, state)) = OPEN_SHELL.with(|o| {
o.borrow()
.as_ref()
.map(|s| (s.node, s.owner, s.fills.clone(), s.state.clone()))
}) else {
return false;
};
let ShellHost::Dialog(dialog) = &state.host else {
return false;
};
if !with_tree(|t| t.node_exists(node)) {
return false;
}
let fill = SlotHost::new(true);
fill.set_hexpand(true);
let clamp = adw::Clamp::new();
clamp.set_maximum_size(600);
clamp.set_tightening_threshold(400);
clamp.set_margin_start(12);
clamp.set_margin_end(12);
clamp.set_margin_top(24);
clamp.set_margin_bottom(24);
clamp.set_child(Some(&fill));
let scroll = gtk4::ScrolledWindow::new();
scroll.set_policy(gtk4::PolicyType::Never, gtk4::PolicyType::Automatic);
scroll.set_vexpand(true);
scroll.set_child(Some(&clamp));
let toolbar = adw::ToolbarView::new();
toolbar.add_top_bar(&adw::HeaderBar::new());
toolbar.set_content(Some(&scroll));
let page = adw::NavigationPage::new(&toolbar, &title);
let key = next_key();
let shared = Rc::new(SlotShared {
key,
kind: SlotKind::Fill,
width: Cell::new(None),
node: Cell::new(None),
});
fills.borrow_mut().push(shared.clone());
state
.pending
.borrow_mut()
.push((key, SlotTarget::Fill(fill)));
let scope = owner.enter(day_reactive::Scope::child);
scope.enter(|| {
let mut cx = BuildCx::new(node);
let _ = Slot {
shared: shared.clone(),
child: Some(build()),
on_tap: None,
id: None,
}
.build(&mut cx);
});
with_tree(|t| {
t.mark_layout_dirty();
t.layout_if_needed();
});
dialog.push_subpage(&page);
let popped = Cell::new(false);
page.connect_hidden(move |page| {
ffi_guard::contain((), || {
if popped.get() || on_navigation_stack(page) {
return;
}
popped.set(true);
scope.dispose();
fills.borrow_mut().retain(|s| s.key != key);
FILL_WIDTHS.with(|m| m.borrow_mut().remove(&key));
if let Some(n) = shared.node.get()
&& with_tree(|t| t.node_exists(n))
{
with_tree(|t| {
t.remove_subtree(n);
t.mark_layout_dirty();
});
}
})
});
true
}