1#![cfg(windows)]
12
13mod controls;
14
15#[cfg(feature = "winui")]
16mod list;
17#[cfg(not(feature = "winui"))]
18#[path = "list_legacy.rs"]
19mod list;
20mod transfer;
21mod tree;
22
23use std::cell::{Cell, RefCell};
24use std::collections::{BTreeSet, HashMap, HashSet};
25use std::ffi::{CStr, CString};
26use std::fmt::Write as _;
27use std::os::raw::{c_char, c_double, c_int, c_void};
28use std::rc::Rc;
29
30use day_toolkit_xaml_sys as ffi;
31use linkme::distributed_slice;
32
33use day_spec::props::*;
34use day_spec::{
35 A11yProps, AnimSpec, Builtin, Cap, Cursor, DrawOp, Event, EventSink, Font, InputPurpose,
36 InputTraits, NodeId, PieceKind, Platform, Point, Proposal, Rect, Registry, Renderer, Size,
37 Support, Toolkit, Transform, WindowOptions, ffi_guard, kinds, props_of,
38};
39
40struct XamlAnim {
45 raw: ffi::DayAnim,
46 _progress: Vec<f64>,
47}
48
49impl XamlAnim {
50 fn new(anim: Option<&AnimSpec>) -> Option<XamlAnim> {
51 let a = anim?;
52 let progress: Vec<f64> = a.keyframes().iter().map(|k| k.progress).collect();
53 let raw = ffi::DayAnim {
54 delay_ms: c_int::try_from(a.delay_ms).unwrap_or(c_int::MAX),
55 duration_ms: c_int::try_from(a.duration_ms).unwrap_or(c_int::MAX),
56 repeat: a.repeat,
57 autoreverse: c_int::from(a.autoreverse),
58 frames: c_int::try_from(progress.len()).unwrap_or(0),
59 progress: progress.as_ptr(),
60 };
61 Some(XamlAnim {
62 raw,
63 _progress: progress,
64 })
65 }
66
67 fn ptr(anim: Option<&XamlAnim>) -> *const ffi::DayAnim {
69 anim.map_or(std::ptr::null(), |a| &raw const a.raw)
70 }
71}
72
73#[derive(Clone, Copy, PartialEq, Eq, Hash)]
74pub struct WinHandle(pub *mut c_void);
75
76mod picker;
78mod textarea;
79mod toolbar;
80
81pub type Handle = WinHandle;
82
83pub mod ext;
84pub use ext::*;
85
86type Sink = Rc<dyn Fn(NodeId, Event)>;
88
89day_core::tls_group! {
90 static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
91 static LOADED_MEASURES: RefCell<BTreeSet<u64>> = const { RefCell::new(BTreeSet::new()) };
93 static LABEL_NODE: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
96 static LABEL_ELIDE: RefCell<HashMap<usize, Elided>> = RefCell::new(HashMap::new());
101 static LABEL_TEXT: RefCell<HashMap<u64, String>> = RefCell::new(HashMap::new());
104 static LABEL_ALIGN: RefCell<HashMap<usize, day_spec::props::TextAlign>> =
107 RefCell::new(HashMap::new());
108 static LABEL_RUNS: RefCell<HashSet<usize>> = RefCell::new(HashSet::new());
110 static INKS: RefCell<HashMap<(usize, InkSlot), Repaint>> = RefCell::new(HashMap::new());
115 static SURFACES: RefCell<HashMap<usize, Surface>> = RefCell::new(HashMap::new());
118 static DRAG_REGIONS: RefCell<HashSet<usize>> = RefCell::new(HashSet::new());
121 static TEXT_FIELD_NODE: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
125 static TEXT_FIELD_ECHO: RefCell<HashMap<u64, String>> = RefCell::new(HashMap::new());
130 static NAV_MENU_ROWS: RefCell<HashMap<usize, (usize, usize)>> = RefCell::new(HashMap::new());
132 static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
134 static NAV_PAGE_IDS: RefCell<HashMap<usize, NodeId>> = RefCell::new(HashMap::new());
136 static NAV_HOST_BY_ID: RefCell<HashMap<u64, *mut c_void>> = RefCell::new(HashMap::new());
138 static PENDING_SPLIT_NAV: Cell<*mut c_void> = const { Cell::new(std::ptr::null_mut()) };
141 static NAV_MENU_HOST: RefCell<HashMap<usize, *mut c_void>> = RefCell::new(HashMap::new());
143 static SPLIT_SIDEBAR_PAGES: RefCell<HashSet<usize>> = RefCell::new(HashSet::new());
145 static SCROLL_STATE: RefCell<HashMap<usize, *mut c_void>> = RefCell::new(HashMap::new());
147 static GESTURES: RefCell<HashSet<(usize, c_int)>> = RefCell::new(HashSet::new());
149 static CANVASES: RefCell<HashSet<usize>> = RefCell::new(HashSet::new());
153
154 static INSPECTOR_STATE: RefCell<HashMap<usize, XamlInspector>> = RefCell::new(HashMap::new());
156 static INSPECTOR_PANE_IDS: RefCell<HashMap<usize, (NodeId, bool)>> =
158 RefCell::new(HashMap::new());
159 static INSPECTOR_PANES_BY_HOST: RefCell<HashMap<u64, InspectorPaneNodes>> =
162 RefCell::new(HashMap::new());
163
164 static RESOLVED: RefCell<HashMap<&'static str, Option<CString>>> =
165 RefCell::new(HashMap::new());
166
167 static LAST_WINDOW_SIZE: std::cell::Cell<Size> =
169 const { std::cell::Cell::new(Size::new(0.0, 0.0)) };
170 static COVERS: RefCell<Vec<(*mut c_void, NodeId)>> = const { RefCell::new(Vec::new()) };
172 static COVER_IDS: RefCell<HashMap<usize, NodeId>> = RefCell::new(HashMap::new());
174 static COVER_HALF: RefCell<std::collections::HashSet<usize>> =
177 RefCell::new(std::collections::HashSet::new());
178
179}
180
181struct SplitNav {
191 node: u64,
192 nav_view: *mut c_void,
193 content_host: *mut c_void,
194 menu_node: u64,
195 sidebar_page: Option<(*mut c_void, NodeId)>,
196 detail_pages: Vec<(*mut c_void, NodeId, String)>,
199 is_stack: bool,
202 resident: bool,
209 selected: usize,
215}
216
217enum NavState {
218 Split(SplitNav),
219}
220
221const NAV_PANE_HEADER_H: c_int = 60;
224
225fn attach_custom_sidebar() {
229 let pending = PENDING_SPLIT_NAV.with(|v| v.replace(std::ptr::null_mut()));
230 if pending.is_null() {
231 return;
232 }
233 let page = NAV_STATE.with(|m| {
234 m.borrow().values().find_map(|state| {
235 let NavState::Split(s) = state;
236 (s.nav_view == pending).then_some(s.sidebar_page).flatten()
237 })
238 });
239 if let Some((page, _)) = page {
240 SPLIT_SIDEBAR_PAGES.with(|p| p.borrow_mut().remove(&(page as usize)));
241 unsafe { ffi::day_xaml_nav_custom_sidebar(pending, page) };
242 }
243}
244
245extern "C" fn on_cover_escape(id: u64) {
248 ffi_guard::contain((), || {
249 let node = COVERS
250 .with(|c| c.borrow().last().map(|(_, node)| *node))
251 .unwrap_or(NodeId(id));
252 emit(
253 node,
254 Event::NavBack {
255 already_popped: false,
256 },
257 );
258 });
259}
260
261extern "C" fn nav_menu_changed(id: u64, index: c_int) {
262 ffi_guard::contain((), || {
266 emit(NodeId(id), Event::SelectionChanged(i64::from(index)));
267 });
268}
269
270extern "C" fn document_event(host_id: u64, kind: c_int, index: c_int, key: *const c_char) {
273 ffi_guard::contain((), || {
274 let tag = match kind {
275 0 => "day:tab-new",
276 1 => "day:tab-close",
277 _ => "day:tab-move",
278 };
279 let text = if key.is_null() {
280 String::new()
281 } else {
282 unsafe { std::ffi::CStr::from_ptr(key) }
283 .to_string_lossy()
284 .into_owned()
285 };
286 emit(
287 NodeId(host_id),
288 Event::Custom {
289 tag,
290 num: f64::from(index),
291 text,
292 },
293 );
294 });
295}
296
297extern "C" fn nav_selection(host_id: u64, index: c_int) {
298 ffi_guard::contain((), || {
299 let host = NAV_HOST_BY_ID.with(|m| m.borrow().get(&host_id).copied());
300 let Some(host) = host else { return };
301 let menu = NAV_STATE.with(|m| match m.borrow().get(&(host as usize)) {
302 Some(NavState::Split(s)) if s.menu_node != 0 => Some(s.menu_node),
303 _ => None,
304 });
305 if let Some(menu_node) = menu {
306 emit(NodeId(menu_node), Event::SelectionChanged(i64::from(index)));
307 }
308 });
309}
310
311extern "C" fn nav_region_size(host_id: u64, region: c_int, w: c_int, h: c_int) {
314 ffi_guard::contain((), || {
315 if w <= 0 || h <= 0 {
316 return;
317 }
318 let host = NAV_HOST_BY_ID.with(|m| m.borrow().get(&host_id).copied());
319 let Some(host) = host else { return };
320 let size = Size::new(f64::from(w), f64::from(h));
321 let reports: Vec<NodeId> = NAV_STATE.with(|m| {
322 let m = m.borrow();
323 let Some(NavState::Split(s)) = m.get(&(host as usize)) else {
324 return Vec::new();
325 };
326 if region == 1 {
327 s.sidebar_page.map(|(_, id)| id).into_iter().collect()
328 } else {
329 s.detail_pages.iter().map(|(_, id, _)| *id).collect()
330 }
331 });
332 for id in reports {
333 emit(id, Event::FrameChanged(size));
334 }
335 });
336}
337
338fn nav_page_content_host(host_id: u64, page: NodeId) -> Option<*mut c_void> {
343 let host = NAV_HOST_BY_ID.with(|m| m.borrow().get(&host_id).copied())?;
344 NAV_STATE.with(|m| {
345 let m = m.borrow();
346 let NavState::Split(s) = m.get(&(host as usize))?;
347 (s.node == host_id && s.detail_pages.iter().any(|(_, id, _)| *id == page))
348 .then_some(s.content_host)
349 })
350}
351
352#[cfg(test)]
353mod button_menu_tests {
354 use super::*;
355
356 fn item() -> day_spec::MenuItem {
357 day_spec::MenuItem::Action {
358 id: None,
359 action: 1,
360 label: "Open".into(),
361 shortcut: None,
362 enabled: true,
363 checked: None,
364 role: None,
365 icon: None,
366 }
367 }
368
369 #[test]
372 fn a_provider_that_releases_its_button_opens_nothing() {
373 let (node, button) = (41_u64, 0x1000_usize);
374 let provider: day_spec::ContextMenuFn = Rc::new(move |_| {
375 BUTTON_MENUS.with(|m| m.borrow_mut().retain(|_, (b, _)| *b != button));
376 vec![item()]
377 });
378 BUTTON_MENUS.with(|m| m.borrow_mut().insert(node, (button, provider)));
379 assert_eq!(button_menu_for(node), ButtonMenu::Nothing);
380 assert_eq!(button_menu_for(node), ButtonMenu::NotAMenuButton);
381 }
382
383 #[test]
386 fn a_replaced_button_is_not_the_pressed_one() {
387 let node = 42_u64;
388 let provider: day_spec::ContextMenuFn = Rc::new(move |_| {
389 let replacement: day_spec::ContextMenuFn = Rc::new(|_| Vec::new());
390 BUTTON_MENUS.with(|m| m.borrow_mut().insert(node, (0x2000, replacement)));
391 vec![item()]
392 });
393 BUTTON_MENUS.with(|m| m.borrow_mut().insert(node, (0x1000, provider)));
394 assert_eq!(button_menu_for(node), ButtonMenu::Nothing);
395 BUTTON_MENUS.with(|m| m.borrow_mut().remove(&node));
396 }
397
398 #[test]
399 fn a_live_button_shows_its_menu() {
400 let node = 43_u64;
401 let provider: day_spec::ContextMenuFn = Rc::new(|_| vec![item()]);
402 BUTTON_MENUS.with(|m| m.borrow_mut().insert(node, (0x3000, provider)));
403 std::assert_matches!(button_menu_for(node), ButtonMenu::Show(0x3000, items) if items.len() == 1);
404 BUTTON_MENUS.with(|m| m.borrow_mut().remove(&node));
405 }
406}
407
408#[cfg(test)]
409mod deferred_nav_size_tests {
410 use super::*;
411
412 fn register(host_id: u64, page: NodeId) -> *mut c_void {
414 let host = std::ptr::without_provenance_mut::<c_void>(1);
415 let content = std::ptr::without_provenance_mut::<c_void>(2);
416 NAV_HOST_BY_ID.with(|m| m.borrow_mut().insert(host_id, host));
417 NAV_STATE.with(|m| {
418 m.borrow_mut().insert(
419 host as usize,
420 NavState::Split(SplitNav {
421 node: host_id,
422 nav_view: host,
423 content_host: content,
424 menu_node: 0,
425 sidebar_page: None,
426 detail_pages: vec![(std::ptr::without_provenance_mut(3), page, String::new())],
427 is_stack: true,
428 resident: false,
429 selected: 0,
430 }),
431 );
432 });
433 content
434 }
435
436 #[test]
437 fn removed_page_does_not_receive_a_deferred_size() {
438 let content = register(10, NodeId(20));
439 assert_eq!(nav_page_content_host(10, NodeId(20)), Some(content));
440 NAV_STATE.with(|m| {
441 let mut m = m.borrow_mut();
442 let Some(NavState::Split(s)) = m.get_mut(&1) else {
443 unreachable!();
444 };
445 s.detail_pages.clear();
446 });
447 assert_eq!(nav_page_content_host(10, NodeId(20)), None);
448 NAV_STATE.with(|m| m.borrow_mut().clear());
449 NAV_HOST_BY_ID.with(|m| m.borrow_mut().clear());
450 }
451
452 #[test]
453 fn released_host_and_reused_native_address_do_not_resolve() {
454 register(10, NodeId(20));
455 NAV_STATE.with(|m| m.borrow_mut().clear());
456 NAV_HOST_BY_ID.with(|m| m.borrow_mut().remove(&10));
457 assert_eq!(nav_page_content_host(10, NodeId(20)), None);
458
459 let content = register(11, NodeId(21));
461 assert_eq!(nav_page_content_host(10, NodeId(20)), None);
462 assert_eq!(nav_page_content_host(11, NodeId(20)), None);
463 assert_eq!(nav_page_content_host(11, NodeId(21)), Some(content));
464 NAV_STATE.with(|m| m.borrow_mut().clear());
465 NAV_HOST_BY_ID.with(|m| m.borrow_mut().clear());
466 }
467}
468
469struct XamlInspector {
474 content_host: *mut c_void,
475 panel_host: *mut c_void,
476 node: u64,
477}
478
479#[derive(Default)]
481struct InspectorPaneNodes {
482 content: Option<NodeId>,
483 panel: Option<NodeId>,
484}
485
486extern "C" fn inspector_region_size(host_id: u64, region: c_int, w: c_int, h: c_int) {
489 ffi_guard::contain((), || {
490 if w <= 0 || h <= 0 {
491 return;
492 }
493 let id = INSPECTOR_PANES_BY_HOST.with(|m| {
494 m.borrow()
495 .get(&host_id)
496 .and_then(|p| if region == 1 { p.panel } else { p.content })
497 });
498 if let Some(id) = id {
499 emit(
500 id,
501 Event::FrameChanged(Size::new(f64::from(w), f64::from(h))),
502 );
503 }
504 });
505}
506
507extern "C" fn nav_back(host_id: u64) {
509 ffi_guard::contain((), || {
510 emit(
511 NodeId(host_id),
512 Event::NavBack {
513 already_popped: false,
514 },
515 );
516 });
517}
518
519fn stack_sync(host: *mut c_void) {
522 NAV_STATE.with(|m| {
523 if let Some(NavState::Split(s)) = m.borrow().get(&(host as usize)) {
524 let last = s.detail_pages.len().saturating_sub(1);
525 for (i, (page, _, _)) in s.detail_pages.iter().enumerate() {
526 unsafe { ffi::day_xaml_set_visible(*page, c_int::from(i == last)) };
527 }
528 unsafe {
529 ffi::day_xaml_nav_set_back_visible(
530 s.nav_view,
531 c_int::from(s.detail_pages.len() >= 2),
532 );
533 };
534 if let Some((_, _, title)) = s.detail_pages.last() {
537 unsafe { ffi::day_xaml_nav_set_header(s.nav_view, cstr(title).as_ptr()) };
538 }
539 }
540 });
541}
542
543fn select_sync(host: *mut c_void) {
548 let pages: Vec<(*mut c_void, bool)> = NAV_STATE.with(|m| {
554 match m.borrow().get(&(host as usize)) {
555 Some(NavState::Split(s)) if !s.detail_pages.is_empty() => {
556 let shown = s.selected.min(s.detail_pages.len() - 1);
559 s.detail_pages
560 .iter()
561 .enumerate()
562 .map(|(i, (page, _, _))| (*page, i == shown))
563 .collect()
564 }
565 _ => Vec::new(),
566 }
567 });
568 for (page, visible) in pages {
569 unsafe { ffi::day_xaml_set_visible(page, c_int::from(visible)) };
570 }
571}
572
573pub fn emit(id: NodeId, ev: Event) {
575 let sink = SINK.with(|s| s.borrow().clone());
576 if let Some(sink) = sink {
577 sink(id, ev);
578 }
579}
580
581fn apply_button_content(
582 h: *mut c_void,
583 title: &str,
584 icon: Option<&day_spec::Icon>,
585 icon_only: bool,
586) {
587 let (glyph, name, geometry) = match icon {
588 Some(day_spec::Icon::Symbol(s)) => (toolbar::glyph_for(*s), String::new(), String::new()),
589 Some(day_spec::Icon::Image(name)) => {
590 ("", name.clone(), vector_geometry(name).unwrap_or_default())
591 }
592 None => ("", String::new(), String::new()),
593 };
594 unsafe {
595 ffi::day_xaml_button_set_content(
596 h,
597 cstr(title).as_ptr(),
598 cstr(glyph).as_ptr(),
599 cstr(&name).as_ptr(),
600 cstr(&geometry).as_ptr(),
601 c_int::from(icon_only),
602 );
603 };
604}
605
606fn apply_button_style(h: *mut c_void, style: day_spec::props::ButtonStyleSpec) {
610 use day_spec::props::ButtonStyleSpec as S;
611 let (kind, tint) = match style {
612 S::Automatic | S::Compact => (0, day_spec::Ink::CLEAR),
614 S::Bordered => (1, day_spec::Ink::CLEAR),
615 S::Prominent => (2, day_spec::Ink::CLEAR),
616 S::Tinted(c) => (3, c),
617 S::Plain => (4, day_spec::Ink::CLEAR),
619 };
620 paint_inks(
622 h,
623 InkSlot::ButtonTint,
624 tint.is_dynamic(),
625 move |h, palette| {
626 let fill = tint.resolve(palette);
627 unsafe {
630 ffi::day_xaml_button_set_style(h, kind, argb(fill), argb(S::on_tint(fill)));
631 };
632 },
633 );
634}
635
636struct Elided {
643 full: String,
644 mode: day_spec::props::Truncation,
645 width: f64,
646}
647
648fn apply_paragraph(
652 h: *mut c_void,
653 wraps: bool,
654 para: &day_spec::props::LabelParagraph,
655 text: &str,
656 plain: bool,
657) {
658 unsafe {
659 ffi::day_xaml_label_set_paragraph(
660 h,
661 c_int::from(wraps),
662 c_int::try_from(para.max_lines).unwrap_or(c_int::MAX),
663 para.letter_spacing,
664 para.line_height,
665 );
666 }
667 let one_line = !wraps || para.max_lines == 1;
668 let elides = plain && one_line && para.truncation != day_spec::props::Truncation::Tail;
669 let key = h as usize;
670 if elides {
671 let width = LABEL_ELIDE.with(|m| {
672 let mut m = m.borrow_mut();
673 let e = m.entry(key).or_insert_with(|| Elided {
674 full: text.to_owned(),
675 mode: para.truncation,
676 width: 0.0,
677 });
678 e.mode = para.truncation;
679 text.clone_into(&mut e.full);
680 e.width
681 });
682 if width > 0.0 {
683 elide_label(h, width);
684 }
685 } else if LABEL_ELIDE.with(|m| m.borrow_mut().remove(&key)).is_some() {
686 let whole = cstr(text);
688 unsafe { ffi::day_xaml_label_show_elided(h, whole.as_ptr(), whole.as_ptr()) };
689 }
690}
691
692fn elide_label(h: *mut c_void, width: f64) {
694 let Some((full, mode)) = LABEL_ELIDE.with(|m| {
695 let mut m = m.borrow_mut();
696 let e = m.get_mut(&(h as usize))?;
697 e.width = width;
698 Some((e.full.clone(), e.mode))
699 }) else {
700 return;
701 };
702 let shown = day_spec::elide(&full, mode, width, |s| unsafe {
703 ffi::day_xaml_label_text_width(h, cstr(s).as_ptr())
704 });
705 unsafe { ffi::day_xaml_label_show_elided(h, cstr(&shown).as_ptr(), cstr(&full).as_ptr()) };
706}
707
708fn note_label_text(h: *mut c_void, text: &str) {
711 if let Some(node) = LABEL_NODE.with(|m| m.borrow().get(&(h as usize)).copied()) {
712 LABEL_TEXT.with(|m| {
713 if let Some(t) = m.borrow_mut().get_mut(&node) {
714 text.clone_into(t);
715 }
716 });
717 }
718 let width = LABEL_ELIDE.with(|m| {
719 m.borrow_mut().get_mut(&(h as usize)).map(|e| {
720 text.clone_into(&mut e.full);
721 e.width
722 })
723 });
724 if let Some(width) = width
725 && width > 0.0
726 {
727 elide_label(h, width);
728 }
729}
730
731fn label_text_of(h: *mut c_void) -> (String, bool) {
733 if let Some(full) = LABEL_ELIDE.with(|m| m.borrow().get(&(h as usize)).map(|e| e.full.clone()))
734 {
735 return (full, true);
736 }
737 let text = unsafe {
739 let p = ffi::day_xaml_label_text(h);
740 if p.is_null() {
741 String::new()
742 } else {
743 let s = CStr::from_ptr(p).to_string_lossy().into_owned();
744 ffi::day_xaml_string_free(p);
745 s
746 }
747 };
748 (
749 text,
750 !LABEL_RUNS.with(|m| m.borrow().contains(&(h as usize))),
751 )
752}
753
754fn label_align_code(align: day_spec::props::TextAlign) -> c_int {
757 let rtl = day_core::layout_direction() == day_spec::LayoutDirection::Rtl;
758 match align {
759 day_spec::props::TextAlign::Center => 1,
760 day_spec::props::TextAlign::Trailing => {
761 if rtl {
762 0
763 } else {
764 2
765 }
766 }
767 day_spec::props::TextAlign::Leading => {
768 if rtl {
769 2
770 } else {
771 0
772 }
773 }
774 day_spec::props::TextAlign::Justified => 3,
775 }
776}
777
778fn apply_label_features(h: *mut c_void, f: day_spec::FontSpec) {
780 unsafe {
781 ffi::day_xaml_label_set_features(
782 h,
783 c_int::from(f.small_caps),
784 c_int::from(f.oldstyle_figures),
785 );
786 }
787}
788
789extern "C" fn on_label_selection(id: u64, start: c_int, end: c_int) {
793 ffi_guard::contain((), || {
794 let text = LABEL_TEXT
795 .with(|m| m.borrow().get(&id).cloned())
796 .unwrap_or_default();
797 let to_byte = |units: c_int| utf16_to_byte(&text, usize::try_from(units).unwrap_or(0));
798 emit(
799 NodeId(id),
800 Event::TextSelected {
801 start: to_byte(start),
802 end: to_byte(end),
803 },
804 );
805 });
806}
807
808fn utf16_to_byte(text: &str, units: usize) -> usize {
811 let mut seen = 0usize;
812 for (byte, ch) in text.char_indices() {
813 if seen >= units {
814 return byte;
815 }
816 seen += ch.len_utf16();
817 }
818 text.len()
819}
820
821#[cfg(test)]
822mod label_text_tests {
823 use super::*;
824
825 #[test]
826 fn utf16_offsets_land_on_char_boundaries() {
827 let text = "a\u{e9}\u{1f600}b";
828 assert_eq!(utf16_to_byte(text, 0), 0);
829 assert_eq!(utf16_to_byte(text, 1), 1);
830 assert_eq!(utf16_to_byte(text, 2), 3);
831 assert_eq!(utf16_to_byte(text, 4), 7);
833 assert_eq!(utf16_to_byte(text, 5), 8);
834 assert_eq!(utf16_to_byte(text, 99), 8);
835 }
836
837 #[test]
838 fn justified_has_its_own_code() {
839 assert_eq!(label_align_code(day_spec::props::TextAlign::Justified), 3);
840 assert_eq!(label_align_code(day_spec::props::TextAlign::Center), 1);
841 }
842}
843
844fn keep_image_tint(h: *mut c_void, tint: Option<day_spec::Ink>) {
846 let ink = tint.unwrap_or(day_spec::Ink::CLEAR);
847 keep_inks(
848 h,
849 InkSlot::ImageTint,
850 ink.is_dynamic(),
851 move |h, palette| {
852 unsafe { ffi::day_xaml_image_retint(h, ink_argb(ink, palette)) };
854 },
855 );
856}
857
858fn paint_label_color(h: *mut c_void, ink: day_spec::Ink) {
860 paint_inks(
861 h,
862 InkSlot::LabelColor,
863 ink.is_dynamic(),
864 move |h, palette| {
865 unsafe { ffi::day_xaml_label_set_color(h, ink_argb(ink, palette)) };
867 },
868 );
869}
870
871fn set_label_runs(h: *mut c_void, node: u64, text: &str, runs: &[day_spec::TextRun]) {
873 let dynamic = runs.iter().any(|r| {
874 r.color.is_some_and(day_spec::Ink::is_dynamic)
875 || r.background.is_some_and(day_spec::Ink::is_dynamic)
876 });
877 if dynamic {
878 let (text, runs) = (text.to_owned(), runs.to_vec());
879 paint_inks(h, InkSlot::LabelRuns, true, move |h, palette| {
880 apply_label_runs(h, node, &text, &runs, palette);
881 });
882 } else {
883 keep_inks(h, InkSlot::LabelRuns, false, |_, _| {});
884 apply_label_runs(h, node, text, runs, &day_spec::Palette::current());
885 }
886}
887
888fn apply_label_runs(
890 h: *mut c_void,
891 node: u64,
892 text: &str,
893 runs: &[day_spec::TextRun],
894 palette: &day_spec::Palette,
895) {
896 LABEL_RUNS.with(|m| {
897 if runs.is_empty() {
898 m.borrow_mut().remove(&(h as usize));
899 } else {
900 m.borrow_mut().insert(h as usize);
901 }
902 });
903 if runs.is_empty() {
904 unsafe { ffi::day_xaml_label_set_text(h, cstr(text).as_ptr()) };
907 return;
908 }
909 unsafe { ffi::day_xaml_label_runs_begin(h, node) };
910 let mut at = 0usize;
911 let add = |slice: &str, run: Option<&day_spec::TextRun>| {
912 let mut flags = 0i32;
913 let mut argb = 0u32;
914 let mut bg_argb = 0u32;
915 let mut scale_permille = 1000i32;
916 let mut link = String::new();
917 if let Some(r) = run {
918 scale_permille = (r.font.scale * 1000.0).round() as i32;
919 if r.font
920 .weight
921 .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
922 {
923 flags |= 1;
924 }
925 if r.font.italic {
926 flags |= 2;
927 }
928 if r.font.monospace {
929 flags |= 4;
930 }
931 if r.strikethrough.is_some() {
932 flags |= 8;
933 }
934 if let Some(c) = r.color.map(|c| c.resolve(palette)) {
935 flags |= 16;
936 let f = |v: f64| (v.clamp(0.0, 1.0) * 255.0) as u32;
937 argb = (f(c.a) << 24) | (f(c.r) << 16) | (f(c.g) << 8) | f(c.b);
938 }
939 let pack = |c: day_spec::Color| {
940 let f = |v: f64| (v.clamp(0.0, 1.0) * 255.0) as u32;
941 (f(c.a) << 24) | (f(c.r) << 16) | (f(c.g) << 8) | f(c.b)
942 };
943 if let Some(c) = r.background.map(|c| c.resolve(palette)) {
944 flags |= 32;
945 bg_argb = pack(c);
946 }
947 if r.underline.is_some() {
948 flags |= 64;
949 }
950 if r.font.small_caps {
951 flags |= 128;
952 }
953 if r.font.oldstyle_figures {
954 flags |= 256;
955 }
956 if let Some(u) = r.link.as_deref() {
957 link = u.to_string();
958 }
959 }
960 unsafe {
961 ffi::day_xaml_label_runs_add(
962 h,
963 cstr(slice).as_ptr(),
964 flags,
965 argb,
966 bg_argb,
967 scale_permille,
968 cstr(&link).as_ptr(),
969 );
970 };
971 };
972 for r in runs {
973 let Some(styled) = text.get(r.range.clone()) else {
974 continue;
975 };
976 if r.range.start > at
977 && let Some(plain) = text.get(at..r.range.start)
978 {
979 add(plain, None);
980 }
981 add(styled, Some(r));
982 at = r.range.end;
983 }
984 if let Some(tail) = text.get(at..) {
985 add(tail, None);
986 }
987}
988
989thread_local! {
990 static BITMAP_INFO: std::cell::RefCell<std::collections::HashMap<u64, day_spec::BitmapInfo>> =
993 std::cell::RefCell::new(std::collections::HashMap::new());
994}
995
996fn cstr(s: &str) -> CString {
997 CString::new(s).unwrap_or_else(|_| CString::new(s.replace('\0', "")).unwrap_or_default())
1000}
1001
1002extern "C" fn on_link(id: u64, url: *const c_char) {
1005 ffi_guard::contain((), || {
1006 let url = unsafe { CStr::from_ptr(url) }
1007 .to_string_lossy()
1008 .into_owned();
1009 emit(NodeId(id), Event::LinkActivated(url));
1010 });
1011}
1012
1013thread_local! {
1014 static BUTTON_MENUS: RefCell<HashMap<u64, (usize, day_spec::ContextMenuFn)>> =
1018 RefCell::new(HashMap::new());
1019}
1020
1021#[derive(Debug, PartialEq)]
1023enum ButtonMenu {
1024 NotAMenuButton,
1026 Nothing,
1028 Show(usize, Vec<day_spec::MenuItem>),
1030}
1031
1032fn button_menu_for(id: u64) -> ButtonMenu {
1037 let Some((button, f)) = BUTTON_MENUS.with(|m| m.borrow().get(&id).cloned()) else {
1038 return ButtonMenu::NotAMenuButton;
1039 };
1040 let still_registered =
1041 || BUTTON_MENUS.with(|m| m.borrow().get(&id).is_some_and(|(b, _)| *b == button));
1042 match day_spec::resolve_button_menu(&f, still_registered) {
1043 Some(items) => ButtonMenu::Show(button, items),
1044 None => ButtonMenu::Nothing,
1045 }
1046}
1047
1048extern "C" fn on_press(id: u64) {
1049 ffi_guard::contain((), || {
1050 match button_menu_for(id) {
1053 ButtonMenu::NotAMenuButton => emit(NodeId(id), Event::Pressed),
1054 ButtonMenu::Nothing => {}
1055 ButtonMenu::Show(button, items) => {
1056 let mut spec = String::new();
1057 serialize_menu_xaml(&items, &mut spec);
1058 unsafe {
1062 ffi::day_xaml_show_button_menu(button as *mut c_void, cstr(&spec).as_ptr());
1063 };
1064 }
1065 }
1066 });
1067}
1068extern "C" fn on_toggle(id: u64, on: c_int) {
1069 ffi_guard::contain((), || emit(NodeId(id), Event::ToggleChanged(on != 0)));
1070}
1071extern "C" fn on_text(id: u64, s: *const c_char) {
1072 ffi_guard::contain((), || {
1073 let text = unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned();
1074 let echo = TEXT_FIELD_ECHO.with(|m| {
1076 let mut m = m.borrow_mut();
1077 if m.get(&id) == Some(&text) {
1078 return true;
1079 }
1080 m.remove(&id);
1081 false
1082 });
1083 if echo {
1084 return;
1085 }
1086 emit(NodeId(id), Event::TextChanged(text));
1087 });
1088}
1089extern "C" fn on_slider(id: u64, v: f64, committed: c_int) {
1090 ffi_guard::contain((), || {
1094 emit(NodeId(id), Event::ValueChanged(v));
1095 if committed != 0 {
1096 emit(NodeId(id), Event::ValueCommitted(v));
1097 }
1098 });
1099}
1100#[cfg(feature = "winui")]
1104extern "C" fn on_key_handled(id: u64) -> c_int {
1105 ffi_guard::contain(0, || c_int::from(day_spec::keys::handled(NodeId(id))))
1106}
1107
1108#[cfg(feature = "winui")]
1111extern "C" fn on_text_handled(id: u64) -> c_int {
1112 ffi_guard::contain(0, || c_int::from(day_spec::keys::text(NodeId(id))))
1113}
1114
1115#[cfg(feature = "winui")]
1120extern "C" fn on_key(id: u64, key: *const c_char, text: *const c_char, modifiers: c_int) {
1121 ffi_guard::contain((), || {
1122 if key.is_null() {
1123 return;
1124 }
1125 let read = |p: *const c_char| unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned();
1127 let key = read(key);
1128 let phase = day_spec::KeyPhase::from_wire(f64::from(modifiers));
1130 let modifiers = (modifiers & 0xff) as u8;
1131 let event = if text.is_null() {
1132 day_spec::KeyEvent::named(key, modifiers)
1133 } else {
1134 day_spec::KeyEvent::typed_by(key, read(text), modifiers)
1135 };
1136 emit(NodeId(id), Event::Key(event.with_phase(phase)));
1137 });
1138}
1139
1140extern "C" fn on_field_key(id: u64, name: *const c_char, modifiers: c_int) -> c_int {
1144 ffi_guard::contain(0, || {
1145 if name.is_null() {
1146 return 0;
1147 }
1148 let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();
1150 let node = NodeId(id);
1151 let phase = day_spec::KeyPhase::from_wire(f64::from(modifiers));
1152 let mods = (modifiers & 0xff) as u8;
1153 if phase != day_spec::KeyPhase::Up && !day_spec::keys::field_claims(node, &name, mods) {
1155 return 0;
1156 }
1157 emit(
1158 node,
1159 Event::Key(day_spec::KeyEvent::named(name, 0).with_phase(phase)),
1160 );
1161 1
1162 })
1163}
1164
1165extern "C" fn on_focus(id: u64, kind: c_int) {
1167 ffi_guard::contain((), || {
1168 let ev = match kind {
1169 2 => Event::Submitted,
1170 k => Event::FocusChanged(k != 0),
1171 };
1172 emit(NodeId(id), ev);
1173 });
1174}
1175
1176fn progress_ticks(fraction: f64) -> c_int {
1178 (fraction.clamp(0.0, 1.0) * 1000.0).round() as c_int
1179}
1180
1181#[distributed_slice]
1183pub static RENDERERS: [fn() -> Renderer<Xaml>];
1184
1185struct XamlWin {
1188 win: *mut c_void,
1189 content: *mut c_void,
1190 menuless: bool,
1194}
1195
1196pub struct Xaml {
1197 registry: Registry<Xaml>,
1198 window: *mut c_void,
1199 secondary: Vec<XamlWin>,
1200 menu_spec: String,
1203 primary_root: *mut c_void,
1207}
1208
1209impl Xaml {
1210 fn window_token(&self, h: &WinHandle) -> Option<*mut c_void> {
1214 if let Some(w) = self.secondary.iter().find(|w| w.content == h.0) {
1215 return Some(w.win);
1216 }
1217 (!self.window.is_null()).then_some(self.window)
1218 }
1219}
1220
1221impl Xaml {
1222 #[must_use]
1223 pub fn new() -> Self {
1224 let mut registry = Registry::default();
1225 for f in RENDERERS {
1226 registry.register(f());
1227 }
1228 Xaml {
1236 registry,
1237 window: std::ptr::null_mut(),
1238 secondary: Vec::new(),
1239 menu_spec: String::new(),
1240 primary_root: std::ptr::null_mut(),
1241 }
1242 }
1243}
1244
1245impl Default for Xaml {
1246 fn default() -> Self {
1247 Self::new()
1248 }
1249}
1250
1251fn xaml_style(f: Font) -> (f64, day_spec::FontWeight) {
1262 use day_spec::FontWeight::{Regular, Semibold};
1263 match f {
1264 Font::LargeTitle => (28.0, Semibold), Font::Title => (20.0, Semibold), Font::Title2 => (18.0, Regular), Font::Title3 => (16.0, Semibold),
1268 Font::Headline => (14.0, Semibold), Font::Subheadline | Font::Footnote | Font::Caption => (12.0, Regular), Font::Body => (14.0, Regular), Font::Callout => (13.0, Regular),
1272 Font::Caption2 => (11.0, Regular),
1273 Font::System(pt) | Font::Custom(_, pt) => (pt, Regular),
1274 }
1275}
1276
1277fn apply_custom_family(h: *mut c_void, spec: day_spec::FontSpec) {
1285 let Font::Custom(family, _) = spec.style else {
1286 return;
1287 };
1288
1289 RESOLVED.with(|cache| {
1290 let mut cache = cache.borrow_mut();
1291 let entry = cache.entry(family).or_insert_with(|| {
1292 if let Some(file) = day_spec::fonts::resolve_font_file(family)
1293 .as_deref()
1294 .and_then(|p| p.file_name())
1295 .and_then(|n| n.to_str())
1296 {
1297 Some(cstr(&format!("ms-appx:///fonts/{file}#{family}")))
1298 } else {
1299 log::warn!(
1300 "unknown font family {family:?} — falling back to the system font \
1301 (is the file in the project's fonts/ directory?)"
1302 );
1303 None
1304 }
1305 });
1306 if let Some(s) = entry {
1307 unsafe { ffi::day_xaml_label_set_font_family(h, s.as_ptr()) };
1308 }
1309 });
1310}
1311
1312#[cfg(feature = "winui")]
1316fn win2d_font_family(path: &std::path::Path, family: &str) -> Option<String> {
1317 use std::os::windows::ffi::OsStrExt;
1318
1319 #[link(name = "shlwapi")]
1320 unsafe extern "system" {
1321 fn UrlCreateFromPathW(path: *const u16, url: *mut u16, len: *mut u32, flags: u32) -> i32;
1322 }
1323
1324 let path = std::path::absolute(path).ok()?;
1325 let path = path.to_str()?;
1326 let path = if let Some(unc) = path.strip_prefix(r"\\?\UNC\") {
1328 format!(r"\\{unc}")
1329 } else {
1330 path.strip_prefix(r"\\?\").unwrap_or(path).to_string()
1331 };
1332 let path: Vec<u16> = std::ffi::OsStr::new(&path)
1333 .encode_wide()
1334 .chain(Some(0))
1335 .collect();
1336 let mut url = vec![0u16; path.len() * 3 + 16];
1337 let mut len = u32::try_from(url.len()).ok()?;
1338 let hr = unsafe { UrlCreateFromPathW(path.as_ptr(), url.as_mut_ptr(), &raw mut len, 0) };
1339 if hr < 0 {
1340 return None;
1341 }
1342 let uri = String::from_utf16(&url[..len as usize]).ok()?;
1343 Some(format!("{uri}#{family}"))
1344}
1345
1346#[cfg(all(test, feature = "winui"))]
1347#[test]
1348fn win2d_font_paths_are_windows_file_uris() {
1349 for (path, expected) in [
1350 (
1351 r"C:\Font fixtures\é #100%.ttf",
1352 "file:///C:/Font%20fixtures/%E9%20%23100%25.ttf#Pacifico",
1353 ),
1354 (
1355 r"\\server\fonts\Pacifico.ttf",
1356 "file://server/fonts/Pacifico.ttf#Pacifico",
1357 ),
1358 (
1359 r"\\?\C:\fonts\Pacifico.ttf",
1360 "file:///C:/fonts/Pacifico.ttf#Pacifico",
1361 ),
1362 (
1363 r"\\?\UNC\server\fonts\Pacifico.ttf",
1364 "file://server/fonts/Pacifico.ttf#Pacifico",
1365 ),
1366 ] {
1367 assert_eq!(
1368 win2d_font_family(std::path::Path::new(path), "Pacifico").as_deref(),
1369 Some(expected)
1370 );
1371 }
1372}
1373
1374fn canvas_family(family: &str) -> String {
1378 thread_local! {
1379 static CANVAS_FAMILIES: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
1380 }
1381 CANVAS_FAMILIES.with(|cache| {
1382 cache
1383 .borrow_mut()
1384 .entry(family.to_string())
1385 .or_insert_with(|| {
1386 let Some(path) = day_spec::fonts::resolve_font_file(family) else {
1387 return family.to_string();
1388 };
1389 #[cfg(feature = "winui")]
1390 {
1391 win2d_font_family(&path, family).unwrap_or_else(|| family.to_string())
1392 }
1393 #[cfg(not(feature = "winui"))]
1394 {
1395 path.file_name()
1396 .and_then(|n| n.to_str())
1397 .map(|file| format!("ms-appx:///fonts/{file}#{family}"))
1398 .unwrap_or_else(|| family.to_string())
1399 }
1400 })
1401 .clone()
1402 })
1403}
1404
1405fn resolve_canvas_fonts(ops: &[DrawOp]) -> Vec<DrawOp> {
1408 ops.iter()
1409 .cloned()
1410 .map(|op| match op {
1411 DrawOp::Text {
1412 text,
1413 at,
1414 size,
1415 color,
1416 anchor,
1417 font,
1418 } if font.family.is_some() => DrawOp::Text {
1419 text,
1420 at,
1421 size,
1422 color,
1423 anchor,
1424 font: day_spec::CanvasFont {
1425 family: font.family.as_deref().map(canvas_family),
1426 weight: font.weight,
1427 italic: font.italic,
1428 },
1429 },
1430 op => op,
1431 })
1432 .collect()
1433}
1434
1435fn stage_bundled_fonts() {
1441 let Some(dir) = std::env::current_exe()
1442 .ok()
1443 .and_then(|exe| exe.parent().map(|d| d.join("fonts")))
1444 else {
1445 return;
1446 };
1447 for src in day_spec::fonts::bundled_fonts() {
1448 let Some(dst) = src.file_name().map(|n| dir.join(n)) else {
1449 continue;
1450 };
1451 if src == dst {
1452 continue; }
1454 if let Err(e) =
1455 std::fs::create_dir_all(&dir).and_then(|()| std::fs::copy(&src, &dst).map(|_| ()))
1456 {
1457 log::warn!(
1458 "day-toolkit-winui: could not stage bundled font {}: {e}",
1459 src.display()
1460 );
1461 }
1462 }
1463}
1464
1465fn stage_bundled_images() {
1472 let Some(dst_dir) = std::env::current_exe()
1473 .ok()
1474 .and_then(|exe| exe.parent().map(|d| d.join("images")))
1475 else {
1476 return;
1477 };
1478 let src_dirs: Vec<std::path::PathBuf> = ["DAY_IMAGE_ROOT", "DAY_VECTOR_RASTER_ROOT"]
1479 .iter()
1480 .filter_map(|var| std::env::var_os(var).map(std::path::PathBuf::from))
1481 .collect();
1482 for src_dir in src_dirs {
1483 let Ok(entries) = std::fs::read_dir(&src_dir) else {
1484 continue;
1485 };
1486 for entry in entries.flatten() {
1487 let src = entry.path();
1488 if !src.is_file() {
1489 continue;
1490 }
1491 let Some(dst) = src.file_name().map(|n| dst_dir.join(n)) else {
1492 continue;
1493 };
1494 if src == dst {
1495 continue;
1496 }
1497 let _ = std::fs::create_dir_all(&dst_dir)
1498 .and_then(|()| std::fs::copy(&src, &dst).map(|_| ()));
1499 }
1500 }
1501}
1502
1503fn xaml_weight(w: day_spec::FontWeight) -> c_int {
1505 use day_spec::FontWeight as W;
1506 match w {
1507 W::Thin => 100,
1508 W::UltraLight => 200,
1509 W::Light => 300,
1510 W::Regular => 400,
1511 W::Medium => 500,
1512 W::Semibold => 600,
1513 W::Bold => 700,
1514 W::Heavy => 800,
1515 W::Black => 900,
1516 }
1517}
1518
1519fn font_params(spec: day_spec::FontSpec) -> (f64, c_int, c_int, c_int) {
1521 let (pt, inherent) = xaml_style(spec.style);
1522 let weight = xaml_weight(spec.weight.unwrap_or(inherent));
1523 (
1524 pt,
1525 weight,
1526 c_int::from(spec.italic),
1527 c_int::from(spec.tabular),
1528 )
1529}
1530
1531fn natural(h: *mut c_void) -> Size {
1533 let mut w = 0.0;
1534 let mut hh = 0.0;
1535 unsafe { ffi::day_xaml_measure(h, -1.0, -1.0, &raw mut w, &raw mut hh) };
1536 Size::new(w, hh)
1537}
1538
1539extern "C" fn on_menu_action(id: u64) {
1542 ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::MenuAction(id)));
1543}
1544
1545#[must_use]
1548pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
1549 phase.is_universal()
1550}
1551
1552extern "C" fn on_lifecycle(code: c_int) {
1554 use day_spec::Lifecycle::{DidBecomeActive, WillResignActive, WillTerminate};
1555 ffi_guard::contain((), || {
1556 let phase = match code {
1557 2 => DidBecomeActive,
1558 3 => WillResignActive,
1559 7 => WillTerminate,
1560 _ => return,
1561 };
1562 emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase));
1563 });
1564}
1565
1566fn win_role_label(role: day_spec::MenuRole) -> String {
1567 use day_spec::MenuRole::{
1568 About, CheckForUpdates, CloseWindow, Copy, Cut, Delete, Fullscreen, Minimize, NewWindow,
1569 Paste, Preferences, Quit, Redo, SelectAll, Undo,
1570 };
1571 match role {
1572 Cut => "Cut",
1573 Copy => "Copy",
1574 Paste => "Paste",
1575 SelectAll => "Select All",
1576 Undo => "Undo",
1577 Redo => "Redo",
1578 Delete => "Delete",
1579 About => "About",
1580 Quit => "Exit",
1581 Preferences => "Settings",
1582 Minimize => "Minimize",
1583 CloseWindow => "Close",
1584 Fullscreen => "Full Screen",
1585 NewWindow => "New Window",
1586 CheckForUpdates => "Check for Updates…",
1587 }
1588 .to_string()
1589}
1590
1591fn win_role_keymods(role: day_spec::MenuRole) -> (i32, i32) {
1593 use day_spec::MenuRole::{CloseWindow, Copy, Cut, NewWindow, Paste, Redo, SelectAll, Undo};
1594 match role {
1595 Cut => (i32::from(b'X'), 1),
1596 Copy => (i32::from(b'C'), 1),
1597 Paste => (i32::from(b'V'), 1),
1598 SelectAll => (i32::from(b'A'), 1),
1599 Undo => (i32::from(b'Z'), 1),
1600 Redo => (i32::from(b'Y'), 1),
1601 NewWindow => (i32::from(b'N'), 1),
1602 CloseWindow => (i32::from(b'W'), 1),
1603 _ => (0, 0),
1604 }
1605}
1606
1607fn win_mods(sc: &day_spec::Shortcut) -> i32 {
1608 let mut m = 0;
1609 if sc.primary || sc.control {
1610 m |= 1; }
1612 if sc.shift {
1613 m |= 2;
1614 }
1615 if sc.alt {
1616 m |= 4;
1617 }
1618 m
1619}
1620
1621fn win_keycode(key: &str) -> i32 {
1623 let mut chars = key.chars();
1624 if let (Some(c), None) = (chars.next(), chars.clone().next()) {
1625 if c.is_ascii_alphabetic() {
1626 return c.to_ascii_uppercase() as i32;
1627 }
1628 if c.is_ascii_digit() {
1629 return c as i32;
1630 }
1631 return match c {
1632 ',' => 0xBC,
1633 '.' => 0xBE,
1634 '-' => 0xBD,
1635 '=' => 0xBB,
1636 '/' => 0xBF,
1637 _ => 0,
1638 };
1639 }
1640 match key {
1641 "Return" | "Enter" => 0x0D,
1642 "Delete" | "Del" => 0x2E,
1643 "Space" => 0x20,
1644 "Escape" | "Esc" => 0x1B,
1645 "Tab" => 0x09,
1646 "Backspace" | "Back" => 0x08,
1647 "Left" => 0x25,
1648 "Up" => 0x26,
1649 "Right" => 0x27,
1650 "Down" => 0x28,
1651 "Home" => 0x24,
1652 "End" => 0x23,
1653 _ => key
1654 .strip_prefix('F')
1655 .and_then(|n| n.parse::<i32>().ok())
1656 .filter(|n| (1..=12).contains(n))
1657 .map_or(0, |n| 0x70 + (n - 1)),
1658 }
1659}
1660
1661fn serialize_menu_xaml(items: &[day_spec::MenuItem], out: &mut String) {
1666 fn clean(s: &str) -> String {
1667 s.replace(['\t', '\n'], " ")
1668 }
1669 for item in items {
1670 match item {
1671 day_spec::MenuItem::Separator => out.push_str("-\t0\t-1\t0\t0\t1\t\n"),
1672 day_spec::MenuItem::Submenu { label, items, .. } => {
1673 let _ = writeln!(out, "S\t0\t-1\t0\t0\t1\t{}", clean(label));
1674 serialize_menu_xaml(items, out);
1675 out.push_str("E\t0\t-1\t0\t0\t1\t\n");
1676 }
1677 day_spec::MenuItem::Action {
1678 action,
1679 label,
1680 shortcut,
1681 enabled,
1682 checked,
1683 role,
1684 icon,
1685 ..
1686 } => {
1687 let en = i32::from(*enabled);
1688 let text = match role {
1691 Some(r) if label.is_empty() => win_role_label(*r),
1692 _ => clean(label),
1693 };
1694 let (key, mods) = match (shortcut, role) {
1695 (Some(sc), _) => (win_keycode(&sc.key), win_mods(sc)),
1696 (None, Some(r)) => win_role_keymods(*r),
1697 (None, None) => (0, 0),
1698 };
1699 let glyph = match icon {
1710 Some(day_spec::Icon::Symbol(s)) => toolbar::glyph_for(*s),
1711 _ => "",
1712 };
1713 let chk = checked.map_or(-1, i32::from);
1715 match role {
1716 Some(r) if *action == 0 => {
1717 let _ = writeln!(
1718 out,
1719 "R\t0\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
1720 *r as i32,
1721 key,
1722 mods,
1723 en,
1724 clean(&text),
1725 glyph,
1726 chk
1727 );
1728 }
1729 _ => {
1730 let _ = writeln!(
1731 out,
1732 "A\t{}\t-1\t{}\t{}\t{}\t{}\t{}\t{}",
1733 action,
1734 key,
1735 mods,
1736 en,
1737 clean(&text),
1738 glyph,
1739 chk
1740 );
1741 }
1742 }
1743 }
1744 }
1745 }
1746}
1747
1748fn warn_missing_renderer(kind: PieceKind) {
1753 day_spec::placeholder::report(kind, "xaml");
1754}
1755
1756pub(crate) fn placeholder_handle(kind: PieceKind) -> WinHandle {
1759 WinHandle(unsafe { ffi::day_xaml_label_new(cstr(&format!("⟨{kind}⟩")).as_ptr(), 1) })
1760}
1761
1762fn win_cursor_code(c: &Cursor) -> c_int {
1765 match c {
1766 Cursor::Default => 0,
1767 Cursor::ContextMenu | Cursor::Copy | Cursor::Alias | Cursor::ZoomIn | Cursor::ZoomOut => 1, Cursor::Text | Cursor::VerticalText => 2, Cursor::Wait => 3, Cursor::Crosshair | Cursor::Cell => 4, Cursor::NwseResize => 6, Cursor::NeswResize => 7, Cursor::EwResize | Cursor::ColResize => 8, Cursor::NsResize | Cursor::RowResize => 9, Cursor::Move => 10, Cursor::NotAllowed => 11, Cursor::Pointer | Cursor::Grab | Cursor::Grabbing => 12, Cursor::Progress => 13, Cursor::Help => 14, Cursor::None => 17,
1781 Cursor::Native(name) => match &**name {
1782 "uparrow" => 5,
1783 "appstarting" => 13,
1784 "pin" => 15,
1785 "person" => 16,
1786 _ => 0,
1787 },
1788 }
1789}
1790
1791impl Toolkit for Xaml {
1792 type Handle = WinHandle;
1793
1794 fn set_drag_source(&mut self, h: &WinHandle, source: day_spec::transfer::Source) {
1795 transfer::source(h, source);
1796 }
1797 fn set_drop_target(&mut self, h: &WinHandle, target: day_spec::transfer::Target) {
1798 transfer::target(h, target);
1799 }
1800
1801 #[cfg(feature = "winui")]
1802 fn list_scroll(&mut self, h: &WinHandle, to: day_spec::ListScroll) -> bool {
1803 list::list_scroll(h, to);
1804 true
1805 }
1806
1807 #[cfg(feature = "winui")]
1811 fn ui_idle(&mut self) -> bool {
1812 list::settled()
1813 }
1814
1815 fn gesture_support(&self, _kind: day_spec::GestureKind) -> Support {
1818 Support::Native
1819 }
1820
1821 fn set_hit_slop(&mut self, h: &WinHandle, _node: NodeId, slop: day_spec::Insets) {
1822 let (left, right) = if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
1824 (slop.trailing, slop.leading)
1825 } else {
1826 (slop.leading, slop.trailing)
1827 };
1828 unsafe { ffi::day_xaml_set_hit_slop(h.0, left, slop.top, right, slop.bottom) };
1829 }
1830
1831 fn set_drag_axis(&mut self, h: &WinHandle, _node: NodeId, axis: Option<day_spec::DragAxis>) {
1832 let code = match axis {
1833 None => 0,
1834 Some(day_spec::DragAxis::Horizontal) => 1,
1835 Some(day_spec::DragAxis::Vertical) => 2,
1836 };
1837 unsafe { ffi::day_xaml_set_drag_axis(h.0, code) };
1838 }
1839
1840 fn set_subtree_enabled(&mut self, h: &WinHandle, _node: NodeId, enabled: bool) {
1841 unsafe { ffi::day_xaml_set_subtree_enabled(h.0, c_int::from(enabled)) };
1842 }
1843
1844 fn primary_pointer(&self) -> day_spec::PointerKind {
1845 pointer_kind(unsafe { ffi::day_xaml_primary_pointer() })
1846 }
1847
1848 fn text_scale(&mut self, _style: Font) -> f64 {
1851 let f = unsafe { ffi::day_xaml_text_scale() };
1852 if f.is_finite() && f > 0.0 { f } else { 1.0 }
1853 }
1854
1855 fn set_layout_direction(
1856 &mut self,
1857 h: &WinHandle,
1858 kind: PieceKind,
1859 direction: day_spec::LayoutDirection,
1860 ) {
1861 let rtl = c_int::from(direction == day_spec::LayoutDirection::Rtl);
1862 if kind == kinds::LABEL {
1863 let align = LABEL_ALIGN.with(|m| m.borrow().get(&(h.0 as usize)).copied());
1866 let code = match align.unwrap_or_default() {
1867 day_spec::props::TextAlign::Leading => 0,
1868 day_spec::props::TextAlign::Center => 1,
1869 day_spec::props::TextAlign::Trailing => 2,
1870 day_spec::props::TextAlign::Justified => 3,
1871 };
1872 unsafe { ffi::day_xaml_label_set_direction(h.0, rtl, code) };
1873 return;
1874 }
1875 if matches!(
1877 kind,
1878 kinds::CONTAINER | kinds::SCROLL | kinds::LIST | kinds::NAV | kinds::NAV_PAGE
1879 ) {
1880 return;
1881 }
1882 unsafe { ffi::day_xaml_set_flow_direction(h.0, rtl) };
1883 }
1884
1885 #[cfg(feature = "winui")]
1886 fn set_focusable(&mut self, h: &WinHandle, node: NodeId, focusable: bool) {
1887 if focusable {
1888 unsafe {
1889 ffi::day_xaml_set_focusable(
1890 h.0,
1891 node.0,
1892 on_key_handled,
1893 on_text_handled,
1894 on_key,
1895 on_focus,
1896 );
1897 };
1898 }
1899 }
1900
1901 fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
1902 unsafe {
1903 day_toolkit_xaml_sys::day_xaml_set_visible(handle.0, i32::from(visible));
1904 }
1905 }
1906
1907 fn capability(&self, cap: Cap) -> Support {
1908 match cap {
1909 Cap::SearchField => Support::Native,
1910 Cap::ComboBox => Support::Native,
1911 Cap::Stepper => Support::Emulated,
1912 Cap::DateTimePicker => Support::Native,
1913 Cap::ColorPicker => Support::Native,
1914 Cap::PullRefresh => Support::Emulated,
1915 Cap::Pager => Support::Emulated,
1916 Cap::PullRefreshGesture => Support::Unsupported,
1917 Cap::DragDrop
1918 | Cap::DragExternalImport
1919 | Cap::DragExternalExport
1920 | Cap::DragMultipleItems
1921 | Cap::DragFileReferences
1922 | Cap::DragDeferredReceipt => Support::Native,
1923 Cap::Cursor => Support::Emulated,
1926 Cap::FontList => Support::Native,
1928 Cap::Snapshot => Support::Native,
1929 #[cfg(feature = "winui")]
1930 Cap::CanvasBitmap | Cap::ImageEncode => Support::Native,
1931 Cap::ImageDecode => Support::Native,
1934 Cap::BaselineAlignment => Support::Emulated,
1937 Cap::TextRuns | Cap::TextLinks => Support::Native,
1940 Cap::TextEditable | Cap::TextSpellCheck => Support::Native,
1943 Cap::TextSelectable => Support::Emulated,
1946 #[cfg(feature = "winui")]
1947 Cap::ListRecycling | Cap::ListDelete | Cap::ListSwipeActions => Support::Native,
1948 #[cfg(not(feature = "winui"))]
1949 Cap::ListRecycling => Support::Emulated,
1950 #[cfg(feature = "winui")]
1954 Cap::ListSections => Support::Emulated,
1955 Cap::ListReorder => Support::Native,
1958 Cap::NavReorder => Support::Emulated,
1961 Cap::MultiWindow => Support::Native,
1963 Cap::WindowStates | Cap::WindowFullscreen | Cap::ContentProtection => Support::Native,
1967 Cap::FramelessWindow | Cap::OverlayTitleBar | Cap::DragRegion => Support::Native,
1973 Cap::WindowMaterial => {
1975 if unsafe { ffi::day_xaml_materials_supported() } != 0 {
1976 Support::Native
1977 } else {
1978 Support::Unsupported
1979 }
1980 }
1981 Cap::StatusItem | Cap::AppProgress | Cap::AppBadgeCount | Cap::AppBadgeDot => {
1984 Support::Native
1985 }
1986 Cap::DynamicShortcuts => Support::Native,
1992 Cap::WindowGeometry
1993 | Cap::WindowPosition
1994 | Cap::WindowLevel
1995 | Cap::WindowAppearance
1996 | Cap::RequestAttention
1997 | Cap::Monitors => Support::Native,
1998 Cap::AppMenu | Cap::Toolbar | Cap::ToolbarSearch => Support::Native,
2004 Cap::NavSplit => Support::Native,
2007 Cap::Inspector => Support::Native,
2010 Cap::NavTabs => Support::Native,
2017 Cap::Dialogs | Cap::FileDialogs | Cap::FolderDialog => Support::Native,
2020 Cap::Appearance => Support::Native,
2024 Cap::ReduceMotion => Support::Native,
2027 Cap::Animation => Support::Native,
2031 Cap::Cover => Support::Emulated,
2033 Cap::Tree | Cap::TreeSections => Support::Native,
2036 Cap::NavHeader => Support::Native,
2039 Cap::Announce => Support::Native,
2042 Cap::KeyPhases => Support::Native,
2045 Cap::LabelSelection => Support::Native,
2048 Cap::ScrollOffset | Cap::ScrollPhases | Cap::ScrollZoom => Support::Native,
2052 Cap::ScrollSnap => Support::Emulated,
2055 #[cfg(feature = "winui")]
2058 Cap::ListViewport | Cap::ListScrollAlign => Support::Native,
2059 #[cfg(feature = "winui")]
2064 Cap::ListReaderScroll => Support::Native,
2065 Cap::HitSlop => Support::Native,
2068 #[cfg(feature = "winui")]
2070 Cap::Focusable => Support::Native,
2071 _ => Support::Unsupported,
2072 }
2073 }
2074
2075 fn realize(&mut self, kind: PieceKind, props: &dyn std::any::Any, id: NodeId) -> WinHandle {
2076 unsafe {
2077 let handle = match Builtin::from_key(kind) {
2078 Some(Builtin::Container) => {
2079 let h = ffi::day_xaml_container_new();
2080 if let Some(p) = props.downcast_ref::<ContainerProps>() {
2081 realize_surface(h, p);
2082 }
2083 WinHandle(h)
2084 }
2085 Some(Builtin::Scroll) => {
2086 let p = props
2087 .downcast_ref::<day_spec::props::ScrollProps>()
2088 .cloned()
2089 .unwrap_or_default();
2090 let mut content: *mut c_void = std::ptr::null_mut();
2091 let sv = ffi::day_xaml_scroll_new(&raw mut content, c_int::from(p.horizontal));
2092 SCROLL_STATE.with(|m| m.borrow_mut().insert(sv as usize, content));
2093 configure_scroll(sv, id, &p);
2094 WinHandle(sv)
2095 }
2096 Some(Builtin::Canvas) => {
2097 #[cfg(feature = "winui")]
2098 {
2099 let h =
2101 ffi::day_xaml_canvas_new(id.0, on_key_handled, on_text_handled, on_key);
2102 ffi::day_xaml_enable_focus(h, id.0, on_focus);
2103 CANVASES.with(|c| c.borrow_mut().insert(h as usize));
2104 WinHandle(h)
2105 }
2106 #[cfg(not(feature = "winui"))]
2107 {
2108 placeholder_handle(kind)
2109 }
2110 }
2111 Some(Builtin::Nav) => {
2112 let Some(p) = props_of::<NavProps>(kind, "xaml", props) else {
2113 return placeholder_handle(kind);
2114 };
2115 let is_stack =
2123 matches!(p.presentation, day_spec::props::NavPresentation::Stack);
2124 let mut content: *mut c_void = std::ptr::null_mut();
2125 let pane_mode = match p.presentation {
2131 day_spec::props::NavPresentation::Tabs => 2,
2132 day_spec::props::NavPresentation::Rail => 3,
2133 _ => -1,
2136 };
2137 let nav = ffi::day_xaml_nav_new(
2138 id.0,
2139 nav_selection,
2140 nav_region_size,
2141 nav_back,
2142 &raw mut content,
2143 c_int::from(is_stack),
2144 c_int::from(day_core::layout_direction() == day_spec::LayoutDirection::Rtl),
2145 c_int::from(p.documents.is_some()),
2146 c_int::from(p.documents.as_ref().is_some_and(|d| d.can_add)),
2147 cstr(p.documents.as_ref().map_or("", |d| d.new_label.as_str())).as_ptr(),
2148 document_event,
2149 );
2150 if pane_mode >= 0 {
2151 ffi::day_xaml_nav_set_pane_mode(nav, pane_mode);
2152 }
2153 NAV_STATE.with(|m| {
2154 m.borrow_mut().insert(
2155 nav as usize,
2156 NavState::Split(SplitNav {
2157 node: id.0,
2158 nav_view: nav,
2159 content_host: content,
2160 menu_node: 0,
2161 sidebar_page: None,
2162 detail_pages: Vec::new(),
2163 is_stack,
2164 resident: p.presentation.rows_are_chrome(),
2165 selected: 0,
2166 }),
2167 )
2168 });
2169 NAV_HOST_BY_ID.with(|m| m.borrow_mut().insert(id.0, nav));
2170 if !is_stack {
2171 PENDING_SPLIT_NAV.with(|c| c.set(nav));
2173 }
2174 WinHandle(nav)
2175 }
2176 Some(Builtin::NavPage) => {
2177 let page = ffi::day_xaml_container_new();
2178 NAV_PAGE_IDS.with(|m| m.borrow_mut().insert(page as usize, id));
2179 WinHandle(page)
2180 }
2181 Some(Builtin::Inspector) => {
2182 let (visible, width, leading) =
2183 props
2184 .downcast_ref::<InspectorProps>()
2185 .map_or((false, 280.0, false), |p| {
2186 (
2187 p.visible,
2188 p.width,
2189 p.edge == day_spec::props::PaneEdge::Leading,
2190 )
2191 });
2192 let mut content: *mut c_void = std::ptr::null_mut();
2193 let mut panel: *mut c_void = std::ptr::null_mut();
2194 let sv = ffi::day_xaml_inspector_new(
2195 id.0,
2196 width,
2197 c_int::from(visible),
2198 c_int::from(leading),
2199 inspector_region_size,
2200 &raw mut content,
2201 &raw mut panel,
2202 );
2203 INSPECTOR_STATE.with(|m| {
2204 m.borrow_mut().insert(
2205 sv as usize,
2206 XamlInspector {
2207 content_host: content,
2208 panel_host: panel,
2209 node: id.0,
2210 },
2211 )
2212 });
2213 INSPECTOR_PANES_BY_HOST
2214 .with(|m| m.borrow_mut().insert(id.0, InspectorPaneNodes::default()));
2215 WinHandle(sv)
2216 }
2217 Some(Builtin::InspectorPane) => {
2218 let pane = ffi::day_xaml_container_new();
2219 let panel = props
2220 .downcast_ref::<InspectorPaneProps>()
2221 .is_some_and(|p| p.panel);
2222 INSPECTOR_PANE_IDS.with(|m| m.borrow_mut().insert(pane as usize, (id, panel)));
2223 WinHandle(pane)
2224 }
2225 Some(Builtin::Cover) => {
2229 let cover = ffi::day_xaml_container_new();
2230 ffi::day_xaml_set_visible(cover, 0);
2231 COVER_IDS.with(|m| m.borrow_mut().insert(cover as usize, id));
2232 let p = props_of::<CoverProps>(kind, "xaml", props);
2233 if p.is_some_and(|p| p.half) {
2234 COVER_HALF.with(|s| s.borrow_mut().insert(cover as usize));
2235 }
2236 if p.is_some_and(|p| (p.sheet || p.large) && !p.half) {
2237 ffi::day_xaml_cover_escape(cover, id.0, on_cover_escape);
2238 }
2239 WinHandle(cover)
2240 }
2241 Some(Builtin::NavMenu) => {
2242 let Some(p) = props_of::<NavMenuProps>(kind, "xaml", props) else {
2243 return placeholder_handle(kind);
2244 };
2245 let pending = PENDING_SPLIT_NAV.with(std::cell::Cell::get);
2246 if pending.is_null() {
2247 let w = ffi::day_xaml_navlist_new(id.0, nav_menu_changed);
2249 ffi::day_xaml_navlist_set_items(
2250 w,
2251 cstr(&p.items.join("\n")).as_ptr(),
2252 cstr(&join_sections(&p.sections)).as_ptr(),
2253 );
2254 ffi::day_xaml_navlist_set_selected(
2255 w,
2256 p.selected.map_or(-1, |i| i as c_int),
2257 );
2258 let headings = p.sections.iter().filter(|s| s.is_some()).count();
2259 NAV_MENU_ROWS
2260 .with(|m| m.borrow_mut().insert(w as usize, (p.items.len(), headings)));
2261 WinHandle(w)
2262 } else {
2263 let icons_joined = p
2266 .icons
2267 .iter()
2268 .map(|ic| ic.as_deref().map_or_default(icon_file_name))
2269 .collect::<Vec<_>>()
2270 .join("\n");
2271 let badge_icons_joined = p
2274 .badge_icons
2275 .iter()
2276 .map(|ic| ic.as_deref().map_or_default(icon_file_name))
2277 .collect::<Vec<_>>()
2278 .join("\n");
2279 ffi::day_xaml_document_items(
2280 pending,
2281 cstr(&p.items.join("\u{1f}")).as_ptr(),
2282 cstr(&p.document_keys.join("\u{1f}")).as_ptr(),
2283 );
2284 ffi::day_xaml_nav_set_items(
2285 pending,
2286 cstr(&p.items.join("\n")).as_ptr(),
2287 cstr(&icons_joined).as_ptr(),
2288 cstr(&join_geoms(&p.icons)).as_ptr(),
2289 cstr(&join_tints(&p.tints)).as_ptr(),
2290 cstr(&badge_icons_joined).as_ptr(),
2291 cstr(&join_geoms(&p.badge_icons)).as_ptr(),
2292 cstr(&join_tints(&p.badge_tints)).as_ptr(),
2293 cstr(&join_sections(&p.sections)).as_ptr(),
2294 );
2295 ffi::day_xaml_nav_set_selected(
2296 pending,
2297 p.selected.map_or(-1, |i| i as c_int),
2298 );
2299 NAV_STATE.with(|m| {
2300 if let Some(NavState::Split(s)) =
2301 m.borrow_mut().get_mut(&(pending as usize))
2302 {
2303 s.menu_node = id.0;
2304 s.selected = p.selected.unwrap_or(0);
2305 }
2306 });
2307 select_sync(pending);
2310 PENDING_SPLIT_NAV.with(|c| c.set(std::ptr::null_mut()));
2311 let placeholder = ffi::day_xaml_container_new();
2312 NAV_MENU_HOST
2313 .with(|m| m.borrow_mut().insert(placeholder as usize, pending));
2314 WinHandle(placeholder)
2315 }
2316 }
2317 Some(Builtin::Label) => {
2318 let Some(p) = props_of::<LabelProps>(kind, "xaml", props) else {
2319 return placeholder_handle(kind);
2320 };
2321 let h = ffi::day_xaml_label_new(cstr(&p.text).as_ptr(), c_int::from(p.wraps));
2322 let (pt, weight, italic, tabular) = font_params(p.font);
2323 ffi::day_xaml_label_set_font(h, pt, weight, italic, tabular);
2324 apply_custom_family(h, p.font);
2325 apply_label_features(h, p.font);
2326 ffi::day_xaml_label_set_align(h, label_align_code(p.align));
2329 LABEL_ALIGN.with(|m| m.borrow_mut().insert(h as usize, p.align));
2330 if p.reports_selection {
2331 LABEL_TEXT.with(|m| m.borrow_mut().insert(id.0, p.text.clone()));
2332 ffi::day_xaml_label_report_selection(h, id.0, on_label_selection);
2333 }
2334 if p.role == day_spec::props::TextRole::Secondary {
2335 ffi::day_xaml_label_set_secondary(h);
2336 }
2337 if let Some(c) = p.color {
2338 paint_label_color(h, c);
2339 }
2340 LABEL_NODE.with(|m| m.borrow_mut().insert(h as usize, id.0));
2341 if !p.runs.is_empty() {
2342 set_label_runs(h, id.0, &p.text, &p.runs);
2343 }
2344 apply_paragraph(h, p.wraps, &p.paragraph(), &p.text, p.runs.is_empty());
2345 WinHandle(h)
2346 }
2347 Some(Builtin::Button) => {
2348 let Some(p) = props_of::<ButtonProps>(kind, "xaml", props) else {
2349 return placeholder_handle(kind);
2350 };
2351 let h = ffi::day_xaml_button_new(cstr(&p.title).as_ptr(), id.0, on_press);
2352 apply_button_style(h, p.style);
2353 if p.icon.is_some() {
2354 apply_button_content(h, &p.title, p.icon.as_ref(), p.icon_only);
2355 }
2356 ffi::day_xaml_enable_focus(h, id.0, on_focus);
2357 ffi::day_xaml_set_enabled(h, c_int::from(p.enabled));
2358 ffi::day_xaml_button_set_selected(h, c_int::from(p.selected));
2359 WinHandle(h)
2360 }
2361 Some(Builtin::Toggle) => {
2362 let Some(p) = props_of::<ToggleProps>(kind, "xaml", props) else {
2363 return placeholder_handle(kind);
2364 };
2365 let h = ffi::day_xaml_toggle_new(c_int::from(p.on), id.0, on_toggle);
2366 ffi::day_xaml_enable_focus(h, id.0, on_focus);
2367 ffi::day_xaml_set_enabled(h, c_int::from(p.enabled));
2368 WinHandle(h)
2369 }
2370 Some(Builtin::Slider) => {
2371 let Some(p) = props_of::<SliderProps>(kind, "xaml", props) else {
2372 return placeholder_handle(kind);
2373 };
2374 let step = p.step.unwrap_or((p.max - p.min) / 1000.0).max(1e-9);
2377 let h = ffi::day_xaml_slider_new(p.value, p.min, p.max, step, id.0, on_slider);
2378 ffi::day_xaml_enable_focus(h, id.0, on_focus);
2379 ffi::day_xaml_set_enabled(h, c_int::from(p.enabled));
2380 WinHandle(h)
2381 }
2382 Some(Builtin::Picker) => picker::realize_any(self, props, id),
2383 Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
2384 Some(Builtin::TextField) => {
2385 let Some(p) = props_of::<TextFieldProps>(kind, "xaml", props) else {
2386 return placeholder_handle(kind);
2387 };
2388 ffi::day_xaml_set_field_keys(on_field_key);
2389 let h = ffi::day_xaml_textbox_new(
2390 cstr(&p.text).as_ptr(),
2391 cstr(&p.placeholder).as_ptr(),
2392 id.0,
2393 on_text,
2394 );
2395 ffi::day_xaml_enable_focus(h, id.0, on_focus);
2396 ffi::day_xaml_set_enabled(h, c_int::from(p.enabled));
2397 TEXT_FIELD_NODE.with(|m| m.borrow_mut().insert(h as usize, id.0));
2398 WinHandle(h)
2399 }
2400 Some(Builtin::Divider) => {
2401 let vertical = day_spec::props_of::<DividerProps>(kind, "xaml", props)
2402 .is_some_and(|p| p.vertical);
2403 WinHandle(ffi::day_xaml_divider_new(c_int::from(vertical)))
2404 }
2405 Some(Builtin::List) => {
2406 let Some(p) = props_of::<ListProps>(kind, "xaml", props) else {
2407 return placeholder_handle(kind);
2408 };
2409 attach_custom_sidebar();
2410 WinHandle(list::new(id, p))
2411 }
2412 Some(Builtin::Progress) => {
2413 let Some(p) = props_of::<ProgressProps>(kind, "xaml", props) else {
2414 return placeholder_handle(kind);
2415 };
2416 if p.value.is_none() {
2417 return crate::controls::spinner::make(self, p, id);
2418 }
2419 match p.value {
2420 Some(v) => WinHandle(ffi::day_xaml_progress_new(1, progress_ticks(v))),
2421 None => WinHandle(ffi::day_xaml_progress_new(0, 0)),
2422 }
2423 }
2424 Some(Builtin::Image) => {
2425 let Some(p) = props_of::<ImageProps>(kind, "xaml", props) else {
2426 return placeholder_handle(kind);
2427 };
2428 let mode = match p.content_mode {
2430 ContentMode::Fit => 0,
2431 ContentMode::Fill => 1,
2432 ContentMode::Stretch => 2,
2433 };
2434 let named = match &p.source {
2441 day_spec::ImageSource::Named(name) => name.clone(),
2442 _ => String::new(),
2443 };
2444 match &p.source {
2450 day_spec::ImageSource::Bytes(bytes) => {
2453 let h = ffi::day_xaml_image_bytes_new(
2454 bytes.as_ptr(),
2455 bytes.len() as c_int,
2456 mode,
2457 );
2458 if let Some(tint) = p.tint {
2459 ffi::day_xaml_image_set_tint(h, argb(tint), 1);
2460 }
2461 WinHandle(h)
2462 }
2463 day_spec::ImageSource::Decoded(id) => {
2464 let h = ffi::day_xaml_image_bitmap_new(id.0, mode);
2465 if let Some(tint) = p.tint {
2466 ffi::day_xaml_image_set_tint(h, argb(tint), 1);
2467 }
2468 WinHandle(h)
2469 }
2470 day_spec::ImageSource::Named(_) => {
2471 let tinted = match p.tint {
2475 Some(_) if p.template => 3,
2476 Some(_) => 1,
2477 None if p.template => 2,
2478 None => 0,
2479 };
2480 let geometry = vector_geometry(&named).and_then(|spec| {
2481 let h = ffi::day_xaml_vector_new(
2482 cstr(&spec).as_ptr(),
2483 mode,
2484 p.tint.map_or(0, argb),
2485 tinted,
2486 );
2487 (!h.is_null()).then_some(h)
2488 });
2489 let recolored = || {
2494 let uri = image_uri(&named);
2495 if tinted != 1 || uri.is_empty() || !cfg!(feature = "winui") {
2496 return None;
2497 }
2498 let h = ffi::day_xaml_image_new(cstr(&uri).as_ptr(), mode);
2499 ffi::day_xaml_image_set_tint(h, p.tint.map_or(0, argb), 1);
2500 Some(h)
2501 };
2502 let tinted = || {
2506 if tinted == 0 {
2507 return None;
2508 }
2509 let file = icon_file_name(&named);
2510 if file.is_empty() {
2511 return None;
2512 }
2513 let h = ffi::day_xaml_image_tinted_new(
2514 cstr(&file).as_ptr(),
2515 mode,
2516 p.tint.map_or(0, argb),
2517 tinted,
2518 );
2519 (!h.is_null()).then_some(h)
2520 };
2521 WinHandle(geometry.or_else(recolored).or_else(tinted).unwrap_or_else(
2522 || ffi::day_xaml_image_new(cstr(&image_uri(&named)).as_ptr(), mode),
2523 ))
2524 }
2525 }
2526 }
2527 Some(Builtin::Tree) => {
2528 let Some(p) = props_of::<TreeProps>(kind, "xaml", props) else {
2529 return placeholder_handle(kind);
2530 };
2531 attach_custom_sidebar();
2532 WinHandle(tree::new(id, p))
2533 }
2534 Some(
2537 Builtin::ListCell | Builtin::ListItem | Builtin::Split | Builtin::SplitPane,
2538 )
2539 | None => {
2540 if let Some(make) = self.registry.get(kind).map(|r| r.make) {
2541 return make(self, props, id);
2542 }
2543 warn_missing_renderer(kind);
2544 placeholder_handle(kind)
2545 }
2546 };
2547 match Builtin::from_key(kind) {
2548 Some(Builtin::Image) => {
2551 ffi::day_xaml_set_passive(handle.0);
2552 if let Some(p) = props.downcast_ref::<day_spec::props::ImageProps>() {
2553 keep_image_tint(handle.0, p.tint);
2554 }
2555 }
2556 Some(Builtin::Divider) => ffi::day_xaml_set_passive(handle.0),
2557 _ => {}
2558 }
2559 ffi::day_xaml_on_control_loaded(handle.0, id.0, control_loaded);
2560 handle
2561 }
2562 }
2563
2564 fn update(
2565 &mut self,
2566 h: &WinHandle,
2567 kind: PieceKind,
2568 patch: &dyn std::any::Any,
2569 anim: Option<&AnimSpec>,
2570 ) {
2571 if let Some(patch) = patch.downcast_ref::<TreePatch>() {
2572 tree::patch(h.0 as usize, patch);
2573 return;
2574 }
2575 unsafe {
2576 match kind {
2577 kinds::IMAGE => {
2578 if let Some(patch) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
2579 match patch {
2580 day_spec::props::ImagePatch::Tint(tint) => {
2581 ffi::day_xaml_image_set_tint(
2582 h.0,
2583 tint.map_or(0, argb),
2584 i32::from(tint.is_some()),
2585 );
2586 keep_image_tint(h.0, *tint);
2587 }
2588 day_spec::props::ImagePatch::Source(source) => match source {
2589 day_spec::ImageSource::Named(name) => {
2590 if let Some(spec) = vector_geometry(name) {
2591 ffi::day_xaml_image_set_vector(h.0, cstr(&spec).as_ptr());
2592 } else {
2593 ffi::day_xaml_image_set_uri(
2594 h.0,
2595 cstr(&image_uri(name)).as_ptr(),
2596 );
2597 }
2598 }
2599 day_spec::ImageSource::Bytes(b) => {
2600 ffi::day_xaml_image_set_bytes(
2601 h.0,
2602 b.as_ptr(),
2603 b.len() as c_int,
2604 );
2605 }
2606 day_spec::ImageSource::Decoded(id) => {
2607 ffi::day_xaml_image_set_bitmap(h.0, id.0);
2608 }
2609 },
2610 }
2611 }
2612 }
2613 kinds::CONTAINER => match patch.downcast_ref::<ContainerPatch>() {
2614 Some(ContainerPatch::Fill(fill)) => patch_fill(h.0, fill.as_ref(), anim),
2615 Some(ContainerPatch::Surface(p)) => patch_surface(h.0, p),
2616 None => {}
2617 },
2618 kinds::LABEL => {
2619 if let Some(p) = patch.downcast_ref::<LabelPatch>() {
2620 match p {
2621 LabelPatch::Paragraph(para) => {
2622 let wraps = ffi::day_xaml_label_wraps(h.0) != 0;
2624 let (text, plain) = label_text_of(h.0);
2625 apply_paragraph(h.0, wraps, para, &text, plain);
2626 }
2627 LabelPatch::Text(t) => {
2628 keep_inks(h.0, InkSlot::LabelRuns, false, |_, _| {});
2630 ffi::day_xaml_label_set_text(h.0, cstr(t).as_ptr());
2631 note_label_text(h.0, t);
2632 }
2633 LabelPatch::Font(f) => {
2634 let (pt, weight, italic, tabular) = font_params(*f);
2635 ffi::day_xaml_label_set_font(h.0, pt, weight, italic, tabular);
2636 apply_custom_family(h.0, *f);
2637 apply_label_features(h.0, *f);
2638 let width = LABEL_ELIDE.with(|m| {
2640 m.borrow().get(&(h.0 as usize)).map_or(0.0, |e| e.width)
2641 });
2642 if width > 0.0 {
2643 elide_label(h.0, width);
2644 }
2645 }
2646 LabelPatch::Runs(text, runs) => {
2647 let node = LABEL_NODE
2648 .with(|m| m.borrow().get(&(h.0 as usize)).copied())
2649 .unwrap_or(0);
2650 set_label_runs(h.0, node, text, runs);
2651 note_label_text(h.0, text);
2652 }
2653 LabelPatch::Color(c) => {
2654 paint_label_color(h.0, c.unwrap_or(day_spec::Ink::CLEAR));
2655 }
2656 }
2657 }
2658 }
2659 kinds::BUTTON => {
2660 if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
2661 match p {
2662 ButtonPatch::Content(c) => {
2663 apply_button_content(h.0, &c.title, c.icon.as_ref(), c.icon_only);
2664 }
2665 ButtonPatch::Title(t) => {
2666 ffi::day_xaml_button_set_title(h.0, cstr(t).as_ptr());
2667 }
2668 ButtonPatch::Enabled(e) => {
2669 ffi::day_xaml_set_enabled(h.0, c_int::from(*e));
2670 }
2671 ButtonPatch::Selected(on) => {
2672 ffi::day_xaml_button_set_selected(h.0, c_int::from(*on));
2673 }
2674 ButtonPatch::Style(s) => apply_button_style(h.0, *s),
2675 }
2676 }
2677 }
2678 kinds::TOGGLE => {
2679 if let Some(p) = patch.downcast_ref::<TogglePatch>() {
2680 match p {
2681 TogglePatch::On(on) => ffi::day_xaml_toggle_set(h.0, c_int::from(*on)),
2682 TogglePatch::Enabled(e) => {
2683 ffi::day_xaml_set_enabled(h.0, c_int::from(*e));
2684 }
2685 }
2686 }
2687 }
2688 kinds::SLIDER => {
2689 if let Some(p) = patch.downcast_ref::<SliderPatch>() {
2690 match p {
2691 SliderPatch::Value(v) => ffi::day_xaml_slider_set(h.0, *v),
2692 SliderPatch::Enabled(e) => {
2693 ffi::day_xaml_set_enabled(h.0, c_int::from(*e));
2694 }
2695 }
2696 }
2697 }
2698 kinds::PROGRESS => {
2699 if let Some(p @ ProgressPatch::Animating(_)) =
2700 patch.downcast_ref::<ProgressPatch>()
2701 {
2702 crate::controls::spinner::update(self, h, p);
2703 return;
2704 }
2705
2706 if let Some(ProgressPatch::Value(Some(v))) =
2707 patch.downcast_ref::<ProgressPatch>()
2708 {
2709 ffi::day_xaml_progress_set(h.0, progress_ticks(*v));
2710 }
2711 }
2712 kinds::LIST => {
2713 if let Some(patch) = patch.downcast_ref::<ListPatch>() {
2714 list::patch(h, patch);
2715 }
2716 }
2717 kinds::SCROLL => {
2718 #[cfg(feature = "winui")]
2720 if let Some(day_spec::props::ScrollPatch::Zoom { scale, animated }) =
2721 patch.downcast_ref::<day_spec::props::ScrollPatch>()
2722 {
2723 ffi::day_xaml_scroll_zoom(h.0, *scale, c_int::from(*animated));
2724 }
2725 }
2726 kinds::NAV_MENU => {
2727 let host = NAV_MENU_HOST.with(|m| m.borrow().get(&(h.0 as usize)).copied());
2729 match patch.downcast_ref::<NavMenuPatch>() {
2730 Some(NavMenuPatch::Selected(sel)) => {
2731 let idx = sel.map_or(-1, |i| i as c_int);
2732 match host {
2733 Some(nav) => ffi::day_xaml_nav_set_selected(nav, idx),
2734 None => ffi::day_xaml_navlist_set_selected(h.0, idx),
2735 }
2736 }
2737 Some(NavMenuPatch::Items {
2745 items,
2746 icons,
2747 tints,
2748 badge_icons,
2749 badge_tints,
2750 sections,
2751 selected,
2752 document_keys,
2753 ..
2754 }) => {
2755 let idx = selected.map_or(-1, |i| i as c_int);
2756 let joined = cstr(&items.join("\n"));
2757 let sections_joined = cstr(&join_sections(sections));
2758 if let Some(nav) = host {
2759 let icons_joined = icons
2760 .iter()
2761 .map(|ic| ic.as_deref().map_or_default(icon_file_name))
2762 .collect::<Vec<_>>()
2763 .join("\n");
2764 ffi::day_xaml_document_items(
2765 nav,
2766 cstr(&items.join("\u{1f}")).as_ptr(),
2767 cstr(&document_keys.join("\u{1f}")).as_ptr(),
2768 );
2769 ffi::day_xaml_nav_set_items(
2770 nav,
2771 joined.as_ptr(),
2772 cstr(&icons_joined).as_ptr(),
2773 cstr(&join_geoms(icons)).as_ptr(),
2774 cstr(&join_tints(tints)).as_ptr(),
2775 cstr(
2776 &badge_icons
2777 .iter()
2778 .map(|ic| ic.as_deref().map_or_default(icon_file_name))
2779 .collect::<Vec<_>>()
2780 .join("\n"),
2781 )
2782 .as_ptr(),
2783 cstr(&join_geoms(badge_icons)).as_ptr(),
2784 cstr(&join_tints(badge_tints)).as_ptr(),
2785 sections_joined.as_ptr(),
2786 );
2787 ffi::day_xaml_nav_set_selected(nav, idx);
2788 } else {
2789 ffi::day_xaml_navlist_set_items(
2790 h.0,
2791 joined.as_ptr(),
2792 sections_joined.as_ptr(),
2793 );
2794 ffi::day_xaml_navlist_set_selected(h.0, idx);
2795 let headings = sections.iter().filter(|s| s.is_some()).count();
2796 NAV_MENU_ROWS.with(|m| {
2797 m.borrow_mut().insert(h.0 as usize, (items.len(), headings))
2798 });
2799 }
2800 }
2801 Some(NavMenuPatch::IconProgress(_)) | None => {}
2802 }
2803 }
2804 kinds::COVER => {
2811 if let Some(p) = patch.downcast_ref::<CoverPatch>() {
2812 let node = COVER_IDS
2813 .with(|m| m.borrow().get(&(h.0 as usize)).copied())
2814 .unwrap_or(day_spec::WINDOW_NODE);
2815 match p {
2816 CoverPatch::Present { background, .. } => {
2817 ffi::day_xaml_hit_on(h.0);
2819 match *background {
2822 Some(bg) => paint_inks(
2823 h.0,
2824 InkSlot::Surface,
2825 bg.is_dynamic(),
2826 move |h, palette| {
2828 ffi::day_xaml_container_set_bg(
2829 h,
2830 ink_argb(bg, palette),
2831 );
2832 },
2833 ),
2834 None => paint_inks(h.0, InkSlot::Surface, true, |h, _| {
2835 ffi::day_xaml_cover_ground(h);
2836 }),
2837 }
2838 let root = ffi::day_xaml_window_chrome_root(self.window);
2844 ffi::day_xaml_reparent(root, h.0);
2848 let (y, size) = cover_frame(h.0, cover_extent(self.window));
2849 ffi::day_xaml_set_geometry(
2850 h.0,
2851 0,
2852 y.round() as c_int,
2853 size.width.round() as c_int,
2854 size.height.round() as c_int,
2855 );
2856 ffi::day_xaml_set_visible(h.0, 1);
2857 COVERS.with(|c| c.borrow_mut().push((h.0, node)));
2858 emit(node, Event::FrameChanged(size));
2859 }
2860 CoverPatch::DismissDisabled(_) => {}
2861 CoverPatch::Dismiss => {
2862 ffi::day_xaml_set_visible(h.0, 0);
2863 COVERS.with(|c| c.borrow_mut().retain(|(w, _)| *w != h.0));
2864 emit(node, Event::CoverHidden);
2865 }
2866 }
2867 }
2868 }
2869 kinds::INSPECTOR => {
2870 if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>()
2871 {
2872 ffi::day_xaml_inspector_set_open(h.0, c_int::from(*v));
2873 }
2874 }
2875 kinds::NAV => {
2876 if let Some(p) = patch.downcast_ref::<day_spec::props::DocumentTabsPatch>() {
2877 ffi::day_xaml_document_chrome(h.0, c_int::from(p.native));
2878 return;
2879 }
2880 if let Some(np) = patch.downcast_ref::<NavPatch>() {
2881 #[expect(
2882 clippy::match_same_arms,
2883 reason = "each variant that sets no title keeps its own explanation"
2884 )]
2885 let title = match np {
2886 NavPatch::Pushed { title, .. } => Some(title.as_str()),
2887 NavPatch::Title(t) => Some(t.as_str()),
2888 NavPatch::Popped => None,
2891 NavPatch::GuardTop(_) => None,
2894 NavPatch::Reorder(order) => {
2895 NAV_STATE.with(|m| {
2896 if let Some(NavState::Split(st)) =
2897 m.borrow_mut().get_mut(&(h.0 as usize))
2898 {
2899 let old = st.detail_pages.clone();
2900 st.detail_pages = order
2901 .iter()
2902 .filter_map(|i| old.get(*i).cloned())
2903 .collect();
2904 }
2905 });
2906 None
2907 }
2908 NavPatch::Presentation(_) => None,
2913 NavPatch::Select(i) => {
2918 NAV_STATE.with(|m| {
2921 if let Some(NavState::Split(st)) =
2922 m.borrow_mut().get_mut(&(h.0 as usize))
2923 {
2924 st.selected = *i;
2925 }
2926 });
2927 select_sync(h.0);
2928 None
2929 }
2930 NavPatch::ListVisible(_) | NavPatch::ListInStack(_) => None,
2934 };
2935 if let Some(title) = title {
2936 let nav = NAV_STATE.with(|m| {
2937 let mut m = m.borrow_mut();
2938 match m.get_mut(&(h.0 as usize)) {
2939 Some(NavState::Split(s)) => {
2940 if let Some(top) = s.detail_pages.last_mut() {
2942 top.2 = title.to_string();
2943 }
2944 Some(s.nav_view)
2945 }
2946 _ => None,
2947 }
2948 });
2949 if let Some(nav) = nav {
2950 ffi::day_xaml_nav_set_header(nav, cstr(title).as_ptr());
2951 }
2952 }
2953 }
2954 }
2955 kinds::PICKER => picker::update_any(self, h, patch),
2956 kinds::TEXT_AREA => textarea::update_any(self, h, patch),
2957 kinds::TEXT_FIELD => {
2958 if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
2959 match p {
2960 TextFieldPatch::Text { text, from_native } => {
2961 if !*from_native {
2962 let node = TEXT_FIELD_NODE
2963 .with(|m| m.borrow().get(&(h.0 as usize)).copied());
2964 if let Some(node) = node {
2965 TEXT_FIELD_ECHO
2966 .with(|m| m.borrow_mut().insert(node, text.clone()));
2967 }
2968 ffi::day_xaml_textbox_set_text(h.0, cstr(text).as_ptr());
2969 }
2970 }
2971 TextFieldPatch::Placeholder(t) => {
2972 ffi::day_xaml_textbox_set_placeholder(h.0, cstr(t).as_ptr());
2973 }
2974 TextFieldPatch::Enabled(e) => {
2975 ffi::day_xaml_set_enabled(h.0, c_int::from(*e));
2976 }
2977 TextFieldPatch::Select(sel) => {
2978 let at = |n: usize| n.min(c_int::MAX as usize) as c_int;
2979 ffi::day_xaml_textbox_select(h.0, at(sel.start), at(sel.end));
2980 }
2981 }
2982 }
2983 }
2984 _ => {
2985 if let Some(update) = self.registry.get(kind).map(|r| r.update) {
2986 update(self, h, patch);
2987 }
2988 }
2989 }
2990 }
2991 }
2992
2993 fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
2995 let f = self.registry.get(kind).and_then(|r| r.release);
2998 if let Some(f) = f {
2999 f(self, h);
3000 }
3001 }
3002 fn release(&mut self, h: WinHandle) {
3003 tree::release(h.0 as usize);
3004 if DRAG_REGIONS.with(|d| d.borrow_mut().remove(&(h.0 as usize))) {
3006 unsafe { ffi::day_xaml_set_drag_region(h.0, 0) };
3007 }
3008 self.secondary.retain(|w| {
3011 if w.content == h.0 {
3012 unsafe { ffi::day_xaml_window_destroy2(w.win) };
3013 false
3014 } else {
3015 true
3016 }
3017 });
3018 if !self.primary_root.is_null() && self.primary_root == h.0 {
3022 self.primary_root = std::ptr::null_mut();
3023 unsafe { ffi::day_xaml_destroy_primary() };
3024 }
3025 let key = h.0 as usize;
3026 BUTTON_MENUS.with(|m| m.borrow_mut().retain(|_, (button, _)| *button != key));
3027 if let Some(node) = LABEL_NODE.with(|m| m.borrow_mut().remove(&key)) {
3028 LABEL_TEXT.with(|m| m.borrow_mut().remove(&node));
3029 }
3030 LABEL_ELIDE.with(|m| m.borrow_mut().remove(&key));
3031 LABEL_ALIGN.with(|m| m.borrow_mut().remove(&key));
3032 LABEL_RUNS.with(|m| m.borrow_mut().remove(&key));
3033 INKS.with(|m| m.borrow_mut().retain(|(view, _), _| *view != key));
3034 SURFACES.with(|m| m.borrow_mut().remove(&key));
3035 if let Some(node) = TEXT_FIELD_NODE.with(|m| m.borrow_mut().remove(&key)) {
3036 TEXT_FIELD_ECHO.with(|m| m.borrow_mut().remove(&node));
3037 }
3038 NAV_MENU_ROWS.with(|m| m.borrow_mut().remove(&key));
3039 NAV_PAGE_IDS.with(|m| m.borrow_mut().remove(&key));
3040 if let Some(insp) = INSPECTOR_STATE.with(|m| m.borrow_mut().remove(&key)) {
3043 INSPECTOR_PANES_BY_HOST.with(|m| {
3044 m.borrow_mut().remove(&insp.node);
3045 });
3046 }
3047 INSPECTOR_PANE_IDS.with(|m| m.borrow_mut().remove(&key));
3048 NAV_MENU_HOST.with(|m| m.borrow_mut().remove(&key));
3049 SPLIT_SIDEBAR_PAGES.with(|m| m.borrow_mut().remove(&key));
3050 if let Some(NavState::Split(s)) = NAV_STATE.with(|m| m.borrow_mut().remove(&key)) {
3051 NAV_HOST_BY_ID.with(|m| m.borrow_mut().retain(|_, v| *v != s.nav_view));
3052 unsafe { ffi::day_xaml_delete(s.content_host) };
3053 }
3054 list::release(key);
3055 if let Some(content) = SCROLL_STATE.with(|m| m.borrow_mut().remove(&key)) {
3057 unsafe { ffi::day_xaml_delete(content) };
3058 }
3059 GESTURES.with(|g| g.borrow_mut().retain(|(ptr, _)| *ptr != key));
3060 CANVASES.with(|c| c.borrow_mut().remove(&key));
3061 COVERS.with(|c| c.borrow_mut().retain(|(w, _)| *w != h.0));
3065 COVER_HALF.with(|s| s.borrow_mut().remove(&(h.0 as usize)));
3066 COVER_IDS.with(|m| {
3067 m.borrow_mut().remove(&key);
3068 });
3069 day_spec::sidetable::sweep(key);
3074 unsafe { ffi::day_xaml_delete(h.0) };
3075 }
3076
3077 fn insert(&mut self, parent: &WinHandle, child: &WinHandle, index: usize) {
3078 enum NavInsert {
3081 No,
3082 Done,
3083 Content {
3086 node: NodeId,
3087 host_id: u64,
3088 stack: bool,
3089 resident: bool,
3090 },
3091 }
3092 let nav = NAV_STATE.with(|m| {
3093 let mut m = m.borrow_mut();
3094 let Some(NavState::Split(s)) = m.get_mut(&(parent.0 as usize)) else {
3095 return NavInsert::No;
3096 };
3097 let node = NAV_PAGE_IDS
3098 .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
3099 .unwrap_or(NodeId(0));
3100 if !s.is_stack && index == 0 {
3101 unsafe { ffi::day_xaml_nav_set_pane_header(s.nav_view, child.0) };
3104 s.sidebar_page = Some((child.0, node));
3105 SPLIT_SIDEBAR_PAGES.with(|p| p.borrow_mut().insert(child.0 as usize));
3106 NavInsert::Done
3107 } else {
3108 unsafe { ffi::day_xaml_add_child(s.content_host, child.0) };
3110 s.detail_pages.push((child.0, node, String::new()));
3111 NavInsert::Content {
3112 node,
3113 host_id: s.node,
3114 stack: s.is_stack,
3115 resident: s.resident,
3116 }
3117 }
3118 });
3119 match nav {
3120 NavInsert::No => {}
3121 NavInsert::Done => return,
3122 NavInsert::Content {
3123 node,
3124 host_id,
3125 stack,
3126 resident,
3127 } => {
3128 let boxed: Box<dyn FnOnce() + Send> = Box::new(move || {
3144 let Some(host) = nav_page_content_host(host_id, node) else {
3145 return;
3146 };
3147 let (mut w, mut h) = (0.0, 0.0);
3148 unsafe { ffi::day_xaml_widget_size(host, &raw mut w, &raw mut h) };
3149 if w > 0.0 && h > 0.0 {
3150 emit(node, Event::FrameChanged(Size::new(w, h)));
3151 }
3152 });
3153 let data = Box::into_raw(Box::new(boxed)).cast::<c_void>();
3154 unsafe { ffi::day_xaml_post(run_posted, data) };
3155 if stack {
3156 stack_sync(parent.0);
3157 } else if resident {
3158 select_sync(parent.0);
3159 }
3160 return;
3161 }
3162 }
3163 let inspected = INSPECTOR_STATE.with(|m| {
3166 let m = m.borrow();
3167 let state = m.get(&(parent.0 as usize))?;
3168 let (pane_id, panel) = INSPECTOR_PANE_IDS
3169 .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
3170 .unwrap_or((NodeId(0), index == 1));
3171 let host = if panel {
3172 state.panel_host
3173 } else {
3174 state.content_host
3175 };
3176 unsafe { ffi::day_xaml_add_child(host, child.0) };
3177 INSPECTOR_PANES_BY_HOST.with(|p| {
3178 if let Some(nodes) = p.borrow_mut().get_mut(&state.node) {
3179 if panel {
3180 nodes.panel = Some(pane_id);
3181 } else {
3182 nodes.content = Some(pane_id);
3183 }
3184 }
3185 });
3186 Some((host, pane_id))
3187 });
3188 if let Some((host, pane_id)) = inspected {
3189 let (mut w, mut h) = (0.0, 0.0);
3192 unsafe { ffi::day_xaml_widget_size(host, &raw mut w, &raw mut h) };
3193 if w > 0.0 && h > 0.0 && pane_id.0 != 0 {
3194 emit(pane_id, Event::FrameChanged(Size::new(w, h)));
3195 }
3196 return;
3197 }
3198 let target = SCROLL_STATE
3200 .with(|m| m.borrow().get(&(parent.0 as usize)).copied())
3201 .unwrap_or(parent.0);
3202 unsafe { ffi::day_xaml_add_child(target, child.0) };
3203 }
3204
3205 fn remove(&mut self, parent: &WinHandle, child: &WinHandle) {
3206 let removed = NAV_STATE.with(|m| {
3208 let mut m = m.borrow_mut();
3209 let Some(NavState::Split(s)) = m.get_mut(&(parent.0 as usize)) else {
3210 return None;
3211 };
3212 s.detail_pages.retain(|&(p, _, _)| p != child.0);
3213 SPLIT_SIDEBAR_PAGES.with(|p| p.borrow_mut().remove(&(child.0 as usize)));
3214 unsafe { ffi::day_xaml_remove_child(s.content_host, child.0) };
3215 Some((s.is_stack, s.resident))
3216 });
3217 match removed {
3218 Some((true, _)) => {
3219 stack_sync(parent.0);
3221 return;
3222 }
3223 Some((false, true)) => {
3224 select_sync(parent.0);
3227 return;
3228 }
3229 Some((false, false)) => return,
3232 None => {}
3233 }
3234 let inspected = INSPECTOR_STATE.with(|m| {
3236 m.borrow().get(&(parent.0 as usize)).map(|state| {
3237 let panel = INSPECTOR_PANE_IDS
3238 .with(|ids| ids.borrow().get(&(child.0 as usize)).map(|(_, p)| *p))
3239 .unwrap_or(false);
3240 if panel {
3241 state.panel_host
3242 } else {
3243 state.content_host
3244 }
3245 })
3246 });
3247 if let Some(host) = inspected {
3248 unsafe { ffi::day_xaml_remove_child(host, child.0) };
3249 return;
3250 }
3251 let target = SCROLL_STATE
3252 .with(|m| m.borrow().get(&(parent.0 as usize)).copied())
3253 .unwrap_or(parent.0);
3254 unsafe { ffi::day_xaml_remove_child(target, child.0) };
3255 }
3256
3257 fn move_child(&mut self, _parent: &WinHandle, _child: &WinHandle, _to: usize) {
3258 }
3260
3261 fn measure(&mut self, h: &WinHandle, kind: PieceKind, p: Proposal) -> Size {
3262 match kind {
3263 kinds::LABEL => {
3264 let nat = natural(h.0);
3265 match p.width {
3266 Some(pw) if nat.width > pw => {
3267 let mut w = 0.0;
3269 let mut hh = 0.0;
3270 unsafe { ffi::day_xaml_measure(h.0, pw, -1.0, &raw mut w, &raw mut hh) };
3271 Size::new(pw.ceil(), hh.ceil())
3272 }
3273 _ => Size::new(nat.width.ceil(), nat.height.ceil()),
3274 }
3275 }
3276 kinds::BUTTON => {
3279 let nat = natural(h.0);
3280 Size::new(nat.width.ceil(), nat.height.ceil())
3281 }
3282 kinds::SLIDER => Size::new(p.width.unwrap_or(180.0), natural(h.0).height.max(24.0)),
3283 kinds::PICKER => picker::measure_any(self, h, p),
3284 kinds::TEXT_AREA => textarea::measure_any(self, h, p),
3285 kinds::TEXT_FIELD => Size::new(p.width.unwrap_or(180.0), natural(h.0).height.max(28.0)),
3286 kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 1.0),
3287 kinds::LIST => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
3289 kinds::NAV_MENU => {
3290 if NAV_MENU_HOST.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
3293 return Size::new(0.0, 0.0);
3294 }
3295 let (rows, headings) = NAV_MENU_ROWS
3296 .with(|m| m.borrow().get(&(h.0 as usize)).copied().unwrap_or((0, 0)));
3297 Size::new(
3298 p.width.unwrap_or(220.0),
3299 p.height
3300 .unwrap_or(rows as f64 * 40.0 + headings as f64 * 32.0 + 8.0),
3301 )
3302 }
3303 kinds::PROGRESS => {
3304 let nat = natural(h.0);
3306 if unsafe { ffi::day_xaml_progress_is_ring(h.0) } != 0 {
3307 let side = nat.width.max(nat.height).max(20.0);
3308 Size::new(side, side)
3309 } else {
3310 Size::new(p.width.unwrap_or(nat.width.max(20.0)), nat.height.max(6.0))
3311 }
3312 }
3313 _ => {
3314 if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
3315 return measure(self, h, p);
3316 }
3317 let nat = natural(h.0);
3318 Size::new(
3319 p.width.unwrap_or(nat.width).ceil(),
3320 p.height.unwrap_or(nat.height).ceil(),
3321 )
3322 }
3323 }
3324 }
3325
3326 fn set_cursor(&mut self, h: &WinHandle, cursor: Cursor) {
3327 unsafe { ffi::day_xaml_set_cursor(h.0, win_cursor_code(&cursor)) };
3332 }
3333
3334 fn set_selectable(&mut self, h: &WinHandle, selectable: bool) -> Option<WinHandle> {
3335 unsafe { ffi::day_xaml_label_set_selectable(h.0, c_int::from(selectable)) };
3337 None
3338 }
3339
3340 fn set_input_traits(&mut self, h: &WinHandle, traits: &InputTraits) -> Option<WinHandle> {
3345 let key = h.0 as usize;
3346 let node = TEXT_FIELD_NODE.with(|m| m.borrow().get(&key).copied())?;
3347 let swapped = unsafe {
3348 ffi::day_xaml_field_set_secure(h.0, c_int::from(traits.secure), node, on_text, on_focus)
3349 };
3350 let live = if swapped.is_null() { h.0 } else { swapped };
3351 if traits.secure && unsafe { ffi::day_xaml_field_is_secure(live) } == 0 {
3354 log::error!(
3355 "day-toolkit-winui: a secure text field could not be rebuilt as a PasswordBox; its \
3356 characters are showing"
3357 );
3358 }
3359 let (scope, plain) = match traits.purpose {
3364 InputPurpose::Text => (0, false),
3365 InputPurpose::Name => (1, true),
3366 InputPurpose::Email => (2, true),
3367 InputPurpose::Url => (3, true),
3368 InputPurpose::Phone => (4, true),
3369 InputPurpose::Number | InputPurpose::Decimal => (5, false),
3370 InputPurpose::OneTimeCode => (5, true),
3371 InputPurpose::Username | InputPurpose::Password | InputPurpose::NewPassword => {
3372 (0, true)
3373 }
3374 };
3375 unsafe {
3379 ffi::day_xaml_field_set_traits(
3380 live,
3381 c_int::from(traits.read_only),
3382 scope,
3383 c_int::from(plain),
3384 );
3385 };
3386 if swapped.is_null() {
3387 return None;
3388 }
3389 let new = WinHandle(swapped);
3390 TEXT_FIELD_NODE.with(|m| m.borrow_mut().insert(swapped as usize, node));
3393 let gestures: Vec<c_int> = GESTURES.with(|g| {
3394 g.borrow()
3395 .iter()
3396 .filter(|(ptr, _)| *ptr == key)
3397 .map(|(_, k)| *k)
3398 .collect()
3399 });
3400 for k in gestures {
3401 GESTURES.with(|g| g.borrow_mut().insert((swapped as usize, k)));
3402 unsafe { ffi::day_xaml_enable_gesture(swapped, node, k, on_gesture) };
3403 }
3404 transfer::migrate(key, &new);
3405 unsafe { ffi::day_xaml_on_control_loaded(swapped, node, control_loaded) };
3407 self.release(*h);
3408 Some(new)
3409 }
3410
3411 fn set_opacity(&mut self, h: &WinHandle, opacity: f64, anim: Option<&AnimSpec>) {
3415 let anim = XamlAnim::new(anim);
3416 unsafe { ffi::day_xaml_set_opacity(h.0, opacity, XamlAnim::ptr(anim.as_ref())) };
3417 }
3418
3419 fn set_transform(&mut self, h: &WinHandle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
3420 let anim = XamlAnim::new(anim);
3423 unsafe {
3424 ffi::day_xaml_set_transform(
3425 h.0,
3426 t.tx,
3427 t.ty,
3428 t.sx,
3429 t.sy,
3430 t.rotation.degrees(),
3431 XamlAnim::ptr(anim.as_ref()),
3432 );
3433 };
3434 }
3435
3436 fn first_baseline(&mut self, h: &WinHandle, kind: PieceKind, size: Size) -> Option<f64> {
3441 if !day_spec::kind_has_baseline(kind) {
3442 return None;
3443 }
3444 let b = unsafe { ffi::day_xaml_baseline(h.0, size.height) };
3445 (b >= 0.0).then_some(b)
3446 }
3447
3448 fn set_frame(&mut self, h: &WinHandle, frame: Rect, anim: Option<&AnimSpec>) {
3449 if SPLIT_SIDEBAR_PAGES.with(|m| m.borrow().contains(&(h.0 as usize))) {
3453 unsafe {
3454 ffi::day_xaml_set_geometry(
3455 h.0,
3456 0,
3457 0,
3458 frame.size.width.round() as c_int,
3459 NAV_PANE_HEADER_H,
3460 );
3461 };
3462 return;
3463 }
3464 if let Some(anim) = XamlAnim::new(anim) {
3465 unsafe {
3467 ffi::day_xaml_set_geometry_animated(
3468 h.0,
3469 frame.origin.x.round(),
3470 frame.origin.y.round(),
3471 frame.size.width.round(),
3472 frame.size.height.round(),
3473 &raw const anim.raw,
3474 );
3475 }
3476 } else {
3477 unsafe {
3478 ffi::day_xaml_set_geometry(
3479 h.0,
3480 frame.origin.x.round() as c_int,
3481 frame.origin.y.round() as c_int,
3482 frame.size.width.round() as c_int,
3483 frame.size.height.round() as c_int,
3484 );
3485 };
3486 }
3487 list::frame(h, frame);
3489 let elided_at = LABEL_ELIDE.with(|m| m.borrow().get(&(h.0 as usize)).map(|e| e.width));
3491 if let Some(width) = elided_at
3492 && (width - frame.size.width).abs() > 0.25
3493 {
3494 elide_label(h.0, frame.size.width);
3495 }
3496 }
3497
3498 fn set_scroll_content(&mut self, h: &WinHandle, content: Size) {
3501 if let Some(c) = SCROLL_STATE.with(|m| m.borrow().get(&(h.0 as usize)).copied()) {
3502 unsafe {
3503 ffi::day_xaml_scroll_set_content_size(
3504 c,
3505 content.width.round() as c_int,
3506 content.height.round() as c_int,
3507 );
3508 };
3509 }
3510 }
3511
3512 fn list_row_metrics(&mut self, _h: &WinHandle) -> day_spec::RowMetrics {
3514 day_spec::RowMetrics {
3515 insets: day_spec::Insets {
3516 top: 0.0,
3517 leading: 12.0,
3518 bottom: 0.0,
3519 trailing: 12.0,
3520 },
3521 min_height: 40.0,
3522 }
3523 }
3524
3525 fn scroll_to(&mut self, h: &WinHandle, target: Rect, animated: bool) {
3526 unsafe {
3527 ffi::day_xaml_scroll_to(
3528 h.0,
3529 target.origin.y.round() as c_int,
3530 target.size.height.round() as c_int,
3531 c_int::from(animated),
3532 );
3533 };
3534 }
3535
3536 fn scroll_offset(&mut self, h: &WinHandle) -> Point {
3537 let (mut x, mut y) = (0.0_f64, 0.0_f64);
3538 unsafe { ffi::day_xaml_scroll_offset(h.0, &raw mut x, &raw mut y) };
3539 Point::new(x, y)
3540 }
3541
3542 fn enable_gesture(&mut self, h: &WinHandle, node: NodeId, kind: day_spec::GestureKind) {
3543 let k = match kind {
3544 day_spec::GestureKind::DoubleTap => 8,
3548 day_spec::GestureKind::Press => 9,
3549 day_spec::GestureKind::Touches => 10,
3550 day_spec::GestureKind::Tap => 0,
3551 day_spec::GestureKind::LongPress => 1,
3552 day_spec::GestureKind::Drag => 2,
3553 day_spec::GestureKind::Hover => 3,
3554 day_spec::GestureKind::Pinch => 4,
3557 day_spec::GestureKind::Rotate => 7,
3559 day_spec::GestureKind::Pan => {
3560 if CANVASES.with(|c| c.borrow().contains(&(h.0 as usize))) {
3561 5
3562 } else {
3563 6
3564 }
3565 }
3566 };
3567 if !GESTURES.with(|g| g.borrow_mut().insert((h.0 as usize, k))) {
3569 return;
3570 }
3571 unsafe { ffi::day_xaml_enable_gesture(h.0, node.0, k, on_gesture) };
3572 }
3573
3574 fn focus(&mut self, h: &WinHandle, _node: NodeId, focused: bool) {
3575 unsafe { ffi::day_xaml_control_focus(h.0, c_int::from(focused)) };
3578 }
3579
3580 fn set_event_sink(&mut self, sink: EventSink) {
3581 SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
3582 }
3583
3584 fn set_a11y(&mut self, h: &WinHandle, a11y: &A11yProps) {
3585 use day_spec::Role;
3586 if let Some(id) = &a11y.identifier {
3587 unsafe { ffi::day_xaml_set_name(h.0, cstr(id).as_ptr()) };
3588 }
3589 let (role, level) = match a11y.role {
3593 Role::None => (0, 0),
3594 Role::Button => (1, 0),
3595 Role::Toggle => (2, 0),
3596 Role::Slider => (3, 0),
3597 Role::TextInput => (4, 0),
3598 Role::Heading(n) => (5, c_int::from(n)),
3599 Role::Image => (6, 0),
3600 Role::Meter => (7, 0),
3601 Role::Group => (8, 0),
3602 Role::Tree => (9, 0),
3603 Role::TreeItem => (10, 0),
3604 Role::Tab => (11, 0),
3605 Role::TabList => (12, 0),
3606 };
3607 let label = cstr(a11y.label.as_deref().unwrap_or(""));
3608 let hint = cstr(a11y.hint.as_deref().unwrap_or(""));
3609 let value = cstr(a11y.value.as_deref().unwrap_or(""));
3610 let hidden = c_int::from(a11y.hidden || a11y.decorative);
3611 unsafe {
3612 ffi::day_xaml_set_a11y(
3613 h.0,
3614 label.as_ptr(),
3615 hint.as_ptr(),
3616 value.as_ptr(),
3617 role,
3618 level,
3619 hidden,
3620 );
3621 };
3622 }
3623
3624 fn announce(&mut self, text: &str, urgent: bool) {
3625 unsafe { ffi::day_xaml_announce(cstr(text).as_ptr(), c_int::from(urgent)) };
3626 }
3627
3628 fn read_native(&self, h: &WinHandle) -> day_spec::NativeSnapshot {
3633 use day_spec::Role;
3634 let mut raw = ffi::DayXamlNative {
3635 found: 0,
3636 role: 0,
3637 level: 0,
3638 label: std::ptr::null_mut(),
3639 value: std::ptr::null_mut(),
3640 identifier: std::ptr::null_mut(),
3641 text: std::ptr::null_mut(),
3642 has_number: 0,
3643 number: 0.0,
3644 checked: -1,
3645 enabled: -1,
3646 visible: -1,
3647 has_frame: 0,
3648 x: 0.0,
3649 y: 0.0,
3650 w: 0.0,
3651 h: 0.0,
3652 };
3653 unsafe { ffi::day_xaml_read_native(h.0, &raw mut raw) };
3655 let take = |p: *mut c_char| -> Option<String> {
3657 if p.is_null() {
3658 return None;
3659 }
3660 unsafe {
3663 let s = CStr::from_ptr(p).to_string_lossy().into_owned();
3664 ffi::day_xaml_string_free(p);
3665 Some(s)
3666 }
3667 };
3668 let tri = |v: c_int| (v >= 0).then_some(v != 0);
3669 let found = raw.found != 0;
3670 let role = match raw.role {
3671 1 => Role::Button,
3672 2 => Role::Toggle,
3673 3 => Role::Slider,
3674 4 => Role::TextInput,
3675 5 => Role::Heading(raw.level.clamp(1, 9) as u8),
3676 6 => Role::Image,
3677 7 => Role::Meter,
3678 8 => Role::Group,
3679 9 => Role::Tree,
3680 10 => Role::TreeItem,
3681 11 => Role::Tab,
3682 12 => Role::TabList,
3683 _ => Role::None,
3684 };
3685 let (label, value, identifier) = (take(raw.label), take(raw.value), take(raw.identifier));
3686 let shown = take(raw.text);
3688 let text = LABEL_ELIDE
3689 .with(|m| m.borrow().get(&(h.0 as usize)).map(|e| e.full.clone()))
3690 .or(shown);
3691 day_spec::NativeSnapshot {
3692 found,
3693 role: if found { role } else { Role::None },
3694 label: label.filter(|_| found),
3695 value: value.filter(|_| found),
3696 identifier: identifier.filter(|_| found),
3697 text,
3698 number: (raw.has_number != 0).then_some(raw.number),
3699 checked: tri(raw.checked),
3700 enabled: tri(raw.enabled),
3701 visible: tri(raw.visible),
3702 frame: (raw.has_frame != 0).then(|| Rect::new(raw.x, raw.y, raw.w, raw.h)),
3703 }
3704 }
3705
3706 fn read_displayed(&self, h: &WinHandle) -> day_spec::Displayed {
3710 let mut out = [0.0f64; 11];
3711 let read = unsafe { ffi::day_xaml_read_displayed(h.0, out.as_mut_ptr()) };
3713 let mut shown = day_spec::Displayed::default();
3714 if read & 1 != 0 {
3715 shown.opacity = Some(out[0]);
3716 }
3717 if read & 2 != 0 {
3718 shown.translation = Some(Point::new(out[1], out[2]));
3719 }
3720 if read & 4 != 0 {
3721 shown.frame = Some(Rect::new(out[3], out[4], out[5], out[6]));
3722 }
3723 if read & 8 != 0 {
3724 shown.background = Some(day_spec::Color::rgba(out[7], out[8], out[9], out[10]));
3725 }
3726 shown
3727 }
3728
3729 fn attach_tree(&mut self, host: &WinHandle, source: day_spec::TreeSource) {
3730 tree::attach(host.0 as usize, source);
3731 }
3732
3733 fn attach_list(&mut self, host: &WinHandle, source: day_spec::ListSource) {
3734 list::attach(host, source);
3735 }
3736
3737 fn set_context_menu(&mut self, h: &WinHandle, _node: NodeId, items: &[day_spec::MenuItem]) {
3738 let mut spec = String::new();
3742 serialize_menu_xaml(items, &mut spec);
3743 unsafe { ffi::day_xaml_set_context_menu(h.0, cstr(&spec).as_ptr()) };
3744 }
3745
3746 fn set_button_menu(&mut self, h: &WinHandle, node: NodeId, f: day_spec::ContextMenuFn) {
3747 BUTTON_MENUS.with(|m| m.borrow_mut().insert(node.0, (h.0 as usize, f)));
3749 }
3750
3751 fn edit_toolbar(&mut self, h: &WinHandle, ops: &[day_spec::ToolbarOp]) -> bool {
3752 self.edit_toolbar(h, ops)
3753 }
3754
3755 fn update_toolbar(&mut self, h: &WinHandle, patch: &day_spec::ToolbarPatch) {
3756 self.patch_toolbar(h, patch);
3757 }
3758
3759 fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
3760 if self.window.is_null() {
3761 return;
3762 }
3763 let items = day_core::menu::standard_menu_bar_for(
3766 day_core::menu::MenuBarStyle::Windows,
3767 items.to_vec(),
3768 );
3769 let mut spec = String::new();
3770 serialize_menu_xaml(&items, &mut spec);
3771 self.menu_spec.clone_from(&spec);
3775 let c = cstr(&spec);
3776 unsafe { ffi::day_xaml_set_app_menu(self.window, c.as_ptr()) };
3777 for w in self.secondary.iter().filter(|w| !w.menuless) {
3780 unsafe { ffi::day_xaml_window_set_menu2(w.win, c.as_ptr()) };
3781 }
3782 }
3783
3784 fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
3785 use day_spec::present::PresentSpec;
3786 match spec {
3787 PresentSpec::Dialog { .. } => unsafe {
3788 ffi::day_xaml_present_dialog(
3789 req,
3790 cstr(spec.title()).as_ptr(),
3791 cstr(spec.message().unwrap_or("")).as_ptr(),
3792 cstr(&spec.buttons_joined()).as_ptr(),
3793 cstr(&spec.roles_joined()).as_ptr(),
3794 self.window,
3795 );
3796 },
3797 PresentSpec::Prompt {
3798 placeholder,
3799 initial,
3800 ok,
3801 cancel,
3802 ..
3803 } => unsafe {
3804 ffi::day_xaml_present_prompt(
3805 req,
3806 cstr(spec.title()).as_ptr(),
3807 cstr(spec.message().unwrap_or("")).as_ptr(),
3808 cstr(placeholder).as_ptr(),
3809 cstr(initial).as_ptr(),
3810 cstr(ok).as_ptr(),
3811 cstr(cancel).as_ptr(),
3812 self.window,
3813 );
3814 },
3815 PresentSpec::OpenFile { multiple, .. } => unsafe {
3816 ffi::day_xaml_present_file_open(
3817 req,
3818 cstr(spec.title()).as_ptr(),
3819 cstr(&spec.filters_joined()).as_ptr(),
3820 c_int::from(*multiple),
3821 self.window,
3822 );
3823 },
3824 PresentSpec::OpenFolder { .. } => unsafe {
3825 ffi::day_xaml_present_folder_open(req, cstr(spec.title()).as_ptr(), self.window);
3826 },
3827 PresentSpec::SaveFile { suggested_name, .. } => unsafe {
3828 ffi::day_xaml_present_file_save(
3830 req,
3831 cstr(spec.title()).as_ptr(),
3832 cstr(suggested_name).as_ptr(),
3833 cstr(&spec.filters_joined()).as_ptr(),
3834 self.window,
3835 );
3836 },
3837 }
3838 }
3839
3840 fn dismiss(&mut self, req: u64) {
3841 unsafe { ffi::day_xaml_dismiss_present(req) };
3842 }
3843
3844 #[cfg(windows)]
3845 fn share_support(&self) -> day_spec::Support {
3846 day_spec::Support::Native
3847 }
3848 #[cfg(windows)]
3849 fn share(&mut self, spec: &day_spec::share::ShareSpec, _anchor: Option<&Self::Handle>) -> bool {
3850 let (url, title) = (spec.url.as_str(), spec.title.as_str());
3851 day_platform_windows::share::share(url, title)
3852 }
3853 fn open_url(&mut self, url: &str) {
3854 let c = cstr(url);
3855 unsafe { ffi::day_xaml_open_url(c.as_ptr()) };
3856 }
3857
3858 fn adopt(&mut self, raw: day_spec::RawHandle) -> WinHandle {
3859 WinHandle(raw)
3861 }
3862
3863 fn request_frame(
3864 &mut self,
3865 _host: &WinHandle,
3866 cb: day_spec::FrameCallback,
3867 ) -> day_spec::CancelFrame {
3868 extern "C" fn fire(token: u64, timestamp: f64) {
3869 Xaml::post(Box::new(move || {
3873 day_core::frame::native::deliver(token, day_spec::FrameStamp::new(timestamp));
3874 }));
3875 }
3876 let token = day_core::frame::native::register(cb);
3877 unsafe { ffi::day_xaml_request_frame(token, fire) };
3878 Box::new(move || {
3879 day_core::frame::native::cancel(token);
3880 unsafe { ffi::day_xaml_cancel_frame(token) };
3881 })
3882 }
3883
3884 fn replay(&mut self, h: &WinHandle, ops: &[DrawOp], _size: Size) {
3885 let ops = resolve_canvas_fonts(ops);
3887 let (nums, texts) = day_spec::encode_ops(&ops);
3888 let joined = cstr(&texts.join("\u{1f}"));
3889 unsafe {
3890 ffi::day_xaml_canvas_set_ops(h.0, nums.as_ptr(), nums.len() as c_int, joined.as_ptr());
3891 };
3892 }
3893
3894 fn native_document_tabs(&self) -> bool {
3895 cfg!(feature = "winui")
3896 }
3897
3898 fn open_window(
3899 &mut self,
3900 id: NodeId,
3901 options: &WindowOptions,
3902 kind: day_spec::WindowKind,
3903 ) -> day_spec::WindowOpenReply<WinHandle> {
3904 let fixed = c_int::from(kind.is_panel());
3905 let chrome = window_chrome(options);
3906 let win = unsafe {
3907 ffi::day_xaml_window_new2(
3908 cstr(&options.title).as_ptr(),
3909 options.size.width as c_int,
3910 options.size.height as c_int,
3911 id.0,
3912 fixed,
3913 &raw const chrome,
3914 )
3915 };
3916 if win.is_null() {
3917 return day_spec::WindowOpenReply::Unsupported;
3918 }
3919 if options.min_size.is_some() || options.max_size.is_some() {
3920 set_limits(win, options.min_size, options.max_size);
3921 }
3922 let content = unsafe { ffi::day_xaml_window_content2(win) };
3923 let menuless = kind.is_panel();
3930 if !menuless && !self.menu_spec.is_empty() {
3931 unsafe { ffi::day_xaml_window_set_menu2(win, cstr(&self.menu_spec).as_ptr()) };
3932 }
3933 self.secondary.push(XamlWin {
3934 win,
3935 content,
3936 menuless,
3937 });
3938 day_spec::WindowOpenReply::Open(WinHandle(content))
3939 }
3940
3941 fn close_window(&mut self, host: &WinHandle) {
3942 if let Some(w) = self.secondary.iter().find(|w| w.content == host.0) {
3943 unsafe { ffi::day_xaml_window_close2(w.win) };
3944 }
3945 }
3946
3947 fn quit_app(&mut self) {
3948 unsafe { ffi::day_xaml_quit() };
3951 }
3952
3953 fn focus_window(&mut self, host: &WinHandle) {
3954 if let Some(win) = self.window_token(host) {
3956 unsafe { ffi::day_xaml_window_raise2(win) };
3957 }
3958 }
3959
3960 fn set_window_title(&mut self, host: &WinHandle, title: &str) {
3961 if let Some(win) = self.window_token(host) {
3964 unsafe { ffi::day_xaml_window_set_title2(win, cstr(title).as_ptr()) };
3965 }
3966 }
3967
3968 fn set_drag_region(&mut self, h: &WinHandle, drag: bool) {
3973 DRAG_REGIONS.with(|d| {
3974 let mut d = d.borrow_mut();
3975 if drag {
3976 d.insert(h.0 as usize);
3977 } else {
3978 d.remove(&(h.0 as usize));
3979 }
3980 });
3981 unsafe { ffi::day_xaml_set_drag_region(h.0, c_int::from(drag)) };
3982 }
3983
3984 fn apply_window(&mut self, host: &WinHandle, change: &day_spec::WindowChange) {
3985 use day_spec::WindowChange as C;
3986 let Some(win) = self.window_token(host) else {
3988 return;
3989 };
3990 match change {
3991 C::State(state) => unsafe { ffi::day_xaml_window_set_state(win, state.code()) },
3994 C::ContentProtected(on) => unsafe {
3996 ffi::day_xaml_window_set_protected(win, c_int::from(*on));
3997 },
3998 C::Frame { origin, size } => unsafe {
4001 let p = origin.unwrap_or(Point::ZERO);
4002 let z = size.unwrap_or(Size::new(0.0, 0.0));
4003 ffi::day_xaml_window_set_frame(
4004 win,
4005 c_int::from(origin.is_some()),
4006 p.x,
4007 p.y,
4008 c_int::from(size.is_some()),
4009 z.width,
4010 z.height,
4011 );
4012 },
4013 C::Limits { min, max } => set_limits(win, *min, *max),
4015 C::Level(level) => unsafe {
4016 ffi::day_xaml_window_set_flag(
4017 win,
4018 0,
4019 c_int::from(*level == day_spec::WindowLevel::Floating),
4020 );
4021 },
4022 C::SkipTaskbar(skip) => unsafe {
4024 ffi::day_xaml_window_set_flag(win, 1, c_int::from(*skip));
4025 },
4026 C::Resizable(on) => unsafe { ffi::day_xaml_window_set_flag(win, 2, c_int::from(*on)) },
4027 C::Minimizable(on) => unsafe {
4028 ffi::day_xaml_window_set_flag(win, 3, c_int::from(*on));
4029 },
4030 C::Maximizable(on) => unsafe {
4031 ffi::day_xaml_window_set_flag(win, 4, c_int::from(*on));
4032 },
4033 C::Closable(on) => unsafe { ffi::day_xaml_window_set_flag(win, 5, c_int::from(*on)) },
4034 C::Visible(on) => unsafe { ffi::day_xaml_window_set_flag(win, 6, c_int::from(*on)) },
4035 C::Appearance(dark) => {
4037 unsafe { ffi::day_xaml_window_set_appearance(win, dark.map_or(-1, c_int::from)) };
4038 repaint_inks();
4040 }
4041 C::RequestAttention(a) => unsafe {
4043 ffi::day_xaml_window_attention(
4044 win,
4045 c_int::from(*a == day_spec::Attention::Critical),
4046 );
4047 },
4048 C::OnAllWorkspaces(_) => {}
4050 }
4051 }
4052
4053 fn window_frame(&self, host: &WinHandle) -> Option<day_spec::Rect> {
4054 let win = self.window_token(host)?;
4055 let mut r = [0.0f64; 4];
4056 (unsafe { ffi::day_xaml_window_frame(win, r.as_mut_ptr()) } != 0)
4057 .then(|| day_spec::Rect::new(r[0], r[1], r[2], r[3]))
4058 }
4059
4060 fn monitors(&self) -> Vec<day_spec::Monitor> {
4061 let count = unsafe { ffi::day_xaml_monitors(std::ptr::null_mut(), 0) }.max(0);
4062 let mut raw: Vec<ffi::DayXamlMonitor> = (0..count)
4063 .map(|_| ffi::DayXamlMonitor {
4064 frame: [0.0; 4],
4065 work: [0.0; 4],
4066 scale: 1.0,
4067 primary: 0,
4068 id: [0; 160],
4069 name: [0; 128],
4070 })
4071 .collect();
4072 let filled = unsafe { ffi::day_xaml_monitors(raw.as_mut_ptr(), count) }.clamp(0, count);
4073 raw.truncate(filled as usize);
4074 let text = |chars: &[c_char]| {
4075 unsafe { CStr::from_ptr(chars.as_ptr()) }
4077 .to_string_lossy()
4078 .into_owned()
4079 };
4080 let rect = |r: [f64; 4]| day_spec::Rect::new(r[0], r[1], r[2], r[3]);
4081 raw.iter()
4082 .map(|m| day_spec::Monitor {
4083 id: text(&m.id),
4084 name: text(&m.name),
4085 frame: rect(m.frame),
4086 work_area: rect(m.work),
4087 scale: m.scale,
4088 primary: m.primary != 0,
4089 })
4090 .collect()
4091 }
4092
4093 fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
4097 for item in items {
4098 let (glyph, image) = match &item.icon {
4099 Some(day_spec::Icon::Symbol(sym)) => {
4100 (toolbar::glyph_for(*sym).to_owned(), String::new())
4101 }
4102 Some(day_spec::Icon::Image(name)) => (String::new(), image_uri(name)),
4104 None => (String::new(), String::new()),
4105 };
4106 let tip = if item.tooltip.is_empty() {
4107 &item.title
4108 } else {
4109 &item.tooltip
4110 };
4111 let mut menu = String::new();
4112 serialize_menu_xaml(&item.menu, &mut menu);
4113 unsafe {
4114 ffi::day_xaml_status_set(
4115 cstr(&item.id).as_ptr(),
4116 cstr(tip).as_ptr(),
4117 cstr(&glyph).as_ptr(),
4118 cstr(&image).as_ptr(),
4119 c_int::from(item.template),
4120 item.activate,
4121 cstr(&menu).as_ptr(),
4122 );
4123 };
4124 }
4125 let ids = items
4126 .iter()
4127 .map(|i| i.id.as_str())
4128 .collect::<Vec<_>>()
4129 .join("\n");
4130 unsafe { ffi::day_xaml_status_retain(cstr(&ids).as_ptr()) };
4131 }
4132
4133 fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]) {
4135 set_jump_tasks(shortcuts);
4136 }
4137
4138 fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
4140 use day_spec::AppProgress as P;
4141 let (kind, value) = match progress {
4142 P::None => (0, 0.0),
4143 P::Indeterminate => (1, 0.0),
4144 P::Value(v) => (2, v),
4145 P::Paused(v) => (3, v),
4146 P::Error(v) => (4, v),
4147 };
4148 unsafe { ffi::day_xaml_set_app_progress(kind, value) };
4149 }
4150
4151 fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
4154 use day_spec::AppBadge as B;
4155 let (kind, count) = match badge {
4156 B::None => (0, 0),
4157 B::Count(n) => (1, *n),
4158 B::Dot => (2, 0),
4159 B::Text(_) => return,
4160 };
4161 unsafe { ffi::day_xaml_set_app_badge(kind, count) };
4162 }
4163
4164 fn set_keep_running(&mut self, keep: bool) {
4168 unsafe { ffi::day_xaml_set_keep_running(c_int::from(keep)) };
4169 }
4170
4171 fn snapshot_window_of(&mut self, host: &WinHandle) -> Result<Vec<u8>, String> {
4175 let Some(w) = self.secondary.iter().find(|w| w.content == host.0) else {
4176 return self.snapshot_window();
4178 };
4179 let win = w.win;
4180 snapshot_via(|path| unsafe { ffi::day_xaml_snapshot_png2(win, path) })
4181 }
4182
4183 fn toggle_sidebar(&mut self, _host: &WinHandle) -> bool {
4184 unsafe { ffi::day_xaml_toggle_sidebar() != 0 }
4188 }
4189
4190 fn set_appearance(&mut self, dark: Option<bool>) {
4196 let mode = match dark {
4197 None => 0, Some(false) => 1, Some(true) => 2, };
4201 unsafe { ffi::day_xaml_set_appearance(mode) };
4202 repaint_inks();
4204 }
4205
4206 fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
4209 theme_color(role, self.dark_mode())
4210 }
4211
4212 fn dark_mode(&mut self) -> bool {
4218 unsafe { ffi::day_xaml_is_dark() != 0 }
4219 }
4220
4221 fn reduce_motion(&mut self) -> bool {
4225 unsafe { ffi::day_xaml_reduce_motion() != 0 }
4226 }
4227
4228 fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
4235 let held =
4236 unsafe { ffi::day_xaml_image_decode(id.0, bytes.as_ptr(), bytes.len() as c_int) != 0 };
4237 let format = day_spec::ImageFormat::sniff(bytes);
4238 let event = if let (true, Some((w, h))) = (held, day_spec::ImageFormat::dimensions(bytes)) {
4239 let info = day_spec::BitmapInfo {
4240 pixels: Size::new(f64::from(w), f64::from(h)),
4241 scale: 1.0,
4243 format,
4244 has_alpha: !matches!(
4247 format,
4248 Some(day_spec::ImageFormat::Jpeg | day_spec::ImageFormat::Bmp)
4249 ),
4250 };
4251 BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
4252 Event::ImageDecoded {
4253 req,
4254 result: Ok(info),
4255 }
4256 } else {
4257 unsafe { ffi::day_xaml_image_release(id.0) };
4260 Event::ImageDecoded {
4261 req,
4262 result: Err(day_spec::ImageError::Decode),
4263 }
4264 };
4265 emit(day_spec::WINDOW_NODE, event);
4266 }
4267
4268 fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
4269 BITMAP_INFO.with(|m| m.borrow().get(&id.0).copied())
4270 }
4271
4272 #[cfg(feature = "winui")]
4273 fn render_bitmap(
4274 &mut self,
4275 req: u64,
4276 id: day_spec::BitmapId,
4277 ops: &[DrawOp],
4278 size: Size,
4279 scale: f64,
4280 ) {
4281 let (width, height) = day_spec::export_pixels(size, scale);
4282 let (nums, texts) = day_spec::encode_ops(&resolve_canvas_fonts(ops));
4283 let texts = cstr(&texts.join("\u{1f}"));
4284 let rc = unsafe {
4286 ffi::day_xaml_canvas_bitmap(
4287 id.0,
4288 nums.as_ptr(),
4289 nums.len() as c_int,
4290 texts.as_ptr(),
4291 width as c_int,
4292 height as c_int,
4293 scale,
4294 )
4295 };
4296 let result = if rc == 0 {
4297 let info = day_spec::BitmapInfo {
4298 pixels: Size::new(f64::from(width), f64::from(height)),
4299 scale,
4300 format: None,
4301 has_alpha: true,
4302 };
4303 BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
4304 Ok(info)
4305 } else {
4306 Err(day_spec::ExportError::Failed(format!(
4307 "Win2D bitmap rendering failed ({rc})"
4308 )))
4309 };
4310 emit(day_spec::WINDOW_NODE, Event::BitmapRendered { req, result });
4311 }
4312
4313 #[cfg(feature = "winui")]
4314 fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
4315 vec![day_spec::ImageFormat::Png]
4316 }
4317
4318 #[cfg(feature = "winui")]
4319 fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
4320 let mut result = Err(day_spec::ImageError::Encode);
4321 if spec.format == day_spec::ImageFormat::Png {
4322 let fit = spec.fit.unwrap_or(Size::ZERO);
4323 let mut len = 0;
4324 unsafe {
4326 let bytes = ffi::day_xaml_encode_png(
4327 id.0,
4328 fit.width as c_int,
4329 fit.height as c_int,
4330 &raw mut len,
4331 );
4332 if !bytes.is_null() {
4333 result = Ok(std::slice::from_raw_parts(bytes, len as usize).to_vec());
4334 ffi::day_xaml_bytes_free(bytes);
4335 }
4336 }
4337 }
4338 emit(day_spec::WINDOW_NODE, Event::ImageEncoded { req, result });
4339 }
4340
4341 fn release_image(&mut self, id: day_spec::BitmapId) {
4342 BITMAP_INFO.with(|m| {
4343 m.borrow_mut().remove(&id.0);
4344 });
4345 unsafe { ffi::day_xaml_image_release(id.0) };
4347 }
4348
4349 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
4350 if self.window.is_null() {
4351 return Err("no window".into());
4352 }
4353 let win = self.window;
4354 snapshot_via(|path| unsafe { ffi::day_xaml_snapshot_png(win, path) })
4355 }
4356
4357 fn snapshot_origin(&mut self, _root: &WinHandle) -> Option<Point> {
4361 if self.window.is_null() {
4362 return None;
4363 }
4364 let mut out = [0.0f64; 2];
4365 let rc = unsafe { ffi::day_xaml_snapshot_origin(self.window, out.as_mut_ptr()) };
4368 (rc == 0).then(|| Point::new(out[0], out[1]))
4369 }
4370
4371 fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
4374 unsafe {
4377 let p = ffi::day_xaml_font_families();
4378 if p.is_null() {
4379 return Vec::new();
4380 }
4381 let text = std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned();
4382 ffi::day_xaml_string_free(p);
4383 day_spec::parse_font_list(&text)
4384 }
4385 }
4386
4387 fn measure_text(
4389 &mut self,
4390 text: &str,
4391 size: f64,
4392 font: &day_spec::CanvasFont,
4393 ) -> Option<day_spec::TextMetrics> {
4394 let text = cstr(text);
4395 let family = cstr(&font.family.as_deref().map_or_default(canvas_family));
4397 let mut out = [0.0f64; 8];
4398 let rc = unsafe {
4400 ffi::day_xaml_measure_text(
4401 text.as_ptr(),
4402 size,
4403 c_int::from(font.css_weight()),
4404 c_int::from(font.italic),
4405 family.as_ptr(),
4406 out.as_mut_ptr(),
4407 )
4408 };
4409 (rc == 0).then(|| day_spec::TextMetrics::from_slots(&out))
4410 }
4411}
4412
4413fn snapshot_via(capture: impl FnOnce(*const c_char) -> c_int) -> Result<Vec<u8>, String> {
4418 let path = std::env::temp_dir().join(format!("day-xaml-snap-{}.png", std::process::id()));
4419 let cpath = cstr(&path.to_string_lossy());
4420 let rc = capture(cpath.as_ptr());
4421 if rc != 0 {
4422 return Err(format!("snapshot failed (rc={rc})"));
4423 }
4424 let bytes = std::fs::read(&path).map_err(|e| e.to_string())?;
4425 let _ = std::fs::remove_file(&path);
4426 Ok(bytes)
4427}
4428
4429fn argb(c: impl Into<day_spec::Ink>) -> u32 {
4431 ink_argb(c.into(), &day_spec::Palette::current())
4432}
4433
4434fn ink_argb(ink: day_spec::Ink, palette: &day_spec::Palette) -> u32 {
4436 let c = ink.resolve(palette);
4437 let a = (c.a.clamp(0.0, 1.0) * 255.0) as u32;
4438 let r = (c.r.clamp(0.0, 1.0) * 255.0) as u32;
4439 let g = (c.g.clamp(0.0, 1.0) * 255.0) as u32;
4440 let b = (c.b.clamp(0.0, 1.0) * 255.0) as u32;
4441 (a << 24) | (r << 16) | (g << 8) | b
4442}
4443
4444fn color_of_argb(argb: u32) -> day_spec::Color {
4446 let channel = |shift: u32| f64::from((argb >> shift) & 0xff) / 255.0;
4447 day_spec::Color::rgba(channel(16), channel(8), channel(0), channel(24))
4448}
4449
4450fn role_keys(role: day_spec::SystemColor) -> (&'static [&'static CStr], f64) {
4455 use day_spec::SystemColor as R;
4456 match role {
4457 R::Accent => (&[c"AccentFillColorDefaultBrush"], 1.0),
4458 R::Text => (&[c"TextFillColorPrimaryBrush"], 1.0),
4459 R::SecondaryText => (&[c"TextFillColorSecondaryBrush"], 1.0),
4460 R::TertiaryText => (&[c"TextFillColorTertiaryBrush"], 1.0),
4461 R::Placeholder => (
4462 &[
4463 c"TextControlPlaceholderForeground",
4464 c"TextFillColorSecondaryBrush",
4465 ],
4466 1.0,
4467 ),
4468 R::Link => (
4469 &[c"HyperlinkForeground", c"AccentTextFillColorPrimaryBrush"],
4470 1.0,
4471 ),
4472 R::Separator => (&[c"DividerStrokeColorDefaultBrush"], 1.0),
4473 R::ControlFill => (&[c"ControlFillColorDefaultBrush"], 1.0),
4474 R::Background | R::GroupedBackground => (&[c"SolidBackgroundFillColorBaseBrush"], 1.0),
4475 R::Surface => (&[c"CardBackgroundFillColorDefaultBrush"], 1.0),
4476 R::ElevatedSurface => (&[c"SolidBackgroundFillColorTertiaryBrush"], 1.0),
4477 R::Selection => (
4478 &[
4479 c"TextControlSelectionHighlightColor",
4480 c"AccentFillColorDefaultBrush",
4481 ],
4482 0.35,
4483 ),
4484 R::Destructive => (&[c"SystemFillColorCriticalBrush"], 1.0),
4485 R::Success => (&[c"SystemFillColorSuccessBrush"], 1.0),
4486 R::Warning => (&[c"SystemFillColorCautionBrush"], 1.0),
4487 }
4488}
4489
4490fn theme_color(role: day_spec::SystemColor, dark: bool) -> day_spec::Color {
4493 let (keys, alpha) = role_keys(role);
4494 for key in keys {
4495 let mut packed: std::os::raw::c_uint = 0;
4496 let found =
4498 unsafe { ffi::day_xaml_theme_color(key.as_ptr(), c_int::from(dark), &raw mut packed) };
4499 if found != 0 {
4500 let mut c = color_of_argb(packed);
4501 c.a *= alpha;
4502 return c;
4503 }
4504 }
4505 role.fallback(dark)
4506}
4507
4508fn theme_palette(dark: bool) -> day_spec::Palette {
4510 day_spec::Palette {
4511 dark,
4512 colors: day_spec::SystemColor::ALL.map(|role| theme_color(role, dark)),
4513 }
4514}
4515
4516#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4518enum InkSlot {
4519 Surface,
4521 LabelColor,
4523 LabelRuns,
4525 ButtonTint,
4527 ImageTint,
4529}
4530
4531type Repaint = Rc<dyn Fn(*mut c_void, &day_spec::Palette)>;
4533
4534fn paint_inks(
4537 h: *mut c_void,
4538 slot: InkSlot,
4539 dynamic: bool,
4540 apply: impl Fn(*mut c_void, &day_spec::Palette) + 'static,
4541) {
4542 apply(h, &day_spec::Palette::current());
4543 keep_inks(h, slot, dynamic, apply);
4544}
4545
4546fn keep_inks(
4549 h: *mut c_void,
4550 slot: InkSlot,
4551 dynamic: bool,
4552 apply: impl Fn(*mut c_void, &day_spec::Palette) + 'static,
4553) {
4554 let key = (h as usize, slot);
4555 INKS.with(|m| {
4556 let mut m = m.borrow_mut();
4557 if dynamic {
4558 m.insert(key, Rc::new(apply));
4559 } else {
4560 m.remove(&key);
4561 }
4562 });
4563}
4564
4565fn repaint_inks() {
4570 let entries: Vec<(usize, Repaint)> = INKS.with(|m| {
4571 m.borrow()
4572 .iter()
4573 .map(|(&(h, _), apply)| (h, Rc::clone(apply)))
4574 .collect()
4575 });
4576 if entries.is_empty() {
4577 return;
4578 }
4579 let palettes = [theme_palette(false), theme_palette(true)];
4580 for (h, apply) in entries {
4581 let h = h as *mut c_void;
4582 let dark = unsafe { ffi::day_xaml_element_dark(h) } != 0;
4584 apply(h, &palettes[usize::from(dark)]);
4585 }
4586}
4587
4588fn join_sections(sections: &[Option<String>]) -> String {
4591 sections
4592 .iter()
4593 .map(|s| s.as_deref().unwrap_or_default())
4594 .collect::<Vec<_>>()
4595 .join("\n")
4596}
4597
4598#[derive(Clone, Debug, Default)]
4600struct Surface {
4601 props: ContainerProps,
4603 styled: bool,
4605}
4606
4607fn styled_surface(p: &ContainerProps) -> bool {
4611 p.role.is_none()
4612 && (p.border.is_some()
4613 || p.fill
4614 .as_ref()
4615 .is_some_and(|f| !matches!(f, day_spec::Paint::Solid(_)))
4616 || p.shadow.is_some()
4617 || (p.corner_radius > 0.0 && p.corners != day_spec::Corners::ALL))
4618}
4619
4620fn surface_is_dynamic(p: &ContainerProps) -> bool {
4622 p.fill.as_ref().is_some_and(day_spec::Paint::is_dynamic)
4623 || p.border.is_some_and(|b| b.color.is_dynamic())
4624 || p.shadow.is_some_and(|s| s.color.is_dynamic())
4625}
4626
4627fn gradient_stops(
4630 stops: &[(f64, day_spec::Ink)],
4631 palette: &day_spec::Palette,
4632) -> (Vec<c_double>, Vec<u32>) {
4633 stops
4634 .iter()
4635 .map(|&(at, color)| (at.clamp(0.0, 1.0), ink_argb(color, palette)))
4636 .unzip()
4637}
4638
4639unsafe fn realize_surface(h: *mut c_void, p: &ContainerProps) {
4646 let styled = styled_surface(p);
4647 unsafe {
4649 if styled {
4650 shape_surface(h, p);
4651 } else {
4652 if p.role == Some(day_spec::SurfaceRole::SectionCard) {
4653 ffi::day_xaml_container_set_card(h, p.corner_radius);
4655 }
4656 if p.role == Some(day_spec::SurfaceRole::Window) {
4657 ffi::day_xaml_cover_ground(h);
4659 }
4660 if p.corner_radius > 0.0 && p.role != Some(day_spec::SurfaceRole::SectionCard) {
4661 ffi::day_xaml_container_set_corner(h, p.corner_radius);
4662 }
4663 }
4664 }
4665 let surface = Surface {
4666 props: p.clone(),
4667 styled,
4668 };
4669 SURFACES.with(|m| m.borrow_mut().insert(h as usize, surface.clone()));
4670 paint_surface(h, surface, true);
4671}
4672
4673fn paint_surface(h: *mut c_void, surface: Surface, realize: bool) {
4676 let dynamic = surface_is_dynamic(&surface.props);
4677 paint_inks(h, InkSlot::Surface, dynamic, move |h, palette| {
4678 unsafe { surface_colors(h, &surface, palette, realize) };
4680 });
4681}
4682
4683unsafe fn shape_surface(h: *mut c_void, p: &ContainerProps) {
4689 unsafe {
4691 ffi::day_xaml_container_set_surface(
4692 h,
4693 p.corner_radius,
4694 c_int::from(p.corners.bits()),
4695 c_int::from(p.clips),
4696 );
4697 }
4698}
4699
4700unsafe fn surface_colors(
4708 h: *mut c_void,
4709 surface: &Surface,
4710 palette: &day_spec::Palette,
4711 realize: bool,
4712) {
4713 use day_spec::Paint;
4714 let p = &surface.props;
4715 unsafe {
4717 if !surface.styled {
4718 if let Some(Paint::Solid(ink)) = p.fill {
4719 ffi::day_xaml_container_set_bg(h, ink_argb(ink, palette));
4720 }
4721 return;
4722 }
4723 match &p.fill {
4724 Some(Paint::Solid(ink)) => ffi::day_xaml_container_set_bg(h, ink_argb(*ink, palette)),
4725 Some(Paint::Linear(g)) => {
4726 let line = [g.start.x, g.start.y, g.end.x, g.end.y];
4727 let (offsets, colors) = gradient_stops(&g.stops, palette);
4728 ffi::day_xaml_container_set_gradient(
4729 h,
4730 line.as_ptr(),
4731 offsets.as_ptr(),
4732 colors.as_ptr(),
4733 offsets.len() as c_int,
4734 );
4735 }
4736 Some(Paint::Radial(g)) => {
4737 let (offsets, colors) = gradient_stops(&g.stops, palette);
4738 ffi::day_xaml_container_set_radial(
4739 h,
4740 g.center.x,
4741 g.center.y,
4742 g.radius,
4743 offsets.as_ptr(),
4744 colors.as_ptr(),
4745 offsets.len() as c_int,
4746 );
4747 }
4748 Some(Paint::Conic(g)) => {
4749 let (offsets, colors) = gradient_stops(&g.stops, palette);
4750 ffi::day_xaml_container_set_conic(
4751 h,
4752 g.center.x,
4753 g.center.y,
4754 g.start.degrees(),
4755 offsets.as_ptr(),
4756 colors.as_ptr(),
4757 offsets.len() as c_int,
4758 );
4759 }
4760 None if !realize => ffi::day_xaml_container_set_bg(h, 0),
4761 None => {}
4762 }
4763 match p.border {
4764 Some(border) => {
4765 ffi::day_xaml_container_set_border(
4766 h,
4767 ink_argb(border.color, palette),
4768 border.width,
4769 );
4770 }
4771 None if !realize => ffi::day_xaml_container_set_border(h, 0, 0.0),
4772 None => {}
4773 }
4774 let shadow = p.shadow.filter(|s| s.color.resolve(palette).a > 0.0);
4775 match shadow {
4776 Some(s) => ffi::day_xaml_container_set_shadow(
4777 h,
4778 ink_argb(s.color, palette),
4779 s.blur,
4780 s.dx,
4781 s.dy,
4782 ),
4783 None if !realize => ffi::day_xaml_container_set_shadow(h, 0, 0.0, 0.0, 0.0),
4784 None => {}
4785 }
4786 }
4787}
4788
4789unsafe fn patch_fill(h: *mut c_void, fill: Option<&day_spec::Paint>, anim: Option<&AnimSpec>) {
4797 let mut surface = SURFACES
4798 .with(|m| m.borrow().get(&(h as usize)).cloned())
4799 .unwrap_or_default();
4800 surface.props.fill = fill.cloned();
4801 let solid = match fill {
4802 None => Some(None),
4803 Some(day_spec::Paint::Solid(ink)) => Some(Some(*ink)),
4804 Some(_) => None,
4805 };
4806 if let Some(solid) = solid {
4807 let anim = XamlAnim::new(anim.filter(|_| solid.is_some()));
4811 unsafe {
4813 ffi::day_xaml_container_animate_bg(
4814 h,
4815 argb(solid.unwrap_or(day_spec::Ink::CLEAR)),
4816 XamlAnim::ptr(anim.as_ref()),
4817 );
4818 }
4819 let dynamic = surface_is_dynamic(&surface.props);
4820 let kept = surface.clone();
4821 keep_inks(h, InkSlot::Surface, dynamic, move |h, palette| {
4822 unsafe { surface_colors(h, &kept, palette, false) };
4824 });
4825 } else {
4826 if !surface.styled {
4827 unsafe { shape_surface(h, &surface.props) };
4829 surface.styled = true;
4830 }
4831 paint_surface(h, surface.clone(), false);
4832 }
4833 SURFACES.with(|m| m.borrow_mut().insert(h as usize, surface));
4834}
4835
4836unsafe fn patch_surface(h: *mut c_void, p: &ContainerProps) {
4845 let mut surface = SURFACES
4846 .with(|m| m.borrow().get(&(h as usize)).cloned())
4847 .unwrap_or_default();
4848 if surface.props.role.is_some() {
4849 return;
4850 }
4851 surface.props = ContainerProps {
4852 role: None,
4853 ..p.clone()
4854 };
4855 surface.styled = true;
4856 unsafe { shape_surface(h, &surface.props) };
4858 SURFACES.with(|m| m.borrow_mut().insert(h as usize, surface.clone()));
4859 paint_surface(h, surface, false);
4860}
4861
4862#[cfg(test)]
4863mod styled_surface_tests {
4864 use super::*;
4865 use day_spec::{Border, Color, Corners, LinearGradient, Shadow, SurfaceRole};
4866
4867 fn plain() -> ContainerProps {
4868 ContainerProps {
4869 fill: Some(Color::rgb(0.0, 0.0, 1.0).into()),
4870 corner_radius: 12.0,
4871 clips: true,
4872 ..Default::default()
4873 }
4874 }
4875
4876 #[test]
4877 fn plain_fill_and_uniform_corners_keep_the_plain_path() {
4878 assert!(!styled_surface(&ContainerProps::default()));
4879 assert!(!styled_surface(&plain()));
4880 let square = ContainerProps {
4882 corner_radius: 0.0,
4883 corners: Corners::TOP,
4884 ..plain()
4885 };
4886 assert!(!styled_surface(&square));
4887 }
4888
4889 #[test]
4890 fn each_new_property_takes_the_styled_path() {
4891 let border = ContainerProps {
4892 border: Some(Border::new(Color::BLACK, 2.0)),
4893 ..plain()
4894 };
4895 let gradient = ContainerProps {
4896 fill: Some(LinearGradient::vertical(Color::WHITE, Color::BLACK).into()),
4897 ..plain()
4898 };
4899 let shadow = ContainerProps {
4900 shadow: Some(Shadow::new(Color::BLACK, 4.0)),
4901 clips: false,
4902 ..plain()
4903 };
4904 let corners = ContainerProps {
4905 corners: Corners::TOP,
4906 ..plain()
4907 };
4908 for props in [border, gradient, shadow, corners] {
4909 assert!(styled_surface(&props));
4910 }
4911 }
4912
4913 #[test]
4914 fn a_role_surface_keeps_its_theme_material() {
4915 let card = ContainerProps {
4916 role: Some(SurfaceRole::SectionCard),
4917 border: Some(Border::new(Color::BLACK, 2.0)),
4918 ..plain()
4919 };
4920 assert!(!styled_surface(&card));
4921 }
4922
4923 #[test]
4924 fn gradient_stops_split_into_clamped_offsets_and_argb() {
4925 let (offsets, colors) = gradient_stops(
4926 &[
4927 (-0.5, Color::rgb(1.0, 0.0, 0.0).into()),
4928 (0.5, Color::rgba(0.0, 1.0, 0.0, 0.0).into()),
4929 (1.5, Color::rgb(0.0, 0.0, 1.0).into()),
4930 ],
4931 &day_spec::Palette::fallback(false),
4932 );
4933 assert_eq!(offsets, [0.0, 0.5, 1.0]);
4934 assert_eq!(colors, [0xffff_0000, 0x0000_ff00, 0xff00_00ff]);
4935 }
4936
4937 #[test]
4938 fn radial_and_conic_fills_take_the_styled_path() {
4939 let stops = [(0.0, Color::WHITE), (1.0, Color::BLACK)];
4940 let radial = ContainerProps {
4941 fill: Some(
4942 day_spec::RadialGradient::new(day_spec::UnitPoint::CENTER, 0.5, stops).into(),
4943 ),
4944 ..plain()
4945 };
4946 let conic = ContainerProps {
4947 fill: Some(day_spec::ConicGradient::centered(day_spec::Angle::ZERO, stops).into()),
4948 ..plain()
4949 };
4950 assert!(styled_surface(&radial));
4951 assert!(styled_surface(&conic));
4952 }
4953
4954 #[test]
4955 fn an_ink_resolves_per_palette_and_only_dynamic_surfaces_are_kept() {
4956 let pair = day_spec::Ink::adaptive(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
4957 assert_eq!(
4958 ink_argb(pair, &day_spec::Palette::fallback(false)),
4959 0xffff_0000
4960 );
4961 assert_eq!(
4962 ink_argb(pair, &day_spec::Palette::fallback(true)),
4963 0xff00_00ff
4964 );
4965 assert!(!surface_is_dynamic(&plain()));
4966 let role = ContainerProps {
4967 border: Some(Border::new(day_spec::SystemColor::Separator, 1.0)),
4968 ..plain()
4969 };
4970 assert!(surface_is_dynamic(&role));
4971 assert_eq!(color_of_argb(0x80ff_0000).r, 1.0);
4972 assert!((color_of_argb(0x80ff_0000).a - 128.0 / 255.0).abs() < 1e-9);
4973 }
4974
4975 #[test]
4976 fn every_role_names_a_theme_resource() {
4977 for role in day_spec::SystemColor::ALL {
4978 let (keys, alpha) = role_keys(role);
4979 assert_ne!(keys.len(), 0);
4980 assert!(alpha > 0.0 && alpha <= 1.0);
4981 }
4982 }
4983}
4984
4985fn join_tints(tints: &[Option<day_spec::Ink>]) -> String {
4989 tints
4990 .iter()
4991 .map(|t| t.map_or(0, argb).to_string())
4992 .collect::<Vec<_>>()
4993 .join("\n")
4994}
4995
4996pub(crate) fn vector_geometry(name: &str) -> Option<String> {
4999 let path = day_spec::resource::resolve_vector_xaml(name)?;
5000 std::fs::read_to_string(path).ok()
5001}
5002
5003fn join_geoms(icons: &[Option<String>]) -> String {
5007 icons
5008 .iter()
5009 .map(|ic| {
5010 ic.as_deref()
5011 .and_then(vector_geometry)
5012 .map_or_default(|s| s.replace('\n', "\x1f"))
5013 })
5014 .collect::<Vec<_>>()
5015 .join("\n")
5016}
5017
5018fn icon_file_name(name: &str) -> String {
5029 day_spec::resource::resolve_image_file(name)
5030 .as_deref()
5031 .and_then(|p| p.file_name())
5032 .map_or_default(|n| n.to_string_lossy().into_owned())
5033}
5034
5035fn image_uri(source: &str) -> String {
5036 match day_spec::resource::resolve_image_file(source) {
5041 Some(p) => p.to_string_lossy().into_owned(),
5042 None => String::new(),
5043 }
5044}
5045
5046extern "C" fn win_resized(node: u64, w: c_int, h: c_int) {
5049 ffi_guard::contain((), || {
5050 emit(
5051 day_spec::NodeId(node),
5052 Event::WindowResized(Size::new(f64::from(w), f64::from(h))),
5053 );
5054 });
5055}
5056extern "C" fn win_closed(node: u64) {
5057 ffi_guard::contain((), || emit(day_spec::NodeId(node), Event::WindowClosed));
5058}
5059extern "C" fn primary_closed() {
5062 ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::WindowClosed));
5063}
5064extern "C" fn appearance_changed() {
5067 ffi_guard::contain((), || {
5068 day_core::note_appearance_changed();
5069 repaint_inks();
5070 });
5071}
5072extern "C" fn motion_changed() {
5076 ffi_guard::contain((), day_core::note_motion_changed);
5077}
5078extern "C" fn win_focused(node: u64, active: c_int) {
5079 ffi_guard::contain((), || {
5080 emit(day_spec::NodeId(node), Event::WindowFocused(active != 0));
5081 });
5082}
5083extern "C" fn win_state(node: u64, state: c_int) {
5087 ffi_guard::contain((), || {
5088 let state = day_spec::WindowState::from_code(state);
5089 log::debug!("xaml: window state now {state:?}");
5090 emit(day_spec::NodeId(node), Event::WindowStateChanged(state));
5091 });
5092}
5093extern "C" fn chrome_inset(node: u64, top: c_double) {
5100 ffi_guard::contain((), || {
5101 log::debug!("xaml: overlay title bar inset {top}");
5102 let insets = day_spec::Insets {
5103 top,
5104 ..Default::default()
5105 };
5106 if node != day_spec::WINDOW_NODE.0 {
5107 day_core::set_window_safe_area(day_core::id_to_rnode(NodeId(node)), insets);
5108 } else if !day_core::has_tree() {
5109 day_core::seed_safe_area(insets);
5110 } else {
5111 Xaml::post(Box::new(move || day_core::set_safe_area(insets)));
5112 }
5113 });
5114}
5115
5116fn app_id() -> String {
5119 std::env::var("DAY_APP_ID")
5120 .ok()
5121 .filter(|s| !s.is_empty())
5122 .or_else(|| option_env!("DAY_APP_ID").map(str::to_owned))
5123 .unwrap_or_default()
5124}
5125
5126extern "C" fn forwarded_args(data: *const c_char, len: c_int) {
5130 ffi_guard::contain((), || {
5131 if data.is_null() || len <= 0 {
5132 return;
5133 }
5134 let bytes = unsafe { std::slice::from_raw_parts(data.cast::<u8>(), len as usize) };
5136 let args: Vec<String> = bytes
5137 .split(|b| *b == 0)
5138 .map(|a| String::from_utf8_lossy(a).into_owned())
5139 .collect();
5140 Xaml::post(Box::new(move || day_core::forward_launch_args(args)));
5141 });
5142}
5143
5144fn set_jump_tasks(dynamic: &[day_spec::LauncherShortcut]) {
5148 let id = app_id();
5149 let clean = |s: &str| s.replace(['\t', '\n'], " ");
5150 let spec = dynamic
5151 .iter()
5152 .map(|s| (s.route.clone(), s.label.clone()))
5153 .chain(
5154 day_core::shortcuts::launcher_shortcuts()
5155 .into_iter()
5156 .map(|(route, key)| (route.to_owned(), day_localization::t(key))),
5157 )
5158 .map(|(route, label)| {
5159 format!(
5160 "{}\t{}",
5161 clean(&label),
5162 clean(&day_core::launch_link(&route))
5163 )
5164 })
5165 .collect::<Vec<_>>()
5166 .join("\n");
5167 unsafe { ffi::day_xaml_set_jump_tasks(cstr(&id).as_ptr(), cstr(&spec).as_ptr()) };
5168}
5169
5170fn set_limits(win: *mut c_void, min: Option<Size>, max: Option<Size>) {
5172 let min = min.unwrap_or(Size::new(0.0, 0.0));
5173 let max = max.unwrap_or(Size::new(0.0, 0.0));
5174 unsafe { ffi::day_xaml_window_set_limits(win, min.width, min.height, max.width, max.height) };
5175}
5176
5177extern "C" fn status_action(kind: c_int, id: u64) {
5180 ffi_guard::contain((), || {
5181 if kind == 1 {
5182 day_core::quit();
5183 } else {
5184 day_core::dispatch_menu_action(id);
5185 }
5186 });
5187}
5188
5189fn window_chrome(options: &WindowOptions) -> ffi::DayXamlChrome {
5191 use day_spec::WindowPlacement as P;
5192 use day_spec::{WindowBackground as B, WindowChrome as C, WindowMaterial as M};
5193 let (background, material) = match options.background {
5194 B::Opaque => (0, 0),
5195 B::Transparent => (1, 0),
5196 B::Material(M::Window) => (2, 0),
5197 B::Material(M::Sidebar) => (2, 1),
5198 B::Material(M::Transient) => (2, 2),
5199 };
5200 let (placement, x, y) = match options.placement {
5201 P::Automatic => (0, 0.0, 0.0),
5202 P::Centered => (1, 0.0, 0.0),
5203 P::At(p) => (2, p.x, p.y),
5204 };
5205 ffi::DayXamlChrome {
5206 chrome: match options.chrome {
5207 C::Standard => 0,
5208 C::Overlay => 1,
5209 C::Frameless => 2,
5210 },
5211 background,
5212 material,
5213 shadow: c_int::from(options.shadow),
5214 resizable: c_int::from(options.resizable),
5215 placement,
5216 x,
5217 y,
5218 }
5219}
5220
5221fn cover_frame(cover: *mut c_void, area: Size) -> (f64, Size) {
5230 if COVER_HALF.with(|s| s.borrow().contains(&(cover as usize))) {
5231 let h = (area.height * 0.5).floor();
5232 (area.height - h, Size::new(area.width, h))
5233 } else {
5234 (0.0, area)
5235 }
5236}
5237
5238fn cover_extent(window: *mut c_void) -> Size {
5239 let (mut w, mut h) = (0.0f64, 0.0f64);
5240 unsafe { ffi::day_xaml_window_chrome_size(window, &raw mut w, &raw mut h) };
5241 if w > 0.0 && h > 0.0 {
5242 Size::new(w, h)
5243 } else {
5244 LAST_WINDOW_SIZE.with(std::cell::Cell::get)
5245 }
5246}
5247
5248extern "C" fn window_resized(w: c_int, h: c_int) {
5249 ffi_guard::contain((), || {
5254 let size = Size::new(f64::from(w), f64::from(h));
5255 LAST_WINDOW_SIZE.with(|c| c.set(size));
5256 emit(day_spec::WINDOW_NODE, Event::WindowResized(size));
5257 let full = cover_extent(std::ptr::null_mut());
5261 COVERS.with(|c| {
5262 for (cover, node) in c.borrow().iter() {
5263 let (y, full) = cover_frame(*cover, full);
5264 unsafe {
5265 ffi::day_xaml_set_geometry(
5266 *cover,
5267 0,
5268 y.round() as c_int,
5269 full.width.round() as c_int,
5270 full.height.round() as c_int,
5271 );
5272 };
5273 emit(*node, Event::FrameChanged(full));
5274 }
5275 });
5276 });
5277}
5278
5279extern "C" fn control_loaded(id: u64) {
5280 ffi_guard::contain((), || {
5281 let post = LOADED_MEASURES.with(|pending| {
5282 let mut pending = pending.borrow_mut();
5283 let first = pending.is_empty();
5284 pending.insert(id);
5285 first
5286 });
5287 if !post {
5288 return;
5289 }
5290 let boxed: Box<dyn FnOnce() + Send> = Box::new(|| {
5294 let nodes = LOADED_MEASURES.with(|p| std::mem::take(&mut *p.borrow_mut()));
5295 day_core::try_with_tree(|t| {
5296 for id in nodes {
5297 let node = day_core::id_to_rnode(NodeId(id));
5298 if t.node_exists(node) {
5299 t.mark_needs_measure(node);
5300 }
5301 }
5302 t.layout_if_needed();
5303 });
5304 });
5305 let data = Box::into_raw(Box::new(boxed)).cast::<c_void>();
5306 unsafe { ffi::day_xaml_post(run_posted, data) };
5307 });
5308}
5309
5310extern "C" fn run_posted(data: *mut c_void) {
5311 let f: Box<Box<dyn FnOnce() + Send>> = unsafe { Box::from_raw(data.cast()) };
5314 ffi_guard::contain((), f);
5315}
5316
5317extern "C" fn present_cb(req: u64, tag: c_int, index: i64, text: *const c_char) {
5320 ffi_guard::contain((), || {
5321 let text = if text.is_null() {
5322 String::new()
5323 } else {
5324 unsafe { CStr::from_ptr(text) }
5325 .to_string_lossy()
5326 .into_owned()
5327 };
5328 let result = day_spec::present::PresentResult::decode(tag, index, text);
5329 emit(day_spec::WINDOW_NODE, Event::PresentResult { req, result });
5330 });
5331}
5332
5333extern "C" fn on_gesture(
5341 id: u64,
5342 phase: c_int,
5343 x: c_double,
5344 y: c_double,
5345 tx: c_double,
5346 ty: c_double,
5347) {
5348 use day_spec::DragPhase;
5349 ffi_guard::contain((), || {
5350 let at = Point::new(x, y);
5351 let ev = match phase {
5352 0 => Event::Tap(at),
5353 4 => Event::LongPress(at),
5354 16 => Event::DoubleTap(at),
5355 17 | 18 => Event::Press {
5356 pressed: phase == 17,
5357 location: at,
5358 },
5359 19 => Event::GestureVelocity {
5361 kind: day_spec::GestureKind::Drag,
5362 velocity: Point::new(tx, ty),
5363 },
5364 5..=7 => Event::Pinch {
5365 phase: match phase {
5366 5 => DragPhase::Began,
5367 7 => DragPhase::Ended,
5368 _ => DragPhase::Changed,
5369 },
5370 scale: tx,
5371 location: at,
5372 },
5373 13..=15 => Event::Rotate {
5374 phase: match phase {
5375 13 => DragPhase::Began,
5376 15 => DragPhase::Ended,
5377 _ => DragPhase::Changed,
5378 },
5379 rotation: tx,
5380 location: at,
5381 },
5382 8 => Event::Pan {
5383 phase: DragPhase::Changed,
5384 delta: Point::new(tx, ty),
5385 location: at,
5386 },
5387 10..=12 => Event::Hover {
5388 phase: match phase {
5389 10 => DragPhase::Began,
5390 12 => DragPhase::Ended,
5391 _ => DragPhase::Changed,
5392 },
5393 location: at,
5394 },
5395 1 => Event::Drag {
5396 phase: DragPhase::Began,
5397 location: at,
5398 translation: Point::ZERO,
5399 },
5400 3 => Event::Drag {
5401 phase: DragPhase::Ended,
5402 location: at,
5403 translation: Point::new(tx, ty),
5404 },
5405 _ => Event::Drag {
5406 phase: DragPhase::Changed,
5407 location: at,
5408 translation: Point::new(tx, ty),
5409 },
5410 };
5411 emit(NodeId(id), ev);
5412 });
5413}
5414
5415extern "C" fn on_touches(id: u64, encoded: *const c_char) {
5418 ffi_guard::contain((), || {
5419 if encoded.is_null() {
5420 return;
5421 }
5422 let encoded = unsafe { CStr::from_ptr(encoded) }.to_string_lossy();
5424 let touches = parse_touches(&encoded);
5425 if !touches.is_empty() {
5426 emit(NodeId(id), Event::Touches(touches));
5427 }
5428 });
5429}
5430
5431fn parse_touches(encoded: &str) -> Vec<day_spec::Touch> {
5433 use day_spec::{Touch, TouchPhase};
5434 encoded
5435 .split(';')
5436 .filter_map(|contact| {
5437 let mut f = contact.split(',');
5438 let id = f.next()?.parse::<u64>().ok()?;
5439 let phase = match f.next()?.parse::<u8>().ok()? {
5440 0 => TouchPhase::Began,
5441 1 => TouchPhase::Moved,
5442 2 => TouchPhase::Stationary,
5443 3 => TouchPhase::Ended,
5444 _ => TouchPhase::Cancelled,
5445 };
5446 let x = f.next()?.parse::<f64>().ok()?;
5447 let y = f.next()?.parse::<f64>().ok()?;
5448 let pressure = f.next()?.parse::<f64>().ok()?;
5449 let kind = pointer_kind(f.next()?.parse::<c_int>().ok()?);
5450 Some(
5451 Touch::new(id, phase, Point::new(x, y))
5452 .with_pressure(pressure)
5453 .with_kind(kind),
5454 )
5455 })
5456 .collect()
5457}
5458
5459fn pointer_kind(code: c_int) -> day_spec::PointerKind {
5461 match code {
5462 0 => day_spec::PointerKind::Touch,
5463 2 => day_spec::PointerKind::Stylus,
5464 _ => day_spec::PointerKind::Mouse,
5465 }
5466}
5467
5468#[cfg(feature = "winui")]
5472fn configure_scroll(sv: *mut c_void, id: NodeId, p: &day_spec::props::ScrollProps) {
5473 use day_spec::props::{ScrollIndicators, ScrollSnap};
5474 let (snap, interval) = match p.snap {
5475 ScrollSnap::None => (0, 0.0),
5476 ScrollSnap::Page => (1, 0.0),
5477 ScrollSnap::Interval(points) => (2, points),
5478 };
5479 let (zoom_min, zoom_max) = p.zoom.map_or((0.0, 0.0), |z| (z.min, z.max));
5480 unsafe {
5481 ffi::day_xaml_scroll_configure(
5482 sv,
5483 id.0,
5484 c_int::from(p.indicators == ScrollIndicators::Hidden),
5485 snap,
5486 interval,
5487 zoom_min,
5488 zoom_max,
5489 c_int::from(p.track_offset),
5490 c_int::from(p.track_phase),
5491 on_scroll_event,
5492 );
5493 }
5494}
5495
5496#[cfg(not(feature = "winui"))]
5498fn configure_scroll(_sv: *mut c_void, _id: NodeId, _p: &day_spec::props::ScrollProps) {}
5499
5500#[cfg(feature = "winui")]
5503extern "C" fn on_scroll_event(id: u64, kind: c_int, a: c_double, b: c_double) {
5504 ffi_guard::contain((), || {
5505 let event = match kind {
5506 0 => Event::ScrollChanged(Point::new(a, b)),
5507 1 => Event::ScrollPhase(match a as i32 {
5508 1 => day_spec::ScrollPhase::Dragging,
5509 2 => day_spec::ScrollPhase::Coasting,
5510 _ => day_spec::ScrollPhase::Idle,
5511 }),
5512 _ => Event::ScrollZoomed(a),
5513 };
5514 emit(NodeId(id), event);
5515 });
5516}
5517
5518extern "C" fn text_scale_changed() {
5520 ffi_guard::contain((), day_core::note_text_size_changed);
5521}
5522
5523extern "C" fn on_pointer_kind(code: c_int) {
5525 ffi_guard::contain((), || {
5526 emit(
5527 day_spec::WINDOW_NODE,
5528 Event::PointerKindChanged(pointer_kind(code)),
5529 );
5530 });
5531}
5532
5533#[cfg(test)]
5534mod touches_tests {
5535 use super::*;
5536
5537 #[test]
5538 fn the_wire_reads_every_contact() {
5539 let t = parse_touches("0,0,1.500,2.000,1.0000,1;7,3,3.000,4.000,0.5000,0");
5540 assert_eq!(t.len(), 2);
5541 assert_eq!(t[0].id, 0);
5542 assert_eq!(t[0].phase, day_spec::TouchPhase::Began);
5543 assert_eq!(t[0].location, Point::new(1.5, 2.0));
5544 assert_eq!(t[0].kind, day_spec::PointerKind::Mouse);
5545 assert_eq!(t[1].id, 7);
5546 assert_eq!(t[1].phase, day_spec::TouchPhase::Ended);
5547 assert!((t[1].pressure - 0.5).abs() < 1e-9);
5548 assert_eq!(t[1].kind, day_spec::PointerKind::Touch);
5549 }
5550
5551 #[test]
5552 fn a_malformed_contact_is_skipped() {
5553 let t = parse_touches("x;1,1,0,0,1,2;");
5554 assert_eq!(t.len(), 1);
5555 assert_eq!(t[0].kind, day_spec::PointerKind::Stylus);
5556 assert_eq!(t[0].phase, day_spec::TouchPhase::Moved);
5557 }
5558}
5559
5560impl Platform for Xaml {
5561 const TARGET: &'static str = if cfg!(feature = "winui") {
5563 "windows-winui"
5564 } else {
5565 "windows-xaml"
5566 };
5567 const TOOLKIT: &'static str = if cfg!(feature = "winui") {
5568 "winui"
5569 } else {
5570 "xaml"
5571 };
5572
5573 fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, WinHandle, Size)>) {
5574 unsafe {
5575 let (min_w, min_h) = options
5576 .min_size
5577 .map_or((0, 0), |s| (s.width as c_int, s.height as c_int));
5578 ffi::day_xaml_set_forward_cb(forwarded_args);
5581 if ffi::day_xaml_claim_instance(cstr(&app_id()).as_ptr()) == 0 {
5582 std::process::exit(0);
5583 }
5584 ffi::day_xaml_set_chrome_inset_cb(chrome_inset);
5586 let chrome = window_chrome(&options);
5587 let win = ffi::day_xaml_window_new(
5588 cstr(&options.title).as_ptr(),
5589 options.size.width as c_int,
5590 options.size.height as c_int,
5591 min_w,
5592 min_h,
5593 &raw const chrome,
5594 );
5595 if win.is_null() {
5596 log::error!(
5597 "day-toolkit-winui: could not create the XAML window (see error above)"
5598 );
5599 return;
5600 }
5601 self.window = win;
5602 stage_bundled_fonts();
5605 stage_bundled_images();
5607 if let Ok(icon) = std::env::var("DAY_APP_ICON") {
5609 ffi::day_xaml_set_app_icon(win, cstr(&icon).as_ptr());
5610 }
5611 if options.max_size.is_some() {
5613 set_limits(win, options.min_size, options.max_size);
5614 }
5615 ffi::day_xaml_set_status_cb(status_action);
5616 set_jump_tasks(&[]);
5618 ffi::day_xaml_set_menu_cb(on_menu_action);
5619 ffi::day_xaml_label_link_cb(on_link);
5620 ffi::day_xaml_set_toolbar_cb(toolbar::on_toolbar_value);
5621 ffi::day_xaml_set_lifecycle_cb(on_lifecycle);
5622 ffi::day_xaml_set_touches_cb(on_touches);
5623 ffi::day_xaml_set_pointer_kind_cb(on_pointer_kind);
5624 ffi::day_xaml_watch_text_scale(text_scale_changed);
5625 ffi::day_xaml_set_present_cb(present_cb);
5626 ffi::day_xaml_set_window_state_cb(win_state);
5628 let root = ffi::day_xaml_window_root(win);
5629 self.primary_root = root;
5630 ready(self, WinHandle(root), options.size);
5631 ffi::day_xaml_window_on_resize(win, window_resized);
5632 ffi::day_xaml_set_primary_closed_cb(primary_closed);
5633 ffi::day_xaml_set_appearance_cb(appearance_changed);
5634 ffi::day_xaml_watch_reduce_motion(motion_changed);
5635 ffi::day_xaml_set_window_events_cb(win_resized, win_closed, win_focused);
5636 ffi::day_xaml_window_show(win);
5637 ffi::day_xaml_run(win);
5638 }
5639 }
5640
5641 fn post(f: Box<dyn FnOnce() + Send>) {
5642 let data = Box::into_raw(Box::new(f)).cast::<c_void>();
5643 unsafe { ffi::day_xaml_post(run_posted, data) };
5644 }
5645
5646 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
5647 const STEP: u32 = 0x7FFF_FFFF;
5651 if ms > STEP {
5652 Self::post_delayed(STEP, Box::new(move || Self::post_delayed(ms - STEP, f)));
5653 return;
5654 }
5655 let data = Box::into_raw(Box::new(f)).cast::<c_void>();
5656 unsafe { ffi::day_xaml_post_delayed(ms, run_posted, data) };
5657 }
5658}