1mod controls;
9
10use std::cell::RefCell;
11use std::collections::HashMap;
12use std::ffi::{CStr, CString};
13use std::os::raw::{c_char, c_double, c_int, c_void};
14use std::rc::Rc;
15
16use day_toolkit_qt_sys as ffi;
17use linkme::distributed_slice;
18
19use day_spec::props::*;
20use day_spec::{
21 A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
22 InputTraits, NodeId, PieceKind, Platform, Proposal, Rect, Registry, Renderer, Role, Size,
23 Support, Toolkit, Transform, WindowOptions, ffi_guard, kinds, props_of, sidetable::SideTable,
24};
25
26#[derive(Clone, Copy, PartialEq, Eq, Hash)]
27pub struct QtHandle(pub *mut c_void);
28
29#[derive(Clone, Debug, PartialEq)]
34struct QtAnim {
35 delay_ms: c_int,
36 duration_ms: c_int,
37 cycles: c_int,
39 autoreverse: bool,
40 keys: Vec<f64>,
43}
44
45impl QtAnim {
46 fn new(spec: &AnimSpec) -> Self {
47 let ms = |v: u32| c_int::try_from(v).unwrap_or(c_int::MAX);
48 let keys = if spec.curve == Curve::Linear {
49 vec![0.0, 1.0]
50 } else {
51 spec.keyframes().iter().map(|k| k.progress).collect()
52 };
53 QtAnim {
54 delay_ms: ms(spec.delay_ms),
55 duration_ms: ms(spec.duration_ms),
56 cycles: spec.cycles().map_or(-1, ms),
57 autoreverse: spec.autoreverse,
58 keys,
59 }
60 }
61
62 fn raw(&self) -> ffi::DayQtAnim {
64 ffi::DayQtAnim {
65 delay_ms: self.delay_ms,
66 duration_ms: self.duration_ms,
67 cycles: self.cycles,
68 autoreverse: c_int::from(self.autoreverse),
69 keys: self.keys.as_ptr(),
70 n_keys: c_int::try_from(self.keys.len()).unwrap_or(0),
71 }
72 }
73}
74
75fn with_qt_anim<R>(anim: Option<&AnimSpec>, f: impl FnOnce(*const ffi::DayQtAnim) -> R) -> R {
78 match anim {
79 None => f(std::ptr::null()),
80 Some(spec) => {
81 let run = QtAnim::new(spec);
82 let raw = run.raw();
83 f(&raw const raw)
84 }
85 }
86}
87
88fn qt_input_purpose(purpose: InputPurpose) -> c_int {
92 match purpose {
93 InputPurpose::Text => 0,
94 InputPurpose::Name => 1,
95 InputPurpose::Email => 2,
96 InputPurpose::Url => 3,
97 InputPurpose::Phone => 4,
98 InputPurpose::Number => 5,
99 InputPurpose::Decimal => 6,
100 InputPurpose::Username => 7,
101 InputPurpose::Password => 8,
102 InputPurpose::NewPassword => 9,
103 InputPurpose::OneTimeCode => 10,
104 }
105}
106
107#[cfg(target_os = "linux")]
109mod linux;
110mod picker;
111mod textarea;
112mod toolbar;
113mod transfer;
114mod tree;
115
116pub type Handle = QtHandle;
117
118pub mod ext;
119pub use ext::*;
120pub use toolbar::icon_args;
123
124type Sink = Rc<dyn Fn(NodeId, Event)>;
126
127day_core::tls_group! {
128 static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
129 static RANGES: SideTable<(f64, f64)> = SideTable::new();
134 static RANGES_BY_PTR: SideTable<(f64, f64)> = SideTable::new();
135 static GESTURES: RefCell<std::collections::HashSet<(usize, day_spec::GestureKind)>> =
137 RefCell::new(std::collections::HashSet::new());
138
139 static BUTTON_MENUS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
142 static CTX_MENU_FNS: RefCell<HashMap<u64, day_spec::ContextMenuFn>> =
144 RefCell::new(HashMap::new());
145
146 static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
147 static LIST_BY_NODE: RefCell<HashMap<u64, usize>> = RefCell::new(HashMap::new());
150
151 static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
152 static NAV_PAGE_IDS: RefCell<HashMap<usize, NodeId>> = RefCell::new(HashMap::new());
153 static PAGE_PANE: RefCell<HashMap<usize, day_spec::props::Pane>> = RefCell::new(HashMap::new());
156
157 static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
158 static INSPECTOR_PANE_IDS: RefCell<HashMap<usize, (NodeId, bool)>> =
161 RefCell::new(HashMap::new());
162 static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
164 static SPLIT_PANE_IDS: RefCell<HashMap<usize, (NodeId, bool)>> = RefCell::new(HashMap::new());
166
167 static LABEL_PT: SideTable<f64> = SideTable::new();
174
175 static NAV_SUITES: RefCell<HashMap<usize, NavSuite>> = RefCell::new(HashMap::new());
176 static NAV_SUITE_PAGES: RefCell<std::collections::HashSet<usize>> =
180 RefCell::new(std::collections::HashSet::new());
181 static NAV_SUITE_ROWS: RefCell<HashMap<usize, NavRow>> = RefCell::new(HashMap::new());
184
185 static LAST_WINDOW_SIZE: std::cell::Cell<Size> =
187 const { std::cell::Cell::new(Size::new(0.0, 0.0)) };
188 static COVERS: RefCell<Vec<(*mut c_void, NodeId)>> = const { RefCell::new(Vec::new()) };
190 static COVER_IDS: RefCell<HashMap<usize, NodeId>> = RefCell::new(HashMap::new());
192 static COVER_HALF: RefCell<std::collections::HashSet<usize>> =
195 RefCell::new(std::collections::HashSet::new());
196
197 static NAV_MENU_ROWS: RefCell<HashMap<usize, (usize, usize)>> = RefCell::new(HashMap::new());
200
201 static BITMAP_INFO: RefCell<HashMap<u64, day_spec::BitmapInfo>> = RefCell::new(HashMap::new());
204
205}
206
207pub fn emit(id: NodeId, ev: Event) {
208 let sink = SINK.with(|s| s.borrow().clone());
209 if let Some(sink) = sink {
210 sink(id, ev);
211 }
212}
213
214fn emit_deferred(id: NodeId, ev: Event) {
220 let boxed: Box<dyn FnOnce() + Send> = Box::new(move || emit(id, ev));
221 let data = Box::into_raw(Box::new(boxed)).cast::<c_void>();
222 unsafe { ffi::day_qt_post(run_posted, data) };
223}
224
225fn argb(c: day_spec::Color) -> u32 {
227 let f = |v: f64| (v.clamp(0.0, 1.0) * 255.0) as u32;
228 (f(c.a) << 24) | (f(c.r) << 16) | (f(c.g) << 8) | f(c.b)
229}
230
231fn apply_button_content(
232 h: *mut c_void,
233 title: &str,
234 icon: Option<&day_spec::Icon>,
235 icon_only: bool,
236) {
237 let (name, fallback) = toolbar::icon_args(icon);
238 unsafe {
239 ffi::day_qt_button_set_content(
240 h,
241 cstr(title).as_ptr(),
242 cstr(&name).as_ptr(),
243 fallback,
244 c_int::from(icon_only),
245 );
246 };
247}
248
249fn apply_button_style(w: *mut c_void, style: day_spec::props::ButtonStyleSpec) {
253 use day_spec::props::ButtonStyleSpec as S;
254 let (kind, fill) = match style {
255 S::Automatic | S::Compact | S::Plain => (0, day_spec::Color::CLEAR),
257 S::Bordered => (1, day_spec::Color::CLEAR),
258 S::Prominent => (2, day_spec::Color::CLEAR),
259 S::Tinted(c) => (3, c.resolved()),
260 };
261 unsafe { ffi::day_qt_button_set_style(w, kind, argb(fill), argb(S::on_tint(fill))) };
264}
265
266fn encode_bitmap(
272 id: day_spec::BitmapId,
273 spec: &day_spec::EncodeSpec,
274) -> Result<Vec<u8>, day_spec::ImageError> {
275 use day_spec::ImageFormat as F;
276 let format = match spec.format {
277 F::Png => "png",
278 F::Jpeg => "jpeg",
279 F::Tiff => "tiff",
280 F::Bmp => "bmp",
281 _ => return Err(day_spec::ImageError::Encode),
283 };
284 if !BITMAP_INFO.with(|m| m.borrow().contains_key(&id.0)) {
285 return Err(day_spec::ImageError::Gone);
286 }
287 let quality = spec
289 .quality
290 .map_or(-1, |q| (q.clamp(0.0, 1.0) * 100.0).round() as c_int);
291 let (fit_w, fit_h) = spec.fit.map_or((0.0, 0.0), |f| (f.width, f.height));
292 let mut len: c_int = 0;
293 let bytes = unsafe {
296 let p = ffi::day_qt_image_encode(
297 id.0,
298 cstr(format).as_ptr(),
299 quality,
300 fit_w,
301 fit_h,
302 &raw mut len,
303 );
304 if p.is_null() || len <= 0 {
305 return Err(day_spec::ImageError::Encode);
306 }
307 let out = std::slice::from_raw_parts(p, len as usize).to_vec();
308 ffi::day_qt_bytes_free(p);
309 out
310 };
311 Ok(bytes)
312}
313
314fn render_pdf_document(
316 pages: &[day_spec::PdfPage],
317 info: &day_spec::PdfInfo,
318) -> Result<Vec<u8>, day_spec::ExportError> {
319 let encoded: Vec<(Vec<f64>, CString)> = pages
320 .iter()
321 .map(|page| {
322 let (nums, texts) = day_spec::encode_ops(&page.ops);
323 (nums, cstr(&texts.join("\u{1f}")))
324 })
325 .collect();
326 let views: Vec<ffi::DayQtPdfPage> = pages
327 .iter()
328 .zip(&encoded)
329 .map(|(page, (nums, texts))| ffi::DayQtPdfPage {
330 w: page.size.width,
331 h: page.size.height,
332 nums: nums.as_ptr(),
333 n: nums.len() as c_int,
334 texts: texts.as_ptr(),
335 })
336 .collect();
337 let title = info.title.as_deref().map(cstr);
338 let author = info.author.as_deref().map(cstr);
339 let mut len: c_int = 0;
340 let mut err: *mut c_char = std::ptr::null_mut();
341 unsafe {
345 let p = ffi::day_qt_canvas_render_pdf(
346 views.as_ptr(),
347 views.len() as c_int,
348 title.as_ref().map_or(std::ptr::null(), |t| t.as_ptr()),
349 author.as_ref().map_or(std::ptr::null(), |a| a.as_ptr()),
350 &raw mut len,
351 &raw mut err,
352 );
353 if p.is_null() || len <= 0 {
354 let why = if err.is_null() {
355 "QPdfWriter failed".to_string()
356 } else {
357 let text = CStr::from_ptr(err).to_string_lossy().into_owned();
358 ffi::day_qt_string_free(err);
359 text
360 };
361 ffi::day_qt_bytes_free(p);
362 return Err(day_spec::ExportError::Failed(why));
363 }
364 let out = std::slice::from_raw_parts(p, len as usize).to_vec();
365 ffi::day_qt_bytes_free(p);
366 Ok(out)
367 }
368}
369
370pub(crate) fn cstr(s: &str) -> CString {
371 CString::new(s).unwrap_or_else(|_| CString::new(s.replace('\0', "")).unwrap_or_default())
374}
375
376const LIST_OVERSCAN: usize = 8;
395
396const LIST_HEIGHT_CACHE: usize = 4096;
401
402#[derive(Default)]
405struct CellPool {
406 bound: std::collections::BTreeMap<usize, usize>,
408 row_of: HashMap<usize, usize>,
410 free: Vec<usize>,
412 free_headers: Vec<usize>,
418 headers: std::collections::HashSet<usize>,
420}
421
422impl CellPool {
423 fn retarget(&mut self, band: std::ops::Range<usize>) -> (Vec<usize>, Vec<usize>) {
426 let leaving: Vec<usize> = self
427 .bound
428 .range(..band.start)
429 .chain(self.bound.range(band.end..))
430 .map(|(row, _)| *row)
431 .collect();
432 let mut parked = Vec::with_capacity(leaving.len());
433 for row in leaving {
434 if let Some(cell) = self.bound.remove(&row) {
435 self.row_of.remove(&cell);
436 if self.headers.contains(&cell) {
437 self.free_headers.push(cell);
438 } else {
439 self.free.push(cell);
440 }
441 parked.push(cell);
442 }
443 }
444 let need: Vec<usize> = band.filter(|row| !self.bound.contains_key(row)).collect();
445 (parked, need)
446 }
447
448 fn bind(&mut self, row: usize, cell: usize) {
450 self.bound.insert(row, cell);
451 self.row_of.insert(cell, row);
452 }
453
454 fn take_free(&mut self, header: bool) -> Option<usize> {
456 if header {
457 self.free_headers.pop()
458 } else {
459 self.free.pop()
460 }
461 }
462
463 fn set_kind(&mut self, cell: usize, header: bool) {
465 if header {
466 self.headers.insert(cell);
467 } else {
468 self.headers.remove(&cell);
469 }
470 }
471
472 fn row_of(&self, cell: usize) -> Option<usize> {
473 self.row_of.get(&cell).copied()
474 }
475
476 #[cfg(test)]
478 fn len(&self) -> usize {
479 self.bound.len() + self.free.len() + self.free_headers.len()
480 }
481}
482
483#[derive(Debug, PartialEq)]
487enum RowWork {
488 Reload,
490 Splice(Vec<RowDelta>),
492}
493
494impl RowWork {
495 fn merge(waiting: Option<Self>, next: Self) -> Self {
498 match (waiting, next) {
499 (Some(Self::Splice(mut a)), Self::Splice(b)) => {
500 a.extend(b);
501 Self::Splice(a)
502 }
503 (None, next) => next,
504 (Some(_), _) => Self::Reload,
505 }
506 }
507
508 fn triples(deltas: &[RowDelta]) -> Vec<c_int> {
510 let idx = |i: usize| c_int::try_from(i).unwrap_or(c_int::MAX);
511 deltas
512 .iter()
513 .flat_map(|d| match d {
514 RowDelta::Insert(i) => [0, idx(*i), 0],
515 RowDelta::Remove(i) => [1, idx(*i), 0],
516 RowDelta::Move(from, to) => [2, idx(*from), idx(*to)],
517 })
518 .collect()
519 }
520}
521
522fn supplement_rows(n: usize, is_supplement: &dyn Fn(usize) -> bool) -> Vec<usize> {
527 let lead = (0..n).take_while(|i| is_supplement(*i)).count();
528 let trail = (lead..n).rev().take_while(|i| is_supplement(*i)).count();
529 (0..lead).chain(n - trail..n).collect()
530}
531
532fn row_align_code(align: day_spec::RowAlign) -> c_int {
534 match align {
535 day_spec::RowAlign::Nearest => 0,
536 day_spec::RowAlign::Start => 1,
537 day_spec::RowAlign::Center => 2,
538 day_spec::RowAlign::End => 3,
539 }
540}
541
542struct ListEntry {
543 host: *mut c_void,
544 row_height: f64,
547 automatic: bool,
549 source: Rc<RefCell<Option<day_spec::ListSource>>>,
550 pool: CellPool,
551 heights: HashMap<u64, f64>,
554 height_sum: f64,
556 estimate: c_int,
558 rebind_all: bool,
560 frame_height: c_int,
563 fill_pending: bool,
566 last_width: c_int,
569 cell_width: c_int,
572 node: u64,
573 multi: bool,
576 pin: Option<usize>,
579 pin_row: Option<usize>,
581 headers_for: Option<usize>,
583 supplements_for: Option<usize>,
586 supplement_heights: HashMap<u64, f64>,
590 pending: Option<RowWork>,
592}
593
594extern "C" fn on_list_activate(node: u64, row: c_int) {
595 ffi_guard::contain((), || {
596 if row >= 0 {
597 emit_deferred(NodeId(node), Event::ListActivated(row as usize));
598 }
599 });
600}
601
602extern "C" fn on_list_selection(node: u64, rows: *const c_int, count: c_int) {
607 ffi_guard::contain((), || {
610 let rows: Vec<i64> = if rows.is_null() || count <= 0 {
611 Vec::new()
612 } else {
613 unsafe { std::slice::from_raw_parts(rows, count as usize) }
615 .iter()
616 .map(|r| i64::from(*r))
617 .collect()
618 };
619 let multi = LIST_BY_NODE
620 .with(|m| m.borrow().get(&node).copied())
621 .and_then(|k| LIST_STATE.with(|m| m.borrow().get(&k).map(|st| st.multi)));
622 let Some(multi) = multi else { return };
623 let ev = match (multi, rows.as_slice()) {
624 (false, [row]) => Event::SelectionChanged(*row),
625 _ => Event::SelectionSet(rows),
626 };
627 emit(NodeId(node), ev);
628 });
629}
630
631extern "C" fn on_list_can_move(node: u64, from: c_int, to: c_int) -> c_int {
635 ffi_guard::contain(-1, || {
637 let Some(host_key) = LIST_BY_NODE.with(|m| m.borrow().get(&node).copied()) else {
638 return -1;
639 };
640 let r = LIST_STATE.with(|m| {
641 m.borrow().get(&host_key).and_then(|st| {
642 let s = st.source.borrow().clone()?;
643 Some(((s.len)(), s.reorder))
644 })
645 });
646 let Some((len, Some(r))) = r else { return -1 };
647 let (from, to) = (from.max(0) as usize, to.max(0) as usize);
648 if from >= len {
649 return -1;
650 }
651 let to = to.min(len - 1);
652 ((r.can_move)(from, to) as c_int).min(len as c_int - 1)
653 })
654}
655
656extern "C" fn on_list_move(node: u64, from: c_int, to: c_int) {
659 ffi_guard::contain((), || {
660 let Some(host_key) = LIST_BY_NODE.with(|m| m.borrow().get(&node).copied()) else {
661 return;
662 };
663 let r = LIST_STATE.with(|m| {
664 m.borrow()
665 .get(&host_key)
666 .and_then(|st| st.source.borrow().clone()?.reorder)
667 });
668 let Some(r) = r else { return };
669 let (from, to) = (from.max(0) as usize, to.max(0) as usize);
670 if from != to {
671 (r.move_row)(from, to);
672 schedule_list_populate(host_key);
673 }
674 });
675}
676
677extern "C" fn on_scroll_offset(node: u64, x: c_double, y: c_double) {
681 ffi_guard::contain((), || {
682 emit(
683 NodeId(node),
684 Event::ScrollChanged(day_spec::Point::new(x, y)),
685 );
686 });
687}
688
689fn schedule_list_populate(host_key: usize) {
692 Qt::post(Box::new(move || list_populate(host_key)));
693}
694
695extern "C" fn on_list_window(node: u64) {
699 ffi_guard::contain((), || {
700 Qt::post(Box::new(move || {
703 if let Some(host_key) = LIST_BY_NODE.with(|m| m.borrow().get(&node).copied()) {
704 schedule_list_fill(host_key);
705 }
706 }));
707 });
708}
709
710fn schedule_list_fill(host_key: usize) {
713 let post = LIST_STATE.with(|m| {
714 let mut m = m.borrow_mut();
715 let Some(st) = m.get_mut(&host_key) else {
716 return false;
717 };
718 let first = !st.fill_pending;
719 st.fill_pending = true;
720 first
721 });
722 if !post {
723 return;
724 }
725 Qt::post(Box::new(move || {
726 LIST_STATE.with(|m| {
727 if let Some(st) = m.borrow_mut().get_mut(&host_key) {
728 st.fill_pending = false;
729 }
730 });
731 list_sync(host_key);
732 }));
733}
734
735fn schedule_list_scroll_end(host_key: usize) {
739 Qt::post(Box::new(move || {
740 if let Some(host) = LIST_STATE.with(|m| m.borrow().get(&host_key).map(|st| st.host)) {
741 unsafe { ffi::day_qt_list_scroll_to_end(host) };
742 }
743 }));
744}
745
746fn schedule_list_scroll_row(host_key: usize, row: usize) {
749 Qt::post(Box::new(move || {
750 if let Some(host) = LIST_STATE.with(|m| m.borrow().get(&host_key).map(|st| st.host)) {
751 unsafe { ffi::day_qt_list_scroll_to_row(host, row as c_int) };
752 }
753 }));
754}
755
756fn queue_rows(host_key: usize, work: RowWork) {
761 let post = LIST_STATE.with(|m| {
762 let mut m = m.borrow_mut();
763 let Some(st) = m.get_mut(&host_key) else {
764 return false;
765 };
766 let first = st.pending.is_none();
767 st.pending = Some(RowWork::merge(st.pending.take(), work));
768 first
769 });
770 if post {
771 Qt::post(Box::new(move || flush_rows(host_key)));
772 }
773}
774
775fn flush_rows(host_key: usize) {
782 let work = LIST_STATE.with(|m| {
783 let mut m = m.borrow_mut();
784 let st = m.get_mut(&host_key)?;
785 let work = st.pending.take()?;
786 st.rebind_all = true;
787 let len = st.source.borrow().as_ref().map(|s| (s.len)());
788 Some((st.host, work, len))
789 });
790 let Some((host, work, len)) = work else {
791 return;
792 };
793 if let (RowWork::Splice(deltas), Some(len)) = (work, len) {
794 let triples = RowWork::triples(&deltas);
795 let count = c_int::try_from(deltas.len()).unwrap_or(c_int::MAX);
796 let len = c_int::try_from(len).unwrap_or(c_int::MAX);
797 let applied = unsafe { ffi::day_qt_list_splice_all(host, triples.as_ptr(), count, len) };
798 if applied == 0 {
799 log::debug!("qt list: a splice did not fit the view's rows; reloaded instead");
800 }
801 }
802 list_sync(host_key);
803}
804
805extern "C" fn on_list_viewport_resized(host: *mut c_void) {
810 ffi_guard::contain((), || {
811 let host_key = host as usize;
814 Qt::post(Box::new(move || {
815 let state =
816 LIST_STATE.with(|m| m.borrow().get(&host_key).map(|st| (st.host, st.cell_width)));
817 let Some((host, cell_width)) = state else {
818 return;
819 };
820 let vw = unsafe { ffi::day_qt_list_viewport_width(host) };
821 if cell_width > 0 && vw > 0.0 && (vw as c_int) != cell_width {
822 schedule_list_populate(host_key);
823 }
824 }));
825 });
826}
827
828extern "C" fn on_list_reader_scroll(node: u64) {
833 ffi_guard::contain((), || {
834 Qt::post(Box::new(move || {
835 let report = LIST_BY_NODE
836 .with(|m| m.borrow().get(&node).copied())
837 .and_then(|host_key| {
838 LIST_STATE.with(|m| {
839 m.borrow()
840 .get(&host_key)?
841 .source
842 .borrow()
843 .as_ref()?
844 .reader_scroll
845 .clone()
846 })
847 });
848 if let Some(report) = report {
849 report();
850 }
851 }));
852 });
853}
854
855fn list_populate(host_key: usize) {
860 LIST_STATE.with(|m| {
861 if let Some(st) = m.borrow_mut().get_mut(&host_key) {
862 st.rebind_all = true;
863 }
864 });
865 list_sync(host_key);
866}
867
868struct SyncPass {
870 host: *mut c_void,
871 rowh: f64,
872 source: day_spec::ListSource,
873 work: Vec<(usize, *mut c_void)>,
875 parked: Vec<usize>,
877 width: c_int,
878 host_width: c_int,
879 first_visible: usize,
880 automatic: bool,
881 pin_bind: Option<(usize, *mut c_void)>,
883}
884
885fn list_sync(host_key: usize) {
888 let Some(pass) = LIST_STATE.with(|m| {
891 let mut m = m.borrow_mut();
892 let st = m.get_mut(&host_key)?;
893 let source = st.source.borrow().clone()?;
894 let n = (source.len)();
895 let rowh = st.row_height.max(1.0);
896 unsafe { ffi::day_qt_list_set_count(st.host, n as c_int) };
899 let rebind_all = std::mem::take(&mut st.rebind_all);
900 let is_header = source.is_header.clone();
903 if let Some(is_header) = &is_header
904 && (rebind_all || st.headers_for != Some(n))
905 {
906 let rows: Vec<c_int> = (0..n)
907 .filter(|i| is_header(*i))
908 .map(|i| i as c_int)
909 .collect();
910 unsafe { ffi::day_qt_list_set_headers(st.host, rows.as_ptr(), rows.len() as c_int) };
911 st.headers_for = Some(n);
912 }
913 let is_supplement = source.is_supplement.clone();
918 let mut supplements = Vec::new();
919 if let Some(f) = &is_supplement
920 && (rebind_all || st.supplements_for != Some(n))
921 {
922 supplements = supplement_rows(n, f.as_ref());
923 let raw: Vec<c_int> = supplements.iter().map(|i| *i as c_int).collect();
924 unsafe { ffi::day_qt_list_set_supplements(st.host, raw.as_ptr(), raw.len() as c_int) };
925 st.supplements_for = Some(n);
926 }
927 let (mut w, mut h) = (0.0_f64, 0.0_f64);
928 unsafe { ffi::day_qt_widget_size(st.host, &raw mut w, &raw mut h) };
929 let vw = unsafe { ffi::day_qt_list_viewport_width(st.host) };
933 let width = if vw > 0.0 { vw } else { w }.max(1.0) as c_int;
934 let (mut first, mut last) = (0 as c_int, -1 as c_int);
937 unsafe { ffi::day_qt_list_visible_rows(st.host, &raw mut first, &raw mut last) };
938 let (first, last) = if last >= first {
939 (first.max(0) as usize, last.max(0) as usize + 1)
940 } else {
941 let vh = if st.frame_height > 0 {
942 f64::from(st.frame_height)
943 } else {
944 600.0
947 };
948 (0, (vh / rowh).ceil() as usize)
949 };
950 let first_visible = first.min(n.saturating_sub(1));
951 let band = first.saturating_sub(LIST_OVERSCAN)..(last + LIST_OVERSCAN).min(n);
952 let (parked, need) = st.pool.retarget(band);
953 for cell in &parked {
954 unsafe { ffi::day_qt_list_park_cell(st.host, *cell as *mut c_void) };
955 }
956 if rebind_all && (st.automatic || is_header.is_some() || is_supplement.is_some()) {
957 unsafe { ffi::day_qt_list_clear_heights(st.host) };
962 }
963 for row in supplements {
964 if let Some(h) = st.supplement_heights.get(&(source.token_at)(row)) {
965 unsafe {
966 ffi::day_qt_list_set_row_height(st.host, row as c_int, h.ceil() as c_int);
967 };
968 }
969 }
970 let mut work: Vec<(usize, *mut c_void)> = Vec::with_capacity(need.len());
971 for row in need {
972 let header = is_header.as_ref().is_some_and(|f| f(row));
973 let cell = match st.pool.take_free(header) {
974 Some(spare) => spare as *mut c_void,
975 None => unsafe { ffi::day_qt_container_new() },
976 };
977 st.pool.bind(row, cell as usize);
978 unsafe { ffi::day_qt_list_place_cell(st.host, row as c_int, cell) };
981 work.push((row, cell));
982 }
983 if rebind_all {
984 work = st
985 .pool
986 .bound
987 .iter()
988 .map(|(row, cell)| (*row, *cell as *mut c_void))
989 .collect();
990 }
991 work.sort_unstable_by_key(|(row, _)| *row);
992 if let Some(f) = &is_header {
993 for (row, cell) in &work {
994 st.pool.set_kind(*cell as usize, f(*row));
995 }
996 }
997 let mut pin_bind = None;
1000 if is_header.is_some() {
1001 let host = st.host;
1002 let pin = *st
1003 .pin
1004 .get_or_insert_with(|| unsafe { ffi::day_qt_list_pin_cell(host) } as usize);
1005 let target = unsafe { ffi::day_qt_list_header_for(host, first_visible as c_int) };
1006 let target = usize::try_from(target).ok();
1007 if rebind_all || target != st.pin_row {
1008 st.pin_row = target;
1009 match target {
1010 Some(row) => pin_bind = Some((row, pin as *mut c_void)),
1011 None => unsafe { ffi::day_qt_list_pin_bound(host, -1, 0) },
1012 }
1013 }
1014 }
1015 if rebind_all && st.automatic {
1016 for (row, _) in &work {
1017 if let Some(h) = st.heights.get(&(source.token_at)(*row)) {
1018 unsafe {
1019 ffi::day_qt_list_set_row_height(st.host, *row as c_int, h.ceil() as c_int);
1020 };
1021 }
1022 }
1023 }
1024 st.last_width = w.max(1.0) as c_int;
1025 st.cell_width = width;
1026 Some(SyncPass {
1027 host: st.host,
1028 rowh,
1029 source,
1030 work,
1031 parked,
1032 width,
1033 host_width: st.last_width,
1034 first_visible,
1035 automatic: st.automatic,
1036 pin_bind,
1037 })
1038 }) else {
1039 return;
1040 };
1041 let SyncPass {
1042 host,
1043 rowh,
1044 source,
1045 work,
1046 parked,
1047 width,
1048 host_width,
1049 first_visible,
1050 automatic,
1051 pin_bind,
1052 } = pass;
1053 for cell in parked {
1060 Qt::post(Box::new(move || {
1061 let recycle = LIST_STATE.with(|m| {
1062 let m = m.borrow();
1063 let st = m.get(&host_key)?;
1064 if st.pool.row_of(cell).is_some() {
1065 return None; }
1067 st.source.borrow().as_ref().map(|s| s.recycle.clone())
1068 });
1069 if let Some(recycle) = recycle {
1070 recycle(cell as *mut c_void);
1071 }
1072 }));
1073 }
1074 if source.viewport.is_some() {
1075 Qt::post(Box::new(move || list_report_viewport(host_key)));
1079 } else if source.first_visible.is_some() {
1080 Qt::post(Box::new(move || {
1083 let source = LIST_STATE.with(|m| {
1084 m.borrow()
1085 .get(&host_key)
1086 .and_then(|st| st.source.borrow().clone())
1087 });
1088 if let Some(source) = source
1089 && let Some(report) = &source.first_visible
1090 {
1091 report(first_visible.min((source.len)().saturating_sub(1)));
1092 }
1093 }));
1094 }
1095 let mut measured = false;
1096 for (i, cell) in work {
1097 let (mut x, mut y, mut cw, mut ch) = (0 as c_int, 0 as c_int, 0 as c_int, 0 as c_int);
1101 unsafe {
1102 ffi::day_qt_list_cell_frame(
1103 host,
1104 i as c_int,
1105 &raw mut x,
1106 &raw mut y,
1107 &raw mut cw,
1108 &raw mut ch,
1109 );
1110 };
1111 if cw <= 0 || ch <= 0 {
1112 (x, y, cw, ch) = (0, (i as f64 * rowh) as c_int, width, rowh as c_int);
1113 }
1114 unsafe { ffi::day_qt_set_geometry(cell, x, y, cw, ch) };
1115 (source.bind_row)(i, cell);
1117 if cw != host_width {
1123 (source.layout_cell)(cell, f64::from(cw));
1124 }
1125 let header = source.is_header.as_ref().is_some_and(|f| f(i));
1132 let supplement = source.is_supplement.as_ref().is_some_and(|f| f(i));
1133 if automatic || header || supplement {
1134 let laid = (source.cell_height)(cell);
1135 if laid > 0.0 {
1136 let laid_px = laid.ceil() as c_int;
1137 unsafe {
1138 ffi::day_qt_set_geometry(cell, x, y, cw, laid_px);
1139 ffi::day_qt_list_set_row_height(host, i as c_int, laid_px);
1140 }
1141 if supplement {
1144 list_remember_supplement(host_key, (source.token_at)(i), laid);
1145 } else if !header {
1146 list_remember_height(host_key, (source.token_at)(i), laid);
1147 measured = true;
1148 }
1149 }
1150 }
1151 }
1152 if measured {
1153 list_update_estimate(host_key);
1154 }
1155 if let Some((row, pin)) = pin_bind {
1158 unsafe { ffi::day_qt_set_geometry(pin, 0, 0, width, rowh as c_int) };
1159 (source.bind_pinned)(row, pin);
1160 if width != host_width {
1161 (source.layout_cell)(pin, f64::from(width));
1162 }
1163 let laid = (source.cell_height)(pin);
1164 let height = if laid > 0.0 { laid.ceil() } else { rowh } as c_int;
1165 unsafe { ffi::day_qt_list_pin_bound(host, row as c_int, height) };
1166 }
1167}
1168
1169fn list_report_viewport(host_key: usize) {
1176 let found = LIST_STATE.with(|m| {
1177 let m = m.borrow();
1178 let st = m.get(&host_key)?;
1179 if st.pending.is_some() {
1180 return None;
1181 }
1182 let report = st.source.borrow().as_ref()?.viewport.clone()?;
1183 Some((st.host, report))
1184 });
1185 let Some((host, report)) = found else {
1186 return;
1187 };
1188 let (mut first, mut last, mut end) = (0 as c_int, 0 as c_int, 0.0_f64);
1189 if unsafe { ffi::day_qt_list_viewport(host, &raw mut first, &raw mut last, &raw mut end) } == 0
1190 {
1191 return;
1192 }
1193 report(day_spec::ListViewport {
1194 first: first.max(0) as usize,
1195 last: last.max(first).max(0) as usize,
1196 end_distance: end.max(0.0),
1197 });
1198}
1199
1200fn list_remember_supplement(host_key: usize, token: u64, height: f64) {
1202 LIST_STATE.with(|m| {
1203 if let Some(st) = m.borrow_mut().get_mut(&host_key) {
1204 st.supplement_heights.insert(token, height);
1205 }
1206 });
1207}
1208
1209fn list_remember_height(host_key: usize, token: u64, height: f64) {
1212 LIST_STATE.with(|m| {
1213 let mut m = m.borrow_mut();
1214 let Some(st) = m.get_mut(&host_key) else {
1215 return;
1216 };
1217 if st.heights.len() >= LIST_HEIGHT_CACHE && !st.heights.contains_key(&token) {
1218 st.heights.clear();
1219 st.height_sum = 0.0;
1220 }
1221 if let Some(old) = st.heights.insert(token, height) {
1222 st.height_sum -= old;
1223 }
1224 st.height_sum += height;
1225 });
1226}
1227
1228fn list_update_estimate(host_key: usize) {
1231 let update = LIST_STATE.with(|m| {
1232 let mut m = m.borrow_mut();
1233 let st = m.get_mut(&host_key)?;
1234 if st.heights.is_empty() {
1235 return None;
1236 }
1237 let avg = (st.height_sum / st.heights.len() as f64).round() as c_int;
1238 if avg <= 0 || avg == st.estimate {
1239 return None;
1240 }
1241 st.estimate = avg;
1242 Some((st.host, avg))
1243 });
1244 if let Some((host, avg)) = update {
1245 unsafe { ffi::day_qt_list_set_estimate(host, avg) };
1246 }
1247}
1248
1249fn schedule_list_row_height(host_key: usize, cell: usize, height: f64) {
1253 Qt::post(Box::new(move || {
1254 let found = LIST_STATE.with(|m| {
1255 let m = m.borrow();
1256 let st = m.get(&host_key)?;
1257 if st.pin == Some(cell) {
1259 let row = st.pin_row?;
1260 unsafe {
1261 ffi::day_qt_list_pin_bound(st.host, row as c_int, height.ceil() as c_int);
1262 };
1263 return None;
1264 }
1265 let row = st.pool.row_of(cell)?;
1266 let kind = st.source.borrow().as_ref().map(|s| {
1269 let token = (s.token_at)(row);
1270 if s.is_supplement.as_ref().is_some_and(|f| f(row)) {
1271 (Some(token), true)
1272 } else if s.is_header.as_ref().is_some_and(|f| f(row)) {
1273 (None, false)
1274 } else {
1275 (Some(token), false)
1276 }
1277 });
1278 Some((st.host, row, kind))
1279 });
1280 let Some((host, row, kind)) = found else {
1281 return;
1282 };
1283 unsafe { ffi::day_qt_list_set_row_height(host, row as c_int, height.ceil() as c_int) };
1284 match kind {
1285 Some((Some(token), true)) => list_remember_supplement(host_key, token, height),
1286 Some((Some(token), false)) => {
1287 list_remember_height(host_key, token, height);
1288 list_update_estimate(host_key);
1289 }
1290 _ => {}
1291 }
1292 }));
1293}
1294
1295extern "C" fn on_context_menu_summon(
1299 node: u64,
1300 x: std::os::raw::c_double,
1301 y: std::os::raw::c_double,
1302) -> *mut c_void {
1303 ffi_guard::contain(std::ptr::null_mut(), || {
1304 let Some(f) = CTX_MENU_FNS.with(|m| m.borrow().get(&node).cloned()) else {
1305 return std::ptr::null_mut();
1306 };
1307 let items = f(day_spec::Point::new(x, y));
1308 if items.is_empty() {
1309 return std::ptr::null_mut();
1310 }
1311 let menu = unsafe { ffi::day_qt_menu_new() };
1312 build_qt_menu(menu, &items);
1313 menu
1314 })
1315}
1316
1317extern "C" fn on_button_menu(
1320 key: u64,
1321 _x: std::os::raw::c_double,
1322 _y: std::os::raw::c_double,
1323) -> *mut c_void {
1324 ffi_guard::contain(std::ptr::null_mut(), || {
1325 let Some(f) = BUTTON_MENUS.with(|t| t.get(key as usize)) else {
1326 return std::ptr::null_mut();
1327 };
1328 let Some(items) = day_spec::resolve_button_menu(&f, || {
1330 BUTTON_MENUS.with(|t| t.get(key as usize)).is_some()
1331 }) else {
1332 return std::ptr::null_mut();
1333 };
1334 let menu = unsafe { ffi::day_qt_menu_new() };
1335 build_qt_menu(menu, &items);
1336 menu
1337 })
1338}
1339
1340extern "C" fn on_press(id: u64) {
1341 ffi_guard::contain((), || emit(NodeId(id), Event::Pressed));
1342}
1343extern "C" fn on_toggle(id: u64, on: c_int) {
1344 ffi_guard::contain((), || emit(NodeId(id), Event::ToggleChanged(on != 0)));
1345}
1346extern "C" fn on_text(id: u64, s: *const c_char) {
1347 ffi_guard::contain((), || {
1348 let text = unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned();
1349 emit(NodeId(id), Event::TextChanged(text));
1350 });
1351}
1352extern "C" fn on_text_selected(id: u64, start: c_int, end: c_int) {
1355 ffi_guard::contain((), || {
1356 let start = usize::try_from(start).unwrap_or(0);
1357 let end = usize::try_from(end).unwrap_or(0).max(start);
1358 emit(NodeId(id), Event::TextSelected { start, end });
1359 });
1360}
1361extern "C" fn on_text_scale() {
1362 ffi_guard::contain((), day_core::note_text_size_changed);
1363}
1364extern "C" fn on_link(id: u64, s: *const c_char) {
1365 ffi_guard::contain((), || {
1366 let url = unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned();
1367 emit(NodeId(id), Event::LinkActivated(url));
1368 });
1369}
1370extern "C" fn on_slider(id: u64, v: c_int, committed: c_int) {
1371 ffi_guard::contain((), || {
1372 let (min, max) = RANGES.with(|r| r.get(id as usize)).unwrap_or((0.0, 1.0));
1373 let value = min + (f64::from(v) / 1000.0) * (max - min);
1374 emit(NodeId(id), Event::ValueChanged(value));
1377 if committed != 0 {
1378 emit(NodeId(id), Event::ValueCommitted(value));
1379 }
1380 });
1381}
1382fn key_phase(phase: c_int) -> day_spec::KeyPhase {
1385 match phase {
1386 1 => day_spec::KeyPhase::Repeat,
1387 2 => day_spec::KeyPhase::Up,
1388 _ => day_spec::KeyPhase::Down,
1389 }
1390}
1391
1392extern "C" fn on_key(id: u64, code: c_int, modifiers: c_int, phase: c_int) -> c_int {
1397 ffi_guard::contain(0, || {
1398 let key = match code {
1399 0 => "ArrowLeft",
1400 1 => "ArrowRight",
1401 2 => "ArrowUp",
1402 3 => "ArrowDown",
1403 10..=19 => day_spec::KeyEvent::DIGITS[(code - 10) as usize],
1404 _ => return 0,
1405 };
1406 let node = NodeId(id);
1407 let phase = key_phase(phase);
1408 if phase != day_spec::KeyPhase::Up && !day_spec::keys::handled(node) {
1409 return 0;
1410 }
1411 emit(
1412 node,
1413 Event::Key(day_spec::KeyEvent::named(key, modifiers as u8).with_phase(phase)),
1414 );
1415 1
1416 })
1417}
1418
1419extern "C" fn on_field_key(
1423 id: u64,
1424 name: *const c_char,
1425 modifiers: c_int,
1426 deliver: c_int,
1427 phase: c_int,
1428) -> c_int {
1429 ffi_guard::contain(0, || {
1430 let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy();
1432 let node = NodeId(id);
1433 let phase = key_phase(phase);
1434 if phase == day_spec::KeyPhase::Up {
1435 let up = day_spec::KeyEvent::named(name, modifiers as u8).with_phase(phase);
1436 emit(node, Event::Key(up));
1437 return 1;
1438 }
1439 if !day_spec::keys::field_claims(node, &name, modifiers as u8) {
1440 return 0;
1441 }
1442 if deliver != 0 {
1443 emit(
1444 node,
1445 Event::Key(day_spec::KeyEvent::named(name, 0).with_phase(phase)),
1446 );
1447 }
1448 1
1449 })
1450}
1451
1452extern "C" fn on_text_key_query(id: u64) -> c_int {
1455 ffi_guard::contain(0, || c_int::from(day_spec::keys::text(NodeId(id))))
1456}
1457
1458extern "C" fn on_text_key(
1462 id: u64,
1463 name: *const c_char,
1464 text: *const c_char,
1465 modifiers: c_int,
1466 phase: c_int,
1467) -> c_int {
1468 ffi_guard::contain(0, || {
1469 let read = |p: *const c_char| {
1471 (!p.is_null()).then(|| {
1472 unsafe { std::ffi::CStr::from_ptr(p) }
1473 .to_string_lossy()
1474 .into_owned()
1475 })
1476 };
1477 let key = read(name).unwrap_or_default();
1478 let node = NodeId(id);
1479 let phase = key_phase(phase);
1480 if phase != day_spec::KeyPhase::Up && !day_spec::keys::handled(node) {
1481 return 0;
1482 }
1483 let modifiers = modifiers as u8;
1484 let event = match read(text) {
1485 Some(text) => day_spec::KeyEvent::typed_by(key, text, modifiers),
1486 None => day_spec::KeyEvent::named(key, modifiers),
1487 };
1488 emit(node, Event::Key(event.with_phase(phase)));
1489 1
1490 })
1491}
1492
1493extern "C" fn on_cover_escape(id: u64) {
1496 ffi_guard::contain((), || {
1497 let node = COVERS
1498 .with(|c| c.borrow().last().map(|(_, node)| *node))
1499 .unwrap_or(NodeId(id));
1500 emit(
1501 node,
1502 Event::NavBack {
1503 already_popped: false,
1504 },
1505 );
1506 });
1507}
1508
1509extern "C" fn on_focus(id: u64, kind: c_int) {
1512 ffi_guard::contain((), || {
1513 let ev = match kind {
1514 2 => Event::Submitted,
1515 k => Event::FocusChanged(k != 0),
1516 };
1517 emit(NodeId(id), ev);
1518 });
1519}
1520
1521extern "C" fn on_gesture(id: u64, phase: c_int, x: f64, y: f64, tx: f64, ty: f64) {
1526 use day_spec::{DragPhase, Point};
1527 ffi_guard::contain((), || {
1528 let at = Point::new(x, y);
1529 let seq_phase = |p: c_int| match p {
1530 0 => DragPhase::Began,
1531 2 => DragPhase::Ended,
1532 _ => DragPhase::Changed,
1533 };
1534 let ev = match phase {
1535 0 => Event::Tap(at),
1536 1 => Event::Drag {
1537 phase: DragPhase::Began,
1538 location: at,
1539 translation: Point::ZERO,
1540 },
1541 3 => Event::Drag {
1542 phase: DragPhase::Ended,
1543 location: at,
1544 translation: Point::new(tx, ty),
1545 },
1546 4..=6 => Event::Pinch {
1547 phase: seq_phase(phase - 4),
1548 scale: tx,
1549 location: at,
1550 },
1551 7..=9 => Event::Pan {
1552 phase: seq_phase(phase - 7),
1553 delta: Point::new(tx, ty),
1554 location: at,
1555 },
1556 10..=12 => Event::Hover {
1557 phase: seq_phase(phase - 10),
1558 location: at,
1559 },
1560 13..=15 => Event::Rotate {
1561 phase: seq_phase(phase - 13),
1562 rotation: tx,
1563 location: at,
1564 },
1565 16 => Event::LongPress(at),
1566 17 => Event::DoubleTap(at),
1567 18 | 19 => Event::Press {
1568 pressed: phase == 18,
1569 location: at,
1570 },
1571 _ => Event::Drag {
1572 phase: DragPhase::Changed,
1573 location: at,
1574 translation: Point::new(tx, ty),
1575 },
1576 };
1577 emit(NodeId(id), ev);
1578 });
1579}
1580
1581extern "C" fn on_touches(id: u64, data: *const c_double, count: c_int) {
1584 ffi_guard::contain((), || {
1585 let len = usize::try_from(count).unwrap_or(0) * 6;
1586 if data.is_null() || len == 0 {
1587 return;
1588 }
1589 let numbers = unsafe { std::slice::from_raw_parts(data, len) };
1591 emit(NodeId(id), Event::Touches(contacts(numbers)));
1592 });
1593}
1594
1595fn contacts(numbers: &[f64]) -> Vec<day_spec::Touch> {
1598 use day_spec::{Point, Touch, TouchPhase};
1599 numbers
1600 .as_chunks::<6>()
1601 .0
1602 .iter()
1603 .map(|c| {
1604 let phase = match c[1] as i32 {
1605 0 => TouchPhase::Began,
1606 2 => TouchPhase::Stationary,
1607 3 => TouchPhase::Ended,
1608 4 => TouchPhase::Cancelled,
1609 _ => TouchPhase::Moved,
1610 };
1611 Touch::new(c[0] as u64, phase, Point::new(c[2], c[3]))
1612 .with_pressure(c[4])
1613 .with_kind(pointer_kind(c[5] as c_int))
1614 })
1615 .collect()
1616}
1617
1618fn pointer_kind(code: c_int) -> day_spec::PointerKind {
1620 match code {
1621 0 => day_spec::PointerKind::Touch,
1622 2 => day_spec::PointerKind::Stylus,
1623 _ => day_spec::PointerKind::Mouse,
1624 }
1625}
1626
1627extern "C" fn on_pointer_kind(code: c_int) {
1630 ffi_guard::contain((), || {
1631 emit(
1632 day_spec::WINDOW_NODE,
1633 Event::PointerKindChanged(pointer_kind(code)),
1634 );
1635 });
1636}
1637
1638fn passive(w: *mut c_void) -> QtHandle {
1642 unsafe { ffi::day_qt_set_passive(w) };
1644 QtHandle(w)
1645}
1646
1647fn slider_ticks(value: f64, min: f64, max: f64) -> c_int {
1648 if max <= min {
1649 return 0;
1650 }
1651 (((value - min) / (max - min)) * 1000.0).round() as c_int
1652}
1653
1654fn progress_ticks(fraction: f64) -> c_int {
1656 (fraction.clamp(0.0, 1.0) * 1000.0).round() as c_int
1657}
1658
1659#[distributed_slice]
1661pub static RENDERERS: [fn() -> Renderer<Qt>];
1662
1663struct QtWin {
1666 #[cfg(target_os = "macos")]
1667 id: NodeId,
1668 #[cfg(target_os = "macos")]
1669 tab_group: Option<String>,
1670 win: *mut c_void,
1671 content: *mut c_void,
1672}
1673
1674pub struct Qt {
1675 registry: Registry<Qt>,
1676 window: *mut c_void,
1677 secondary: Vec<QtWin>,
1678 toolbars: std::collections::HashMap<usize, day_spec::ToolbarMirror>,
1680 trays: Vec<(day_spec::StatusItemSpec, *mut c_void)>,
1682}
1683
1684impl Qt {
1685 #[must_use]
1686 pub fn new() -> Self {
1687 register_resources();
1688 let mut registry = Registry::default();
1689 for f in RENDERERS {
1690 registry.register(f());
1691 }
1692 Qt {
1693 registry,
1694 window: std::ptr::null_mut(),
1695 secondary: Vec::new(),
1696 toolbars: std::collections::HashMap::new(),
1697 trays: Vec::new(),
1698 }
1699 }
1700
1701 fn qt_window_for(&self, host: &QtHandle) -> Option<*mut c_void> {
1704 match self.secondary.iter().find(|w| w.content == host.0) {
1705 Some(w) => Some(w.win),
1706 None if !self.window.is_null() && host.0 == self.window => Some(self.window),
1707 None => None,
1708 }
1709 }
1710
1711 fn present_parent(&self) -> *mut c_void {
1714 self.secondary
1715 .iter()
1716 .find(|w| unsafe { ffi::day_qt_window_is_active(w.win) } != 0)
1717 .map_or(self.window, |w| w.win)
1718 }
1719}
1720
1721fn register_resources() {
1725 let Ok(path) = std::env::var("DAY_QRESOURCE") else {
1726 return;
1727 };
1728 unsafe { ffi::day_qt_register_resource(cstr(&path).as_ptr()) };
1729 day_spec::resource::set_resource_opener(open_resource);
1730}
1731
1732fn open_resource(name: &str) -> Option<day_spec::resource::Resource> {
1735 let respath = format!(":/day/assets/{name}");
1736 let mut len: usize = 0;
1737 let ptr = unsafe { ffi::day_qt_resource_data(cstr(&respath).as_ptr(), &raw mut len) };
1738 if ptr.is_null() {
1739 return None;
1740 }
1741 Some(unsafe { day_spec::resource::Resource::from_raw(ptr.cast::<u8>(), len, Box::new(())) })
1742}
1743
1744impl Default for Qt {
1745 fn default() -> Self {
1746 Self::new()
1747 }
1748}
1749
1750fn content_of(parent: &QtHandle) -> *mut c_void {
1751 let inner = unsafe { ffi::day_qt_scroll_content(parent.0) };
1753 if inner.is_null() { parent.0 } else { inner }
1754}
1755
1756#[must_use]
1760#[expect(
1761 clippy::match_same_arms,
1762 reason = "one row per text style, in the order of the type scale it approximates"
1763)]
1764pub fn qt_style(f: Font) -> (f64, day_spec::FontWeight) {
1765 use day_spec::FontWeight::{Regular, Semibold};
1766 match f {
1767 Font::LargeTitle => (26.0, Regular),
1768 Font::Title => (22.0, Regular),
1769 Font::Title2 => (17.0, Regular),
1770 Font::Title3 => (15.0, Regular),
1771 Font::Headline => (13.0, Semibold),
1772 Font::Subheadline => (11.0, Regular),
1773 Font::Body => (13.0, Regular),
1774 Font::Callout => (12.0, Regular),
1775 Font::Footnote => (10.0, Regular),
1776 Font::Caption => (10.0, Regular),
1777 Font::Caption2 => (10.0, Regular),
1778 Font::System(pt) | Font::Custom(_, pt) => (pt, Regular),
1779 }
1780}
1781
1782fn set_label_runs(w: *mut c_void, text: &str, runs: &[day_spec::TextRun]) {
1787 if runs.is_empty() {
1788 unsafe { ffi::day_qt_label_set_text(w, cstr(text).as_ptr()) };
1791 return;
1792 }
1793 let base_pt = LABEL_PT
1794 .with(|t| t.get(w as usize))
1795 .unwrap_or_else(|| qt_style(Font::Body).0);
1796 let html = qt_label_markup(text, runs, base_pt);
1797 unsafe { ffi::day_qt_label_set_rich_text(w, cstr(&html).as_ptr()) };
1798}
1799
1800fn qt_underline_style(style: day_spec::DecorationStyle) -> &'static str {
1803 match style {
1804 day_spec::DecorationStyle::Single | day_spec::DecorationStyle::Double => "solid",
1805 day_spec::DecorationStyle::Dotted => "dotted",
1806 day_spec::DecorationStyle::Wavy => "wave",
1807 }
1808}
1809
1810fn qt_label_markup(text: &str, runs: &[day_spec::TextRun], base_pt: f64) -> String {
1822 use std::fmt::Write as _;
1823 let dialect = day_spec::MarkupDialect::QtHtml;
1824 let mut out = String::with_capacity(text.len() + runs.len() * 32);
1825 let mut at = 0usize;
1826 for r in runs {
1827 let Some(styled) = text.get(r.range.clone()) else {
1828 continue;
1829 };
1830 if r.range.start > at
1831 && let Some(plain) = text.get(at..r.range.start)
1832 {
1833 out.push_str(&day_spec::runs_to_markup(plain, &[], dialect, base_pt));
1834 }
1835 let mut inner = r.clone();
1836 inner.range = 0..styled.len();
1837 if inner.strikethrough.is_some() {
1839 inner.strikethrough = Some(day_spec::Decoration::SINGLE);
1840 }
1841 inner.font.small_caps = false;
1846 match r
1847 .underline
1848 .filter(|d| d.style != day_spec::DecorationStyle::Single)
1849 {
1850 Some(d) => {
1851 inner.underline = None;
1852 let _ = write!(
1853 out,
1854 "<span style=\"text-underline-style:{};",
1855 qt_underline_style(d.style)
1856 );
1857 if let Some(c) = d.color {
1858 let _ = write!(out, "text-decoration-color:{};", css_hex(c.resolved()));
1859 }
1860 out.push_str("\">");
1861 out.push_str(&day_spec::runs_to_markup(
1862 styled,
1863 &[inner],
1864 dialect,
1865 base_pt,
1866 ));
1867 out.push_str("</span>");
1868 }
1869 None => {
1870 out.push_str(&day_spec::runs_to_markup(
1871 styled,
1872 &[inner],
1873 dialect,
1874 base_pt,
1875 ));
1876 }
1877 }
1878 at = r.range.end;
1879 }
1880 if let Some(tail) = text.get(at..) {
1881 out.push_str(&day_spec::runs_to_markup(tail, &[], dialect, base_pt));
1882 }
1883 out
1884}
1885
1886fn css_hex(c: day_spec::Color) -> String {
1888 let byte = |v: f64| (v.clamp(0.0, 1.0) * 255.0) as u8;
1889 format!("#{:02x}{:02x}{:02x}", byte(c.r), byte(c.g), byte(c.b))
1890}
1891
1892fn remember_label_pt(w: *mut c_void, f: day_spec::FontSpec) {
1894 LABEL_PT.with(|t| t.insert(w as usize, f.resolved_points(qt_style(f.style).0)));
1895}
1896
1897unsafe fn apply_custom_family(w: *mut c_void, spec: day_spec::FontSpec) {
1901 if let Font::Custom(family, _) = spec.style {
1902 unsafe { ffi::day_qt_label_set_font_family(w, cstr(family).as_ptr()) };
1903 }
1904}
1905
1906fn qt_weight(w: day_spec::FontWeight) -> c_int {
1908 use day_spec::FontWeight as W;
1909 match w {
1910 W::Thin => 100,
1911 W::UltraLight => 200,
1912 W::Light => 300,
1913 W::Regular => 400,
1914 W::Medium => 500,
1915 W::Semibold => 600,
1916 W::Bold => 700,
1917 W::Heavy => 800,
1918 W::Black => 900,
1919 }
1920}
1921
1922struct FontParams {
1924 pt: f64,
1926 weight: c_int,
1927 italic: c_int,
1928 tabular: c_int,
1929 small_caps: c_int,
1930 oldstyle: c_int,
1931}
1932
1933fn font_params(spec: day_spec::FontSpec) -> FontParams {
1934 let (pt, inherent) = qt_style(spec.style);
1935 FontParams {
1936 pt: spec.resolved_points(pt),
1937 weight: qt_weight(spec.weight.unwrap_or(inherent)),
1938 italic: c_int::from(spec.italic),
1939 tabular: c_int::from(spec.tabular),
1940 small_caps: c_int::from(spec.small_caps),
1941 oldstyle: c_int::from(spec.oldstyle_figures),
1942 }
1943}
1944
1945fn apply_label_font(w: *mut c_void, spec: day_spec::FontSpec) {
1947 let f = font_params(spec);
1948 unsafe {
1950 ffi::day_qt_label_set_font(
1951 w,
1952 f.pt,
1953 f.weight,
1954 f.italic,
1955 f.tabular,
1956 f.small_caps,
1957 f.oldstyle,
1958 );
1959 }
1960}
1961
1962fn apply_paragraph(w: *mut c_void, p: &day_spec::props::LabelParagraph) {
1964 let truncation = match p.truncation {
1965 day_spec::props::Truncation::Tail => 0,
1966 day_spec::props::Truncation::Head => 1,
1967 day_spec::props::Truncation::Middle => 2,
1968 };
1969 let max_lines = c_int::try_from(p.max_lines).unwrap_or(c_int::MAX);
1970 unsafe {
1972 ffi::day_qt_label_set_paragraph(w, max_lines, truncation, p.letter_spacing, p.line_height);
1973 };
1974}
1975
1976fn label_align(a: day_spec::props::TextAlign) -> c_int {
1978 match a {
1979 day_spec::props::TextAlign::Leading => 0,
1980 day_spec::props::TextAlign::Center => 1,
1981 day_spec::props::TextAlign::Trailing => 2,
1982 day_spec::props::TextAlign::Justified => 3,
1983 }
1984}
1985
1986struct NavState {
1992 sidebar_pane: *mut std::os::raw::c_void,
1993 detail_pane: *mut std::os::raw::c_void,
1994 pages: Vec<(QtHandle, NodeId)>,
1997 sidebar_page: Option<QtHandle>,
1999 split: bool,
2001 sidebar_shown: bool,
2004 list_pane: *mut std::os::raw::c_void,
2010 list_width: Option<f64>,
2011 list_page: Option<QtHandle>,
2014 list_shown: bool,
2016 list_positioned: bool,
2019 titles: Vec<String>,
2022}
2023
2024pub(crate) fn toggle_sidebar(host: *mut std::os::raw::c_void) -> bool {
2029 let flip = NAV_STATE.with(|m| {
2031 let mut m = m.borrow_mut();
2032 let st = m.get_mut(&(host as usize))?;
2033 if !st.split {
2034 return None;
2035 }
2036 st.sidebar_shown = !st.sidebar_shown;
2037 Some((st.sidebar_pane, st.sidebar_shown))
2038 });
2039 match flip {
2040 Some((pane, shown)) => {
2041 unsafe { ffi::day_qt_set_visible(pane, i32::from(shown)) };
2042 true
2043 }
2044 None => false,
2045 }
2046}
2047
2048extern "C" fn nav_back_clicked(id: u64) {
2051 ffi_guard::contain((), || {
2052 emit(
2053 NodeId(id),
2054 Event::NavBack {
2055 already_popped: false,
2056 },
2057 );
2058 });
2059}
2060
2061fn nav_sync_header(host: *mut std::os::raw::c_void) {
2064 let (visible, title) = NAV_STATE.with(|m| {
2065 let m = m.borrow();
2066 let Some(state) = m.get(&(host as usize)) else {
2067 return (false, String::new());
2068 };
2069 (
2070 !state.split && state.pages.len() >= 2,
2071 state.titles.last().cloned().unwrap_or_default(),
2072 )
2073 });
2074 unsafe {
2075 ffi::day_qt_nav_header_update(host, c_int::from(visible), cstr(&title).as_ptr());
2076 }
2077 nav_sync_panes(host);
2078}
2079
2080fn is_sidebar_page(page: *mut std::os::raw::c_void) -> bool {
2082 PAGE_PANE
2083 .with(|m| m.borrow().get(&(page as usize)).copied() == Some(day_spec::props::Pane::Sidebar))
2084}
2085
2086fn is_list_page(page: *mut std::os::raw::c_void) -> bool {
2089 PAGE_PANE
2090 .with(|m| m.borrow().get(&(page as usize)).copied() == Some(day_spec::props::Pane::List))
2091}
2092
2093fn nav_present(host: *mut std::os::raw::c_void, split: bool) {
2101 let Some((sidebar_page, sidebar_pane, detail_pane, was_split)) = NAV_STATE.with(|m| {
2102 let st = m.borrow();
2103 let s = st.get(&(host as usize))?;
2104 Some((s.sidebar_page, s.sidebar_pane, s.detail_pane, s.split))
2105 }) else {
2106 return;
2107 };
2108 if was_split == split {
2109 return;
2110 }
2111 unsafe {
2112 ffi::day_qt_set_visible(sidebar_pane, i32::from(split));
2113 if let Some(page) = sidebar_page {
2114 ffi::day_qt_add_child(if split { sidebar_pane } else { detail_pane }, page.0);
2116 ffi::day_qt_set_visible(page.0, 1);
2117 }
2118 }
2119 NAV_STATE.with(|m| {
2120 let mut m = m.borrow_mut();
2121 if let Some(s) = m.get_mut(&(host as usize)) {
2122 s.split = split;
2123 s.sidebar_shown = split;
2124 let detail: Vec<QtHandle> = s
2127 .pages
2128 .iter()
2129 .filter(|(p, _)| !(split && is_sidebar_page(p.0) || is_list_page(p.0)))
2130 .map(|(p, _)| *p)
2131 .collect();
2132 let last = detail.len().saturating_sub(1);
2133 for (i, page) in detail.iter().enumerate() {
2134 unsafe { ffi::day_qt_set_visible(page.0, i32::from(i == last)) };
2135 }
2136 }
2137 });
2138 let host_addr = host as usize;
2142 <Qt as Platform>::post(Box::new(move || {
2143 nav_sync_header(host_addr as *mut std::os::raw::c_void);
2144 }));
2145}
2146
2147fn nav_sync_panes(host: *mut std::os::raw::c_void) {
2149 let reports: Vec<(NodeId, Size)> = NAV_STATE.with(|m| {
2150 let m = m.borrow();
2151 let Some(state) = m.get(&(host as usize)) else {
2152 return Vec::new();
2153 };
2154 let (mut sw, mut sh, mut lw, mut lh, mut dw, mut dh) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
2155 unsafe {
2156 ffi::day_qt_widget_size(state.sidebar_pane, &raw mut sw, &raw mut sh);
2157 ffi::day_qt_widget_size(state.list_pane, &raw mut lw, &raw mut lh);
2158 ffi::day_qt_widget_size(state.detail_pane, &raw mut dw, &raw mut dh);
2159 }
2160 if sh <= 0.0 && dh <= 0.0 {
2161 return Vec::new();
2162 }
2163 state
2164 .pages
2165 .iter()
2166 .map(|(page, id)| {
2167 let size = if state.split && is_sidebar_page(page.0) {
2170 Size::new(sw, sh)
2171 } else if is_list_page(page.0) {
2172 Size::new(lw, lh)
2173 } else {
2174 Size::new(dw, dh)
2175 };
2176 (*id, size)
2177 })
2178 .collect()
2179 });
2180 for (id, size) in reports {
2181 emit(id, Event::FrameChanged(size));
2182 }
2183}
2184
2185extern "C" fn nav_splitter_moved(host: *mut std::os::raw::c_void) {
2186 ffi_guard::contain((), || {
2187 nav_sync_panes(host);
2188 unsafe { ffi::day_qt_toolbar_sync_columns(host) };
2190 });
2191}
2192
2193struct InspectorState {
2199 content_pane: *mut std::os::raw::c_void,
2200 panel_pane: *mut std::os::raw::c_void,
2201 panes: Vec<(NodeId, bool)>,
2203 width: f64,
2204 shown: bool,
2205}
2206
2207fn inspector_sync_panes(host: *mut std::os::raw::c_void) {
2211 let reports: Vec<(NodeId, Size)> = INSPECTOR_STATE.with(|m| {
2212 let m = m.borrow();
2213 let Some(state) = m.get(&(host as usize)) else {
2214 return Vec::new();
2215 };
2216 let (mut cw, mut ch, mut pw, mut ph) = (0.0, 0.0, 0.0, 0.0);
2217 unsafe {
2218 ffi::day_qt_widget_size(state.content_pane, &raw mut cw, &raw mut ch);
2219 ffi::day_qt_widget_size(state.panel_pane, &raw mut pw, &raw mut ph);
2220 }
2221 let _ = ph;
2222 if ch <= 0.0 {
2223 return Vec::new();
2224 }
2225 state
2226 .panes
2227 .iter()
2228 .map(|(id, panel)| {
2229 let size = if *panel {
2230 let w = if state.shown && pw > 0.0 {
2231 pw
2232 } else {
2233 state.width
2234 };
2235 Size::new(w, ch)
2236 } else {
2237 Size::new(cw, ch)
2238 };
2239 (*id, size)
2240 })
2241 .collect()
2242 });
2243 for (id, size) in reports {
2244 emit(id, Event::FrameChanged(size));
2245 }
2246}
2247
2248extern "C" fn inspector_splitter_moved(host: *mut std::os::raw::c_void) {
2249 ffi_guard::contain((), || inspector_sync_panes(host));
2250}
2251
2252struct SplitState {
2258 first_pane: *mut std::os::raw::c_void,
2259 second_pane: *mut std::os::raw::c_void,
2260 node: NodeId,
2261 panes: Vec<(NodeId, bool)>,
2263 share: f64,
2265 min_pane: f64,
2266 placed: bool,
2268 suppress: bool,
2270}
2271
2272fn split_sync_panes(host: *mut std::os::raw::c_void) {
2275 let reports: Vec<(NodeId, Size)> = SPLIT_STATE.with(|m| {
2276 let m = m.borrow();
2277 let Some(state) = m.get(&(host as usize)) else {
2278 return Vec::new();
2279 };
2280 let (mut aw, mut ah, mut bw, mut bh) = (0.0, 0.0, 0.0, 0.0);
2281 unsafe {
2282 ffi::day_qt_widget_size(state.first_pane, &raw mut aw, &raw mut ah);
2283 ffi::day_qt_widget_size(state.second_pane, &raw mut bw, &raw mut bh);
2284 }
2285 if aw <= 0.0 || ah <= 0.0 {
2286 return Vec::new();
2287 }
2288 state
2289 .panes
2290 .iter()
2291 .map(|(id, second)| {
2292 let size = if *second {
2293 Size::new(bw, bh)
2294 } else {
2295 Size::new(aw, ah)
2296 };
2297 (*id, size)
2298 })
2299 .collect()
2300 });
2301 for (id, size) in reports {
2302 emit(id, Event::FrameChanged(size));
2303 }
2304}
2305
2306extern "C" fn split_resized(host: *mut std::os::raw::c_void) {
2309 ffi_guard::contain((), || {
2310 let place = SPLIT_STATE.with(|m| {
2311 let mut m = m.borrow_mut();
2312 let state = m.get_mut(&(host as usize))?;
2313 let (mut w, mut h) = (0.0, 0.0);
2314 unsafe { ffi::day_qt_widget_size(host, &raw mut w, &raw mut h) };
2315 if state.placed || w <= 0.0 || h <= 0.0 {
2316 return None;
2317 }
2318 state.placed = true;
2319 state.suppress = true;
2320 Some(state.share)
2321 });
2322 if let Some(share) = place {
2323 unsafe { ffi::day_qt_split_set_fraction(host, share) };
2324 SPLIT_STATE.with(|m| {
2325 if let Some(state) = m.borrow_mut().get_mut(&(host as usize)) {
2326 state.suppress = false;
2327 }
2328 });
2329 }
2330 split_sync_panes(host);
2331 });
2332}
2333
2334extern "C" fn split_moved(host: *mut std::os::raw::c_void) {
2336 ffi_guard::contain((), || {
2337 let share = unsafe { ffi::day_qt_split_fraction(host) }.clamp(0.0, 1.0);
2338 let report = SPLIT_STATE.with(|m| {
2339 let mut m = m.borrow_mut();
2340 let state = m.get_mut(&(host as usize))?;
2341 if state.suppress || !state.placed || (share - state.share).abs() <= 1e-4 {
2342 return None;
2343 }
2344 state.share = share;
2345 Some(state.node)
2346 });
2347 if let Some(node) = report {
2348 emit(node, Event::ValueChanged(share));
2349 }
2350 split_sync_panes(host);
2351 });
2352}
2353
2354struct NavSuite {
2360 host: NodeId,
2363 menu_node: NodeId,
2366 pages: Vec<(QtHandle, NodeId)>,
2369 titles: Vec<String>,
2371 icons: Vec<Option<String>>,
2372 keys: Vec<String>,
2373}
2374
2375fn suite_apply_rows(host: *mut std::os::raw::c_void) {
2381 NAV_SUITES.with(|m| {
2382 let m = m.borrow();
2383 let Some(suite) = m.get(&(host as usize)) else {
2384 return;
2385 };
2386 for (i, title) in suite.titles.iter().enumerate() {
2387 if i >= suite.pages.len() {
2389 break;
2390 }
2391 let at = i as c_int;
2392 unsafe { ffi::day_qt_tabs_set_title(host, at, cstr(title).as_ptr()) };
2393 let icon = suite
2394 .icons
2395 .get(i)
2396 .and_then(|o| o.as_deref())
2397 .filter(|n| !n.is_empty())
2398 .map_or_default(icon_file_path);
2399 if !icon.is_empty() {
2400 unsafe { ffi::day_qt_tabs_set_icon(host, at, cstr(&icon).as_ptr()) };
2401 }
2402 }
2403 });
2404}
2405
2406fn nav_suite_sync(host: *mut std::os::raw::c_void) {
2410 let reports: Vec<(NodeId, Size)> = NAV_SUITES.with(|m| {
2411 let m = m.borrow();
2412 let Some(suite) = m.get(&(host as usize)) else {
2413 return Vec::new();
2414 };
2415 let (mut w, mut h) = (0.0, 0.0);
2416 unsafe { ffi::day_qt_tabs_content_size(host, &raw mut w, &raw mut h) };
2417 if w <= 0.0 || h <= 0.0 {
2418 return Vec::new();
2419 }
2420 suite
2421 .pages
2422 .iter()
2423 .map(|(_, id)| (*id, Size::new(w, h)))
2424 .collect()
2425 });
2426 for (id, size) in reports {
2427 emit(id, Event::FrameChanged(size));
2428 }
2429}
2430
2431type NavRow = (NodeId, Vec<String>, Vec<Option<String>>, Vec<String>);
2433
2434extern "C" fn nav_suite_changed(id: u64, index: c_int) {
2436 ffi_guard::contain((), || {
2437 let node = NAV_SUITES.with(|m| {
2438 m.borrow()
2439 .values()
2440 .find(|s| s.host.0 == id && s.menu_node.0 != 0)
2441 .map(|s| s.menu_node)
2442 });
2443 emit(
2444 node.unwrap_or(NodeId(id)),
2445 Event::SelectionChanged(i64::from(index)),
2446 );
2447 });
2448}
2449
2450extern "C" fn document_tab_event(id: u64, action: c_int, index: c_int, to: c_int) {
2451 ffi_guard::contain((), || {
2452 let key = NAV_SUITES
2453 .with(|m| {
2454 m.borrow()
2455 .values()
2456 .find(|s| s.host.0 == id)
2457 .and_then(|s| s.keys.get(index.saturating_sub(1) as usize))
2458 .cloned()
2459 })
2460 .unwrap_or_default();
2461 let tag = match action {
2462 0 => "day:tab-new",
2463 1 => "day:tab-close",
2464 _ => "day:tab-move",
2465 };
2466 emit(
2467 NodeId(id),
2468 Event::Custom {
2469 tag,
2470 num: f64::from((to - 1).max(0)),
2471 text: key,
2472 },
2473 );
2474 });
2475}
2476
2477extern "C" fn present_cb(req: u64, tag: c_int, index: i64, text: *const c_char) {
2479 ffi_guard::contain((), || {
2480 let text = if text.is_null() {
2481 String::new()
2482 } else {
2483 unsafe { CStr::from_ptr(text) }
2484 .to_string_lossy()
2485 .into_owned()
2486 };
2487 let result = day_spec::present::PresentResult::decode(tag, index, text);
2488 emit_window(Event::PresentResult { req, result });
2489 });
2490}
2491
2492fn emit_window(ev: Event) {
2493 let sink = SINK.with(|s| s.borrow().clone());
2494 if let Some(sink) = sink {
2495 sink(day_spec::WINDOW_NODE, ev);
2496 }
2497}
2498
2499extern "C" fn win_resized(node: u64, w: c_int, h: c_int) {
2501 ffi_guard::contain((), || {
2502 emit(
2503 day_spec::NodeId(node),
2504 Event::WindowResized(Size::new(f64::from(w), f64::from(h))),
2505 );
2506 });
2507}
2508extern "C" fn win_closed(node: u64) {
2509 let target = if node == 0 {
2512 day_spec::WINDOW_NODE
2513 } else {
2514 day_spec::NodeId(node)
2515 };
2516 ffi_guard::contain((), || emit(target, Event::WindowClosed));
2517}
2518extern "C" fn win_focused(node: u64, active: c_int) {
2519 ffi_guard::contain((), || {
2520 emit(day_spec::NodeId(node), Event::WindowFocused(active != 0));
2521 });
2522}
2523
2524extern "C" fn win_state(node: u64, code: c_int) {
2527 ffi_guard::contain((), || {
2528 let state = day_spec::WindowState::from_code(code);
2529 log::debug!("qt: window state now {state:?}");
2530 let target = if node == 0 {
2531 day_spec::WINDOW_NODE
2532 } else {
2533 day_spec::NodeId(node)
2534 };
2535 emit(target, Event::WindowStateChanged(state));
2536 });
2537}
2538
2539extern "C" fn window_resized(w: c_int, h: c_int) {
2540 ffi_guard::contain((), || {
2541 let size = Size::new(f64::from(w), f64::from(h));
2542 LAST_WINDOW_SIZE.with(|c| c.set(size));
2543 emit(day_spec::WINDOW_NODE, Event::WindowResized(size));
2544 COVERS.with(|c| {
2547 for (cover, node) in c.borrow().iter() {
2548 let (y, size) = cover_frame(*cover, size);
2549 unsafe {
2550 ffi::day_qt_set_geometry(
2551 *cover,
2552 0,
2553 y as c_int,
2554 size.width as c_int,
2555 size.height as c_int,
2556 );
2557 };
2558 emit(*node, Event::FrameChanged(size));
2559 }
2560 });
2561 });
2562}
2563
2564fn cover_frame(cover: *mut c_void, area: Size) -> (f64, Size) {
2567 if COVER_HALF.with(|s| s.borrow().contains(&(cover as usize))) {
2568 let h = (area.height * 0.5).floor();
2569 (area.height - h, Size::new(area.width, h))
2570 } else {
2571 (0.0, area)
2572 }
2573}
2574
2575extern "C" fn nav_menu_changed(id: u64, row: std::os::raw::c_int) {
2576 ffi_guard::contain((), || {
2580 if row >= 0 {
2581 emit_deferred(NodeId(id), Event::SelectionChanged(i64::from(row)));
2582 }
2583 });
2584}
2585
2586extern "C" fn on_menu_action(id: u64) {
2587 ffi_guard::contain((), || emit_window(Event::MenuAction(id)));
2588}
2589
2590fn icon_file_path(name: &str) -> String {
2593 day_spec::resource::resolve_vector_svg(name)
2597 .or_else(|| day_spec::resource::resolve_image_file(name))
2598 .map_or_default(|p| p.to_string_lossy().into_owned())
2599}
2600
2601fn navlist_apply_row_menus(w: *mut c_void, menus: &[Vec<day_spec::MenuItem>]) {
2605 let ptrs: Vec<*mut c_void> = menus
2606 .iter()
2607 .map(|items| {
2608 if items.is_empty() {
2609 std::ptr::null_mut()
2610 } else {
2611 let m = unsafe { ffi::day_qt_menu_new() };
2612 build_qt_menu(m, items);
2613 m
2614 }
2615 })
2616 .collect();
2617 unsafe { ffi::day_qt_navlist_set_row_menus(w, ptrs.as_ptr(), ptrs.len() as i32) };
2618}
2619
2620fn nav_sections_joined(sections: &[Option<String>]) -> (String, usize) {
2623 let headings = sections.iter().filter(|s| s.is_some()).count();
2624 let joined = sections
2625 .iter()
2626 .map(|s| s.as_deref().unwrap_or_default())
2627 .collect::<Vec<_>>()
2628 .join("\u{1f}");
2629 (joined, headings)
2630}
2631
2632fn hex_argb(c: day_spec::Color) -> String {
2638 format!(
2639 "#{:02x}{:02x}{:02x}{:02x}",
2640 (c.a * 255.0).round() as u8,
2641 (c.r * 255.0) as u8,
2642 (c.g * 255.0) as u8,
2643 (c.b * 255.0) as u8
2644 )
2645}
2646
2647fn image_tint(tint: Option<day_spec::Color>, template: bool) -> String {
2650 match tint {
2651 Some(c) => hex_argb(c),
2652 None if template => "currentColor".to_owned(),
2653 None => String::new(),
2654 }
2655}
2656
2657fn is_styled_surface(p: &ContainerProps) -> bool {
2661 matches!(
2662 p.fill,
2663 Some(day_spec::Paint::Linear(_) | day_spec::Paint::Radial(_) | day_spec::Paint::Conic(_))
2664 ) || p.border.is_some()
2665 || p.shadow.is_some()
2666 || (p.corner_radius > 0.0 && p.corners != day_spec::Corners::ALL)
2667}
2668
2669fn solid_fill(fill: Option<&day_spec::Paint>) -> Option<day_spec::Color> {
2671 match fill {
2672 Some(day_spec::Paint::Solid(ink)) => Some(ink.resolved()),
2673 _ => None,
2674 }
2675}
2676
2677fn surface_spec(p: &ContainerProps) -> ([f64; 24], Vec<f64>) {
2683 use day_spec::Paint;
2684 let rgba = |c: day_spec::Color| [c.r, c.g, c.b, c.a];
2685 let mut spec = [0.0; 24];
2686 spec[0..4].copy_from_slice(&rgba(
2687 solid_fill(p.fill.as_ref()).unwrap_or(day_spec::Color::CLEAR),
2688 ));
2689 spec[4] = p.corner_radius;
2690 spec[5] = f64::from(p.corners.bits());
2691 spec[6] = f64::from(u8::from(p.clips));
2692 if let Some(border) = p.border {
2693 spec[7..11].copy_from_slice(&rgba(border.color.resolved()));
2694 spec[11] = border.width;
2695 }
2696 if let Some(shadow) = p.shadow {
2697 spec[12..16].copy_from_slice(&rgba(shadow.color.resolved()));
2698 spec[16] = shadow.blur;
2699 spec[17] = shadow.dx;
2700 spec[18] = shadow.dy;
2701 }
2702 let gradient = match &p.fill {
2703 Some(Paint::Linear(g)) => Some((1.0, [g.start.x, g.start.y, g.end.x, g.end.y], &g.stops)),
2704 Some(Paint::Radial(g)) => Some((2.0, [g.center.x, g.center.y, g.radius, 0.0], &g.stops)),
2705 Some(Paint::Conic(g)) => Some((
2706 3.0,
2707 [g.center.x, g.center.y, g.start.degrees(), 0.0],
2708 &g.stops,
2709 )),
2710 Some(Paint::Solid(_)) | None => None,
2711 };
2712 let mut stops = Vec::new();
2713 if let Some((kind, numbers, ink_stops)) = gradient {
2714 spec[19] = kind;
2715 spec[20..24].copy_from_slice(&numbers);
2716 for (offset, color) in day_spec::resolved_stops(ink_stops) {
2717 stops.push(offset);
2718 stops.extend_from_slice(&rgba(color));
2719 }
2720 }
2721 (spec, stops)
2722}
2723
2724fn surface_is_dynamic(p: &ContainerProps) -> bool {
2726 p.fill.as_ref().is_some_and(day_spec::Paint::is_dynamic)
2727 || p.border.is_some_and(|b| b.color.is_dynamic())
2728 || p.shadow.is_some_and(|s| s.color.is_dynamic())
2729}
2730
2731unsafe fn apply_surface(w: *mut c_void, p: &ContainerProps, fresh: bool) {
2740 unsafe {
2743 match p.role {
2744 Some(day_spec::SurfaceRole::SectionCard) => {
2745 ffi::day_qt_widget_set_section_card(w, p.corner_radius);
2748 }
2749 Some(day_spec::SurfaceRole::Window) => {
2750 ffi::day_qt_widget_set_window_surface(w, p.corner_radius, c_int::from(p.clips));
2751 }
2752 _ if is_styled_surface(p) || ffi::day_qt_widget_has_styled_surface(w) != 0 => {
2753 let (spec, stops) = surface_spec(p);
2756 ffi::day_qt_widget_set_styled_surface(
2757 w,
2758 spec.as_ptr(),
2759 stops.as_ptr(),
2760 (stops.len() / 5) as c_int,
2761 );
2762 }
2763 _ if !fresh || p.fill.is_some() || p.corner_radius > 0.0 || p.clips => {
2764 let bg = solid_fill(p.fill.as_ref()).unwrap_or(day_spec::Color::CLEAR);
2765 ffi::day_qt_widget_set_surface(
2766 w,
2767 bg.r,
2768 bg.g,
2769 bg.b,
2770 bg.a,
2771 p.corner_radius,
2772 c_int::from(p.clips),
2773 );
2774 }
2775 _ => {}
2776 }
2777 }
2778}
2779
2780#[derive(Clone, Default)]
2788struct Inks {
2789 label_color: Option<day_spec::Ink>,
2790 label_runs: Option<(String, Vec<day_spec::TextRun>)>,
2791 button: Option<day_spec::props::ButtonStyleSpec>,
2792 image_tint: Option<day_spec::Ink>,
2793 nav: Option<NavRows>,
2794 cover: Option<day_spec::Ink>,
2795}
2796
2797impl Inks {
2798 fn is_empty(&self) -> bool {
2799 self.label_color.is_none()
2800 && self.label_runs.is_none()
2801 && self.button.is_none()
2802 && self.image_tint.is_none()
2803 && self.nav.is_none()
2804 && self.cover.is_none()
2805 }
2806}
2807
2808#[derive(Clone, Default)]
2811struct NavRows {
2812 items: Vec<String>,
2813 icons: Vec<Option<String>>,
2814 tints: Vec<Option<day_spec::Ink>>,
2815 badge_icons: Vec<Option<String>>,
2816 badge_tints: Vec<Option<day_spec::Ink>>,
2817 badges: Vec<Option<String>>,
2818}
2819
2820impl NavRows {
2821 fn is_dynamic(&self) -> bool {
2822 self.tints
2823 .iter()
2824 .chain(&self.badge_tints)
2825 .any(|t| t.is_some_and(day_spec::Ink::is_dynamic))
2826 }
2827
2828 fn joined(&self) -> [CString; 6] {
2831 let files = |icons: &[Option<String>]| {
2832 icons
2833 .iter()
2834 .map(|ic| ic.as_deref().map_or_default(icon_file_path))
2835 .collect::<Vec<_>>()
2836 .join("\u{1f}")
2837 };
2838 [
2839 cstr(&self.items.join("\u{1f}")),
2840 cstr(&files(&self.icons)),
2841 cstr(&nav_tints_joined(&self.tints)),
2842 cstr(&files(&self.badge_icons)),
2843 cstr(&nav_tints_joined(&self.badge_tints)),
2844 cstr(&nav_counts_joined(&self.badges)),
2845 ]
2846 }
2847}
2848
2849thread_local! {
2850 static INKS: SideTable<Inks> = SideTable::new();
2852 static SURFACES: SideTable<ContainerProps> = SideTable::new();
2855}
2856
2857fn remember_inks(w: *mut c_void, f: impl FnOnce(&mut Inks)) {
2859 INKS.with(|t| {
2860 let mut inks = t.take(w as usize).unwrap_or_default();
2861 f(&mut inks);
2862 if !inks.is_empty() {
2863 t.insert(w as usize, inks);
2864 }
2865 });
2866}
2867
2868fn dynamic(ink: Option<day_spec::Ink>) -> Option<day_spec::Ink> {
2870 ink.filter(|i| i.is_dynamic())
2871}
2872
2873unsafe fn apply_label_color(w: *mut c_void, color: Option<day_spec::Ink>) {
2878 let c = color.map(day_spec::Ink::resolved);
2879 let (r, g, b, a) = c.map_or((0.0, 0.0, 0.0, 0.0), |c| (c.r, c.g, c.b, c.a));
2880 unsafe { ffi::day_qt_label_set_color(w, r, g, b, a, c_int::from(c.is_some())) };
2882 remember_inks(w, |i| i.label_color = dynamic(color));
2883}
2884
2885fn apply_label_runs(w: *mut c_void, text: &str, runs: &[day_spec::TextRun]) {
2887 set_label_runs(w, text, runs);
2888 let dynamic_runs = runs.iter().any(|r| {
2889 r.color.is_some_and(day_spec::Ink::is_dynamic)
2890 || r.background.is_some_and(day_spec::Ink::is_dynamic)
2891 || r.underline
2892 .and_then(|d| d.color)
2893 .is_some_and(day_spec::Ink::is_dynamic)
2894 || r.strikethrough
2895 .and_then(|d| d.color)
2896 .is_some_and(day_spec::Ink::is_dynamic)
2897 });
2898 remember_inks(w, |i| {
2899 i.label_runs = dynamic_runs.then(|| (text.to_owned(), runs.to_vec()));
2900 });
2901}
2902
2903fn apply_button_style_ink(w: *mut c_void, style: day_spec::props::ButtonStyleSpec) {
2905 apply_button_style(w, style);
2906 let tinted = matches!(style, day_spec::props::ButtonStyleSpec::Tinted(ink) if ink.is_dynamic());
2907 remember_inks(w, |i| i.button = tinted.then_some(style));
2908}
2909
2910unsafe fn apply_nav_rows(
2916 w: *mut c_void,
2917 rows: &NavRows,
2918 update: Option<&[usize]>,
2919 sections: &[Option<String>],
2920) -> usize {
2921 let [joined, icons, tints, badge_icons, badge_tints, counts] = rows.joined();
2922 let mut headings = 0;
2923 unsafe {
2925 if let Some(update) = update {
2926 let rows_joined = update
2927 .iter()
2928 .map(std::string::ToString::to_string)
2929 .collect::<Vec<_>>()
2930 .join(",");
2931 ffi::day_qt_navlist_update_rows(
2932 w,
2933 cstr(&rows_joined).as_ptr(),
2934 joined.as_ptr(),
2935 icons.as_ptr(),
2936 tints.as_ptr(),
2937 badge_icons.as_ptr(),
2938 badge_tints.as_ptr(),
2939 counts.as_ptr(),
2940 );
2941 } else {
2942 let (sections_joined, n) = nav_sections_joined(sections);
2943 headings = n;
2944 ffi::day_qt_navlist_set_items(
2945 w,
2946 joined.as_ptr(),
2947 icons.as_ptr(),
2948 tints.as_ptr(),
2949 badge_icons.as_ptr(),
2950 badge_tints.as_ptr(),
2951 counts.as_ptr(),
2952 cstr(§ions_joined).as_ptr(),
2953 );
2954 }
2955 }
2956 remember_inks(w, |i| i.nav = rows.is_dynamic().then(|| rows.clone()));
2957 headings
2958}
2959
2960fn refresh_appearance() {
2965 day_core::note_appearance_changed();
2966 reapply_inks();
2967}
2968
2969fn reapply_inks() {
2971 let mut surfaces = Vec::new();
2972 SURFACES.with(|t| {
2973 t.for_each(|w, p| {
2974 if surface_is_dynamic(p) {
2975 surfaces.push((w, p.clone()));
2976 }
2977 });
2978 });
2979 for (w, p) in surfaces {
2980 unsafe { apply_surface(w as *mut c_void, &p, false) };
2982 }
2983 let mut inks = Vec::new();
2984 INKS.with(|t| t.for_each(|w, i| inks.push((w, i.clone()))));
2985 for (w, i) in inks {
2986 let w = w as *mut c_void;
2987 unsafe {
2989 if let Some(c) = i.label_color {
2990 apply_label_color(w, Some(c));
2991 }
2992 if let Some((text, runs)) = &i.label_runs {
2993 set_label_runs(w, text, runs);
2994 }
2995 if let Some(style) = i.button {
2996 apply_button_style(w, style);
2997 }
2998 if let Some(tint) = i.image_tint {
2999 let tint = image_tint(Some(tint.resolved()), false);
3000 ffi::day_qt_image_set_tint(w, cstr(&tint).as_ptr());
3001 }
3002 if let Some(rows) = &i.nav {
3003 let all: Vec<usize> = (0..rows.items.len()).collect();
3004 apply_nav_rows(w, rows, Some(&all), &[]);
3005 }
3006 if let Some(bg) = i.cover {
3007 let bg = bg.resolved();
3008 ffi::day_qt_widget_set_bg(w, bg.r, bg.g, bg.b, bg.a, std::ptr::null());
3009 }
3010 }
3011 }
3012}
3013
3014extern "C" fn on_appearance() {
3016 ffi_guard::contain((), refresh_appearance);
3017}
3018
3019fn nav_counts_joined(badges: &[Option<String>]) -> String {
3021 badges
3022 .iter()
3023 .map(|b| b.as_deref().unwrap_or(""))
3024 .collect::<Vec<_>>()
3025 .join("\u{1f}")
3026}
3027
3028fn nav_tints_joined(tints: &[Option<day_spec::Ink>]) -> String {
3030 tints
3031 .iter()
3032 .map(|t| match t.map(day_spec::Ink::resolved) {
3033 Some(c) => format!(
3034 "#{:02x}{:02x}{:02x}",
3035 (c.r * 255.0) as u8,
3036 (c.g * 255.0) as u8,
3037 (c.b * 255.0) as u8
3038 ),
3039 None => String::new(),
3040 })
3041 .collect::<Vec<_>>()
3042 .join("\u{1f}")
3043}
3044
3045#[must_use]
3048pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
3049 phase.is_universal()
3050}
3051
3052extern "C" fn on_lifecycle(code: c_int) {
3054 use day_spec::Lifecycle::{DidBecomeActive, WillResignActive, WillTerminate};
3055 ffi_guard::contain((), || {
3056 let phase = match code {
3057 2 => DidBecomeActive,
3058 3 => WillResignActive,
3059 7 => WillTerminate,
3060 _ => return,
3061 };
3062 emit_window(Event::Lifecycle(phase));
3063 });
3064}
3065
3066fn qt_shortcut(sc: &day_spec::Shortcut) -> String {
3069 let mut parts: Vec<String> = Vec::new();
3070 if sc.primary {
3071 parts.push("Ctrl".into());
3072 }
3073 if sc.shift {
3074 parts.push("Shift".into());
3075 }
3076 if sc.alt {
3077 parts.push("Alt".into());
3078 }
3079 if sc.control {
3080 #[cfg(target_os = "macos")]
3082 parts.push("Meta".into());
3083 #[cfg(not(target_os = "macos"))]
3084 parts.push("Ctrl".into());
3085 }
3086 let key = if sc.key.chars().count() == 1 {
3088 sc.key.to_uppercase()
3089 } else {
3090 sc.key.clone()
3091 };
3092 parts.push(key);
3093 parts.join("+")
3097}
3098
3099fn qt_role_label(role: day_spec::MenuRole) -> &'static str {
3101 use day_spec::MenuRole::{
3102 About, CheckForUpdates, CloseWindow, Copy, Cut, Delete, Fullscreen, Minimize, NewWindow,
3103 Paste, Preferences, Quit, Redo, SelectAll, Undo,
3104 };
3105 match role {
3106 Cut => "Cut",
3107 Copy => "Copy",
3108 Paste => "Paste",
3109 SelectAll => "Select All",
3110 Undo => "Undo",
3111 Redo => "Redo",
3112 Delete => "Delete",
3113 About => "About",
3114 Quit => "Quit",
3115 Preferences => "Preferences…",
3116 Minimize => "Minimize",
3117 CloseWindow => "Close",
3118 Fullscreen => "Enter Full Screen",
3119 NewWindow => "New Window",
3120 CheckForUpdates => "Check for Updates…",
3121 }
3122}
3123
3124fn qt_role_shortcut(role: day_spec::MenuRole) -> Option<&'static str> {
3126 use day_spec::MenuRole::{
3127 About, CheckForUpdates, CloseWindow, Copy, Cut, Delete, Fullscreen, Minimize, NewWindow,
3128 Paste, Preferences, Quit, Redo, SelectAll, Undo,
3129 };
3130 Some(match role {
3131 Cut => "Ctrl+X",
3132 Copy => "Ctrl+C",
3133 Paste => "Ctrl+V",
3134 SelectAll => "Ctrl+A",
3135 Undo => "Ctrl+Z",
3136 Redo => "Ctrl+Shift+Z",
3137 Quit => "Ctrl+Q",
3138 CloseWindow => "Ctrl+W",
3139 Minimize => "Ctrl+M",
3140 Preferences => "Ctrl+,",
3141 NewWindow => "Ctrl+N",
3142 Delete | About | Fullscreen | CheckForUpdates => return None,
3143 })
3144}
3145
3146pub(crate) fn build_qt_menu(menu: *mut c_void, items: &[day_spec::MenuItem]) {
3148 for item in items {
3149 match item {
3150 day_spec::MenuItem::Separator => unsafe { ffi::day_qt_menu_add_separator(menu) },
3151 day_spec::MenuItem::Submenu { label, items, .. } => {
3152 let sub = unsafe { ffi::day_qt_menu_add_submenu(menu, cstr(label).as_ptr()) };
3153 build_qt_menu(sub, items);
3154 }
3155 day_spec::MenuItem::Action {
3156 action,
3157 label,
3158 shortcut,
3159 enabled,
3160 checked,
3161 role,
3162 icon,
3163 ..
3164 } => {
3165 if *action != 0 {
3171 let text = match role {
3172 Some(r) if label.is_empty() => qt_role_label(*r).to_string(),
3173 _ => label.clone(),
3174 };
3175 let sc = shortcut
3176 .as_ref()
3177 .map(qt_shortcut)
3178 .or_else(|| role.and_then(|r| qt_role_shortcut(r).map(str::to_string)))
3179 .unwrap_or_default();
3180 let (ic, ic_fallback) = crate::toolbar::icon_args(icon.as_ref());
3181 unsafe {
3182 ffi::day_qt_menu_add_action(
3183 menu,
3184 cstr(&text).as_ptr(),
3185 *action,
3186 cstr(&sc).as_ptr(),
3187 c_int::from(*enabled),
3188 cstr(&ic).as_ptr(),
3189 ic_fallback,
3190 checked.map_or(-1, c_int::from),
3191 );
3192 };
3193 } else if let Some(role) = role {
3194 let text = if label.is_empty() {
3195 qt_role_label(*role).to_string()
3196 } else {
3197 label.clone()
3198 };
3199 let sc = shortcut
3200 .as_ref()
3201 .map(qt_shortcut)
3202 .or_else(|| qt_role_shortcut(*role).map(str::to_string))
3203 .unwrap_or_default();
3204 unsafe {
3205 ffi::day_qt_menu_add_role(
3206 menu,
3207 cstr(&text).as_ptr(),
3208 *role as c_int,
3209 cstr(&sc).as_ptr(),
3210 );
3211 };
3212 }
3213 }
3214 }
3215 }
3216}
3217
3218fn warn_missing_renderer(kind: PieceKind) {
3223 day_spec::placeholder::report(kind, "qt");
3224}
3225
3226pub(crate) fn placeholder_handle(kind: PieceKind) -> QtHandle {
3229 QtHandle(unsafe { ffi::day_qt_label_new(cstr(&format!("⟨{kind}⟩")).as_ptr(), 1) })
3230}
3231
3232fn qt_cursor_shape(c: &Cursor) -> c_int {
3234 match c {
3235 Cursor::Default => -1,
3236 Cursor::Pointer => 13, Cursor::Text | Cursor::VerticalText => 4, Cursor::Crosshair | Cursor::Cell => 2, Cursor::Move => 9, Cursor::Grab => 17, Cursor::Grabbing => 18, Cursor::NotAllowed => 14, Cursor::Wait => 3, Cursor::Progress => 16, Cursor::Help => 15, Cursor::ContextMenu | Cursor::ZoomIn | Cursor::ZoomOut => 0, Cursor::Copy => 19, Cursor::Alias => 21, Cursor::None => 10, Cursor::NsResize => 5, Cursor::EwResize => 6, Cursor::NeswResize => 7, Cursor::NwseResize => 8, Cursor::ColResize => 12, Cursor::RowResize => 11, Cursor::Native(name) => match &**name {
3257 "UpArrowCursor" => 1,
3258 "BlankCursor" => 10,
3259 "SplitVCursor" => 11,
3260 "SplitHCursor" => 12,
3261 "WhatsThisCursor" => 15,
3262 "BusyCursor" => 16,
3263 "DragMoveCursor" => 20,
3264 _ => -1,
3265 },
3266 }
3267}
3268
3269impl Toolkit for Qt {
3270 type Handle = QtHandle;
3271
3272 fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
3273 unsafe {
3274 day_toolkit_qt_sys::day_qt_set_visible(handle.0, i32::from(visible));
3275 }
3276 }
3277
3278 #[expect(
3279 clippy::match_same_arms,
3280 reason = "one arm per capability, each documented with the Qt mechanism behind it"
3281 )]
3282 fn capability(&self, cap: Cap) -> Support {
3283 match cap {
3284 Cap::NavReorder => Support::Emulated,
3287 Cap::Appearance => {
3290 if unsafe { ffi::day_qt_appearance_settable() } != 0 {
3292 Support::Native
3293 } else {
3294 Support::Unsupported
3295 }
3296 }
3297 Cap::SearchField => Support::Native,
3298 Cap::ComboBox => Support::Native,
3299 Cap::Stepper => Support::Native,
3300 Cap::DateTimePicker => Support::Native,
3301 Cap::ColorPicker => Support::Native,
3302 Cap::PullRefresh => Support::Emulated,
3303 Cap::Pager => Support::Emulated,
3304 Cap::PullRefreshGesture => Support::Unsupported,
3305 Cap::Cursor => Support::Emulated,
3308 Cap::WindowTabbing if cfg!(target_os = "macos") => Support::Native,
3310 Cap::FontList => Support::Native,
3312 Cap::Animation => Support::Native,
3317 Cap::ImageDecode | Cap::ImageEncode => Support::Native,
3322 Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
3325 Cap::ListSections => Support::Emulated,
3329 Cap::ScrollSnap => Support::Emulated,
3333 Cap::ListViewport | Cap::ListScrollAlign | Cap::ScrollOffset => Support::Native,
3346 Cap::ListReaderScroll => Support::Native,
3350 Cap::TextRuns
3353 | Cap::TextLinks
3354 | Cap::Snapshot
3355 | Cap::NavSplit
3356 | Cap::NavRepresent
3360 | Cap::NavContentList
3363 | Cap::Dialogs
3364 | Cap::FileDialogs
3365 | Cap::FolderDialog
3367 | Cap::TextEditable
3368 | Cap::TextSelectable
3369 | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::ListReorder
3371 | Cap::ListRecycling
3374 | Cap::MultiWindow
3376 | Cap::WindowStates
3382 | Cap::WindowFullscreen
3383 | Cap::FramelessWindow
3386 | Cap::DragRegion
3388 | Cap::WindowGeometry
3390 | Cap::WindowLevel
3393 | Cap::RequestAttention
3395 | Cap::Monitors
3397 | Cap::NavTabs
3403 | Cap::AppMenu
3405 | Cap::Toolbar
3406 | Cap::ToolbarSearch
3408 | Cap::Inspector
3411 | Cap::Split => Support::Native,
3413 Cap::Focusable | Cap::KeyPhases => Support::Native,
3419 Cap::HitSlop => Support::Emulated,
3422 Cap::LabelSelection => Support::Native,
3426 Cap::Cover => Support::Emulated,
3428 Cap::Tree | Cap::TreeSections => Support::Native,
3431 Cap::BaselineAlignment => Support::Emulated,
3434 Cap::Announce => {
3437 if unsafe { ffi::day_qt_can_announce() } != 0 {
3439 Support::Native
3440 } else {
3441 Support::Unsupported
3442 }
3443 }
3444 Cap::ReduceMotion => Support::Unsupported,
3451 Cap::WindowPosition => {
3454 if unsafe { ffi::day_qt_is_wayland() } != 0 {
3456 Support::Unsupported
3457 } else {
3458 Support::Native
3459 }
3460 }
3461 Cap::AppProgress | Cap::AppBadgeCount => {
3465 if cfg!(target_os = "linux") {
3466 Support::Emulated
3467 } else {
3468 Support::Unsupported
3469 }
3470 }
3471 Cap::TransparentWindow => Support::Native,
3473 Cap::StatusItem => {
3475 if unsafe { ffi::day_qt_tray_available() } != 0 {
3477 Support::Native
3478 } else {
3479 Support::Unsupported
3480 }
3481 }
3482 _ => Support::Unsupported,
3487 }
3488 }
3489
3490 fn realize(&mut self, kind: PieceKind, props: &dyn std::any::Any, id: NodeId) -> QtHandle {
3491 unsafe {
3492 match Builtin::from_key(kind) {
3493 Some(Builtin::Inspector) => {
3494 let (visible, width, leading) =
3495 props
3496 .downcast_ref::<InspectorProps>()
3497 .map_or((false, 280.0, false), |p| {
3498 (
3499 p.visible,
3500 p.width,
3501 p.edge == day_spec::props::PaneEdge::Leading,
3502 )
3503 });
3504 let host = ffi::day_qt_inspector_new(width, c_int::from(leading));
3505 let (content_ix, panel_ix) = if leading { (1, 0) } else { (0, 1) };
3508 let content_pane = ffi::day_qt_splitter_pane(host, content_ix);
3509 let panel_pane = ffi::day_qt_splitter_pane(host, panel_ix);
3510 ffi::day_qt_splitter_on_moved(host, inspector_splitter_moved);
3511 ffi::day_qt_splitter_on_resized(host, inspector_splitter_moved);
3515 ffi::day_qt_set_visible(panel_pane, c_int::from(visible));
3516 INSPECTOR_STATE.with(|m| {
3517 m.borrow_mut().insert(
3518 host as usize,
3519 InspectorState {
3520 content_pane,
3521 panel_pane,
3522 panes: Vec::new(),
3523 width,
3524 shown: visible,
3525 },
3526 )
3527 });
3528 QtHandle(host)
3529 }
3530 Some(Builtin::Split) => {
3531 let (axis, fraction, min_pane) = props
3532 .downcast_ref::<SplitProps>()
3533 .map_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0), |p| {
3534 (p.axis, p.fraction, p.min_pane)
3535 });
3536 let vertical = axis == day_spec::props::SplitAxis::Vertical;
3537 let host = ffi::day_qt_split_new(c_int::from(vertical), min_pane);
3538 let first_pane = ffi::day_qt_splitter_pane(host, 0);
3539 let second_pane = ffi::day_qt_splitter_pane(host, 1);
3540 ffi::day_qt_splitter_on_moved(host, split_moved);
3541 ffi::day_qt_splitter_on_resized(host, split_resized);
3542 SPLIT_STATE.with(|m| {
3543 m.borrow_mut().insert(
3544 host as usize,
3545 SplitState {
3546 first_pane,
3547 second_pane,
3548 node: id,
3549 panes: Vec::new(),
3550 share: fraction.clamp(0.0, 1.0),
3551 min_pane,
3552 placed: false,
3553 suppress: false,
3554 },
3555 )
3556 });
3557 QtHandle(host)
3558 }
3559 Some(Builtin::SplitPane) => {
3560 let w = ffi::day_qt_container_new();
3561 let second = props
3562 .downcast_ref::<SplitPaneProps>()
3563 .is_some_and(|p| p.second);
3564 SPLIT_PANE_IDS.with(|m| m.borrow_mut().insert(w as usize, (id, second)));
3565 QtHandle(w)
3566 }
3567 Some(Builtin::InspectorPane) => {
3568 let w = ffi::day_qt_container_new();
3569 let panel = props
3570 .downcast_ref::<InspectorPaneProps>()
3571 .is_some_and(|p| p.panel);
3572 INSPECTOR_PANE_IDS.with(|m| m.borrow_mut().insert(w as usize, (id, panel)));
3573 QtHandle(w)
3574 }
3575 Some(Builtin::Container) => {
3576 let w = ffi::day_qt_container_new();
3577 if let Some(p) = props.downcast_ref::<ContainerProps>() {
3578 apply_surface(w, p, true);
3579 if *p != ContainerProps::default() {
3580 SURFACES.with(|t| t.insert(w as usize, p.clone()));
3581 }
3582 }
3583 passive(w)
3584 }
3585 Some(Builtin::Nav) => {
3586 let nav_props = props.downcast_ref::<NavProps>();
3587 if nav_props.is_some_and(|p| p.presentation.rows_are_chrome()) {
3596 let w = ffi::day_qt_tabs_new(id.0, nav_suite_changed);
3597 NAV_SUITES.with(|m| {
3598 m.borrow_mut().insert(
3599 w as usize,
3600 NavSuite {
3601 host: id,
3602 menu_node: NodeId(0),
3603 pages: Vec::new(),
3604 titles: Vec::new(),
3605 icons: Vec::new(),
3606 keys: Vec::new(),
3607 },
3608 )
3609 });
3610 if let Some(config) = nav_props.and_then(|p| p.documents.as_ref()) {
3611 ffi::day_qt_tabs_documents(
3612 w,
3613 id.0,
3614 cstr(&config.new_label).as_ptr(),
3615 cstr(&config.close_label).as_ptr(),
3616 c_int::from(config.can_add),
3617 document_tab_event,
3618 );
3619 }
3620 return QtHandle(w);
3621 }
3622 let is_split = nav_props.is_none_or(|p| p.presentation.is_split());
3623 let list_width = nav_props.and_then(|p| p.list_width);
3627 let list_visible = nav_props.is_none_or(|p| p.list_visible);
3628 let host = ffi::day_qt_splitter_new(
3629 list_width.unwrap_or(0.0),
3630 day_spec::NAV_SIDEBAR_MIN_W,
3631 day_spec::NAV_LIST_MIN_W,
3632 );
3633 let sidebar_pane = ffi::day_qt_splitter_pane(host, 0);
3634 let list_pane = ffi::day_qt_splitter_pane(host, 1);
3635 let mut detail_pane = ffi::day_qt_splitter_pane(host, 2);
3636 if list_width.is_some() && !list_visible {
3639 ffi::day_qt_set_visible(list_pane, 0);
3640 }
3641 ffi::day_qt_splitter_on_moved(host, nav_splitter_moved);
3642 ffi::day_qt_splitter_on_resized(host, nav_splitter_moved);
3643 let pages = ffi::day_qt_nav_header_install(host, id.0, nav_back_clicked);
3649 if !pages.is_null() {
3650 detail_pane = pages;
3651 }
3652 let titles = vec![nav_props.map_or_default(|p| p.title.clone())];
3656 if !is_split {
3657 ffi::day_qt_set_visible(sidebar_pane, 0);
3659 }
3660 NAV_STATE.with(|m| {
3661 m.borrow_mut().insert(
3662 host as usize,
3663 NavState {
3664 sidebar_pane,
3665 detail_pane,
3666 pages: Vec::new(),
3667 sidebar_page: None,
3668 split: is_split,
3669 sidebar_shown: is_split,
3670 list_pane,
3671 list_width,
3672 list_page: None,
3673 list_shown: list_visible,
3674 list_positioned: list_visible,
3677 titles,
3678 },
3679 )
3680 });
3681 QtHandle(host)
3682 }
3683 Some(Builtin::NavPage) => {
3684 let page = QtHandle(ffi::day_qt_container_new());
3685 NAV_PAGE_IDS.with(|m| m.borrow_mut().insert(page.0 as usize, id));
3686 if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
3687 PAGE_PANE.with(|m| m.borrow_mut().insert(page.0 as usize, p.pane));
3688 }
3689 page
3690 }
3691 Some(Builtin::Cover) => {
3694 let cover = QtHandle(ffi::day_qt_container_new());
3695 ffi::day_qt_set_visible(cover.0, 0);
3696 COVER_IDS.with(|m| m.borrow_mut().insert(cover.0 as usize, id));
3697 let p = props_of::<CoverProps>(kind, "qt", props);
3698 if p.is_some_and(|p| p.half) {
3699 COVER_HALF.with(|s| s.borrow_mut().insert(cover.0 as usize));
3700 }
3701 if p.is_some_and(|p| (p.sheet || p.large) && !p.half) {
3702 ffi::day_qt_cover_escape(cover.0, id.0, on_cover_escape);
3703 }
3704 cover
3705 }
3706 Some(Builtin::NavMenu) => {
3707 let Some(p) = props_of::<NavMenuProps>(kind, "qt", props) else {
3708 return placeholder_handle(kind);
3709 };
3710 let w = ffi::day_qt_navlist_new(id.0, nav_menu_changed);
3711 NAV_SUITE_ROWS.with(|m| {
3714 m.borrow_mut().insert(
3715 w as usize,
3716 (
3717 id,
3718 p.items.clone(),
3719 p.icons.clone(),
3720 p.document_keys.clone(),
3721 ),
3722 )
3723 });
3724 let rows = NavRows {
3730 items: p.items.clone(),
3731 icons: p.icons.clone(),
3732 tints: p.tints.clone(),
3733 badge_icons: p.badge_icons.clone(),
3734 badge_tints: p.badge_tints.clone(),
3735 badges: p.badges.clone(),
3736 };
3737 let headings = apply_nav_rows(w, &rows, None, &p.sections);
3738 navlist_apply_row_menus(w, &p.menus);
3739 ffi::day_qt_navlist_set_selected(w, p.selected.map_or(-1, |i| i as c_int));
3740 NAV_MENU_ROWS
3741 .with(|m| m.borrow_mut().insert(w as usize, (p.items.len(), headings)));
3742 QtHandle(w)
3743 }
3744 Some(Builtin::Scroll) => {
3745 let p = props
3746 .downcast_ref::<day_spec::props::ScrollProps>()
3747 .cloned()
3748 .unwrap_or_default();
3749 let sa = ffi::day_qt_scroll_new(c_int::from(p.horizontal));
3750 let (snap, interval) = match p.snap {
3756 day_spec::props::ScrollSnap::None => (0, 0.0),
3757 day_spec::props::ScrollSnap::Page => (1, 0.0),
3758 day_spec::props::ScrollSnap::Interval(points) => (2, points),
3759 };
3760 let hidden = p.indicators == day_spec::props::ScrollIndicators::Hidden;
3761 ffi::day_qt_scroll_configure(sa, c_int::from(hidden), snap, interval);
3762 if p.track_offset {
3763 ffi::day_qt_scroll_track_offset(sa, id.0, on_scroll_offset);
3764 }
3765 QtHandle(sa)
3766 }
3767 Some(Builtin::Label) => {
3768 let Some(p) = props_of::<LabelProps>(kind, "qt", props) else {
3769 return placeholder_handle(kind);
3770 };
3771 let w = ffi::day_qt_label_new(cstr(&p.text).as_ptr(), c_int::from(p.wraps));
3772 ffi::day_qt_label_set_align(w, label_align(p.align));
3773 apply_label_font(w, p.font);
3774 apply_custom_family(w, p.font);
3775 if p.font.monospace {
3776 ffi::day_qt_label_set_monospace(w);
3777 }
3778 if p.color.is_some() {
3779 apply_label_color(w, p.color);
3780 }
3781 remember_label_pt(w, p.font);
3782 apply_paragraph(w, &p.paragraph());
3783 apply_label_runs(w, &p.text, &p.runs);
3784 if p.reports_selection {
3785 ffi::day_qt_label_on_selection(w, id.0, on_text_selected);
3786 }
3787 ffi::day_qt_label_on_link(w, id.0, on_link);
3790 passive(w)
3791 }
3792 Some(Builtin::Button) => {
3793 let Some(p) = props_of::<ButtonProps>(kind, "qt", props) else {
3794 return placeholder_handle(kind);
3795 };
3796 let w = ffi::day_qt_button_new(cstr(&p.title).as_ptr(), id.0, on_press);
3797 ffi::day_qt_set_enabled(w, c_int::from(p.enabled));
3798 ffi::day_qt_button_set_selected(w, c_int::from(p.selected));
3799 apply_button_style_ink(w, p.style);
3800 if p.icon.is_some() {
3801 apply_button_content(w, &p.title, p.icon.as_ref(), p.icon_only);
3802 }
3803 ffi::day_qt_enable_focus(w, id.0, on_focus);
3804 QtHandle(w)
3805 }
3806 Some(Builtin::Toggle) => {
3807 let Some(p) = props_of::<ToggleProps>(kind, "qt", props) else {
3808 return placeholder_handle(kind);
3809 };
3810 let w = ffi::day_qt_checkbox_new(c_int::from(p.on), id.0, on_toggle);
3811 ffi::day_qt_set_enabled(w, c_int::from(p.enabled));
3812 ffi::day_qt_enable_focus(w, id.0, on_focus);
3813 QtHandle(w)
3814 }
3815 Some(Builtin::Slider) => {
3816 let Some(p) = props_of::<SliderProps>(kind, "qt", props) else {
3817 return placeholder_handle(kind);
3818 };
3819 RANGES.with(|r| r.insert(id.0 as usize, (p.min, p.max)));
3820 let w = ffi::day_qt_slider_new(
3821 slider_ticks(p.value, p.min, p.max),
3822 id.0,
3823 on_slider,
3824 );
3825 RANGES_BY_PTR.with(|r| r.insert(w as usize, (p.min, p.max)));
3826 ffi::day_qt_enable_focus(w, id.0, on_focus);
3827 QtHandle(w)
3828 }
3829 Some(Builtin::Picker) => picker::realize_any(self, props, id),
3830 Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
3831 Some(Builtin::TextField) => {
3832 let Some(p) = props_of::<TextFieldProps>(kind, "qt", props) else {
3833 return placeholder_handle(kind);
3834 };
3835 let w = ffi::day_qt_lineedit_new(
3836 cstr(&p.text).as_ptr(),
3837 cstr(&p.placeholder).as_ptr(),
3838 id.0,
3839 on_text,
3840 );
3841 ffi::day_qt_enable_focus(w, id.0, on_focus);
3842 ffi::day_qt_lineedit_enable_field_keys(w, id.0, on_field_key);
3843 QtHandle(w)
3844 }
3845 Some(Builtin::Divider) => {
3846 let vertical = day_spec::props_of::<DividerProps>(kind, "qt", props)
3847 .is_some_and(|p| p.vertical);
3848 passive(ffi::day_qt_separator_new(c_int::from(vertical)))
3849 }
3850 Some(Builtin::Progress) => {
3851 let Some(p) = props_of::<ProgressProps>(kind, "qt", props) else {
3852 return placeholder_handle(kind);
3853 };
3854 if p.value.is_none() {
3855 return crate::controls::spinner::make(self, p, id);
3856 }
3857 match p.value {
3858 Some(v) => QtHandle(ffi::day_qt_progress_new(1, progress_ticks(v))),
3859 None => QtHandle(ffi::day_qt_progress_new(0, 0)),
3860 }
3861 }
3862 Some(Builtin::Canvas) => {
3863 let w = ffi::day_qt_canvas_new();
3864 ffi::day_qt_enable_keys(w, id.0, on_key);
3868 ffi::day_qt_enable_focus(w, id.0, on_focus);
3869 passive(w)
3870 }
3871 Some(Builtin::Image) => {
3872 let Some(p) = props_of::<ImageProps>(kind, "qt", props) else {
3873 return placeholder_handle(kind);
3874 };
3875 let mode = match p.content_mode {
3877 ContentMode::Fit => 0,
3878 ContentMode::Fill => 1,
3879 ContentMode::Stretch => 2,
3880 };
3881 let image = match &p.source {
3882 day_spec::ImageSource::Named(named) => {
3885 let res_path = format!(":/day/images/{named}");
3887 let path = if let Some(svg) =
3888 day_spec::resource::resolve_vector_svg(named)
3889 {
3890 svg.to_string_lossy().into_owned()
3891 } else if ffi::day_qt_resource_exists(cstr(&res_path).as_ptr()) != 0 {
3892 res_path
3893 } else {
3894 icon_file_path(named)
3898 };
3899 let tint = image_tint(p.tint.map(day_spec::Ink::resolved), p.template);
3904 passive(ffi::day_qt_image_new(
3905 cstr(&path).as_ptr(),
3906 mode,
3907 cstr(&tint).as_ptr(),
3908 ))
3909 }
3910 day_spec::ImageSource::Bytes(bytes) => {
3916 let tint = image_tint(p.tint.map(day_spec::Ink::resolved), p.template);
3917 passive(ffi::day_qt_image_new_bytes(
3918 bytes.as_ptr(),
3919 bytes.len() as c_int,
3920 mode,
3921 cstr(&tint).as_ptr(),
3922 ))
3923 }
3924 day_spec::ImageSource::Decoded(id) => {
3926 let tint = image_tint(p.tint.map(day_spec::Ink::resolved), false);
3927 passive(ffi::day_qt_image_new_bitmap(
3928 id.0,
3929 mode,
3930 cstr(&tint).as_ptr(),
3931 ))
3932 }
3933 };
3934 remember_inks(image.0, |i| i.image_tint = dynamic(p.tint));
3935 image
3936 }
3937 Some(Builtin::Tree) => {
3938 let Some(p) = props_of::<TreeProps>(kind, "qt", props) else {
3939 return placeholder_handle(kind);
3940 };
3941 QtHandle(tree::new(id, p))
3942 }
3943 Some(Builtin::List) => {
3944 let Some(p) = props_of::<ListProps>(kind, "qt", props) else {
3945 return placeholder_handle(kind);
3946 };
3947 let (row_height, automatic) = match p.row_height {
3948 RowHeight::Uniform(h) => (h, false),
3949 RowHeight::Automatic => (44.0, true),
3950 };
3951 let separators = match p.separators {
3957 None => -1,
3958 Some(false) => 0,
3959 Some(true) => 1,
3960 };
3961 let host = ffi::day_qt_list_new(
3962 id.0,
3963 row_height as c_int,
3964 c_int::from(p.selectable),
3965 c_int::from(p.multi_select),
3966 c_int::from(p.reorderable),
3967 separators,
3968 on_list_selection,
3969 on_list_activate,
3970 on_list_can_move,
3971 on_list_move,
3972 on_list_window,
3973 );
3974 ffi::day_qt_list_on_viewport_resized(host, on_list_viewport_resized);
3977 ffi::day_qt_list_on_reader_scroll(host, on_list_reader_scroll);
3979 if automatic || p.sections {
3982 ffi::day_qt_list_set_automatic(host);
3983 }
3984 LIST_STATE.with(|m| {
3985 m.borrow_mut().insert(
3986 host as usize,
3987 ListEntry {
3988 host,
3989 row_height,
3990 automatic,
3991 source: Rc::new(RefCell::new(None)),
3992 pool: CellPool::default(),
3993 heights: HashMap::new(),
3994 height_sum: 0.0,
3995 estimate: row_height as c_int,
3996 rebind_all: false,
3997 frame_height: -1,
3998 fill_pending: false,
3999 last_width: -1,
4000 cell_width: -1,
4001 node: id.0,
4002 multi: p.multi_select,
4003 pin: None,
4004 pin_row: None,
4005 headers_for: None,
4006 supplements_for: None,
4007 supplement_heights: HashMap::new(),
4008 pending: None,
4009 },
4010 )
4011 });
4012 LIST_BY_NODE.with(|m| m.borrow_mut().insert(id.0, host as usize));
4013 QtHandle(host)
4014 }
4015 Some(Builtin::ListCell | Builtin::ListItem) | None => {
4018 if let Some(make) = self.registry.get(kind).map(|r| r.make) {
4019 return make(self, props, id);
4020 }
4021 warn_missing_renderer(kind);
4022 placeholder_handle(kind)
4023 }
4024 }
4025 }
4026 }
4027
4028 fn update(
4029 &mut self,
4030 h: &QtHandle,
4031 kind: PieceKind,
4032 patch: &dyn std::any::Any,
4033 anim: Option<&AnimSpec>,
4034 ) {
4035 if let Some(patch) = patch.downcast_ref::<TreePatch>() {
4036 tree::patch(h.0 as usize, patch);
4037 return;
4038 }
4039 unsafe {
4040 match kind {
4041 kinds::IMAGE => {
4042 if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
4043 match p {
4044 day_spec::props::ImagePatch::Tint(c) => {
4045 let tint = image_tint((*c).map(day_spec::Ink::resolved), false);
4049 ffi::day_qt_image_set_tint(h.0, cstr(&tint).as_ptr());
4050 remember_inks(h.0, |i| i.image_tint = dynamic(*c));
4051 }
4052 day_spec::props::ImagePatch::Source(source) => match source {
4056 day_spec::ImageSource::Named(named) => {
4057 let res_path = format!(":/day/images/{named}");
4058 let path = if let Some(svg) =
4059 day_spec::resource::resolve_vector_svg(named)
4060 {
4061 svg.to_string_lossy().into_owned()
4062 } else if ffi::day_qt_resource_exists(cstr(&res_path).as_ptr())
4063 != 0
4064 {
4065 res_path
4066 } else {
4067 icon_file_path(named)
4068 };
4069 ffi::day_qt_image_set_path(h.0, cstr(&path).as_ptr());
4072 }
4073 day_spec::ImageSource::Bytes(bytes) => {
4074 ffi::day_qt_image_set_bytes(
4075 h.0,
4076 bytes.as_ptr(),
4077 bytes.len() as c_int,
4078 );
4079 }
4080 day_spec::ImageSource::Decoded(id) => {
4081 ffi::day_qt_image_set_bitmap(h.0, id.0);
4082 }
4083 },
4084 }
4085 }
4086 }
4087 kinds::CONTAINER => {
4088 let key = h.0 as usize;
4089 match patch.downcast_ref::<ContainerPatch>() {
4090 Some(ContainerPatch::Fill(fill)) => {
4091 let mut p = SURFACES.with(|t| t.take(key)).unwrap_or_default();
4092 p.fill.clone_from(fill);
4093 match solid_fill(fill.as_ref()).filter(|_| p.role.is_none()) {
4094 Some(bg) => with_qt_anim(anim, |anim| {
4100 ffi::day_qt_widget_set_bg(h.0, bg.r, bg.g, bg.b, bg.a, anim);
4101 }),
4102 None => apply_surface(h.0, &p, false),
4104 }
4105 SURFACES.with(|t| t.insert(key, p));
4106 }
4107 Some(ContainerPatch::Surface(next)) => {
4111 let mut p = (**next).clone();
4112 p.role = SURFACES.with(|t| t.get(key)).and_then(|old| old.role);
4113 apply_surface(h.0, &p, false);
4114 SURFACES.with(|t| t.insert(key, p));
4115 }
4116 None => {}
4117 }
4118 }
4119 kinds::NAV_MENU => {
4120 if let Some(NavMenuPatch::Items {
4121 document_keys,
4122 items,
4123 icons,
4124 tints,
4125 menus,
4126 badges,
4127 badge_icons,
4128 badge_tints,
4129 sections,
4130 selected,
4131 rows_changed,
4132 ..
4134 }) = patch.downcast_ref::<NavMenuPatch>()
4135 {
4136 NAV_SUITE_ROWS.with(|m| {
4137 if let Some(row) = m.borrow_mut().get_mut(&(h.0 as usize)) {
4138 row.1.clone_from(items);
4139 row.2.clone_from(icons);
4140 row.3 = document_keys.to_vec();
4141 }
4142 });
4143 let host = ffi::day_qt_enclosing_tabs(h.0);
4144 if !host.is_null() {
4145 NAV_SUITES.with(|m| {
4146 if let Some(s) = m.borrow_mut().get_mut(&(host as usize)) {
4147 s.titles.clone_from(items);
4148 s.icons.clone_from(icons);
4149 s.keys = document_keys.to_vec();
4150 }
4151 });
4152 suite_apply_rows(host);
4153 }
4154 let rows = NavRows {
4158 items: items.clone(),
4159 icons: icons.clone(),
4160 tints: tints.clone(),
4161 badge_icons: badge_icons.clone(),
4162 badge_tints: badge_tints.clone(),
4163 badges: badges.clone(),
4164 };
4165 if let Some(changed) = rows_changed {
4166 apply_nav_rows(h.0, &rows, Some(changed), sections);
4167 return;
4168 }
4169 let headings = apply_nav_rows(h.0, &rows, None, sections);
4170 navlist_apply_row_menus(h.0, menus);
4171 ffi::day_qt_navlist_set_selected(h.0, selected.map_or(-1, |i| i as c_int));
4172 NAV_MENU_ROWS
4173 .with(|m| m.borrow_mut().insert(h.0 as usize, (items.len(), headings)));
4174 } else if let Some(NavMenuPatch::Selected(sel)) =
4175 patch.downcast_ref::<NavMenuPatch>()
4176 {
4177 ffi::day_qt_navlist_set_selected(h.0, sel.map_or(-1, |i| i as c_int));
4178 }
4179 }
4180 kinds::COVER => {
4184 if let Some(p) = patch.downcast_ref::<CoverPatch>() {
4185 let node = COVER_IDS
4186 .with(|m| m.borrow().get(&(h.0 as usize)).copied())
4187 .unwrap_or(day_spec::WINDOW_NODE);
4188 match p {
4189 CoverPatch::Present { background, .. } => {
4190 if let Some(bg) = background.map(day_spec::Ink::resolved) {
4191 ffi::day_qt_widget_set_bg(
4192 h.0,
4193 bg.r,
4194 bg.g,
4195 bg.b,
4196 bg.a,
4197 std::ptr::null(),
4198 );
4199 }
4200 remember_inks(h.0, |i| i.cover = dynamic(*background));
4201 ffi::day_qt_add_child(self.window, h.0);
4202 let opaque = background.is_none_or(|bg| bg.resolved().a > 0.0);
4204 ffi::day_qt_cover_top(h.0, c_int::from(opaque));
4205 let (y, size) =
4206 cover_frame(h.0, LAST_WINDOW_SIZE.with(std::cell::Cell::get));
4207 ffi::day_qt_set_geometry(
4208 h.0,
4209 0,
4210 y as c_int,
4211 size.width as c_int,
4212 size.height as c_int,
4213 );
4214 ffi::day_qt_set_visible(h.0, 1);
4215 COVERS.with(|c| c.borrow_mut().push((h.0, node)));
4216 emit(node, Event::FrameChanged(size));
4217 }
4218 CoverPatch::DismissDisabled(_) => {}
4219 CoverPatch::Dismiss => {
4220 ffi::day_qt_set_visible(h.0, 0);
4221 COVERS.with(|c| c.borrow_mut().retain(|(w, _)| *w != h.0));
4222 emit(node, Event::CoverHidden);
4223 }
4224 }
4225 }
4226 }
4227 kinds::SPLIT => {
4228 if let Some(p) = patch.downcast_ref::<SplitPatch>() {
4229 let apply = SPLIT_STATE.with(|m| {
4230 let mut m = m.borrow_mut();
4231 let state = m.get_mut(&(h.0 as usize))?;
4232 match p {
4233 SplitPatch::Fraction(f) => state.share = f.clamp(0.0, 1.0),
4234 SplitPatch::Axis(_) => {}
4235 }
4236 state.suppress = true;
4237 Some((state.placed, state.share, state.min_pane))
4238 });
4239 if let Some((placed, share, min_pane)) = apply {
4240 if let SplitPatch::Axis(axis) = p {
4241 let vertical = *axis == day_spec::props::SplitAxis::Vertical;
4242 ffi::day_qt_split_set_orientation(
4243 h.0,
4244 c_int::from(vertical),
4245 min_pane,
4246 );
4247 }
4248 if placed {
4249 ffi::day_qt_split_set_fraction(h.0, share);
4250 }
4251 SPLIT_STATE.with(|m| {
4252 if let Some(state) = m.borrow_mut().get_mut(&(h.0 as usize)) {
4253 state.suppress = false;
4254 }
4255 });
4256 split_sync_panes(h.0);
4257 }
4258 }
4259 }
4260 kinds::INSPECTOR => {
4261 if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>()
4262 {
4263 INSPECTOR_STATE.with(|m| {
4264 if let Some(state) = m.borrow_mut().get_mut(&(h.0 as usize)) {
4265 state.shown = *v;
4266 ffi::day_qt_set_visible(state.panel_pane, c_int::from(*v));
4267 }
4268 });
4269 let host_addr = h.0 as usize;
4272 <Qt as Platform>::post(Box::new(move || {
4273 inspector_sync_panes(host_addr as *mut std::os::raw::c_void);
4274 }));
4275 }
4276 }
4277 kinds::NAV => {
4278 if let Some(p) = patch.downcast_ref::<day_spec::props::DocumentTabsPatch>() {
4279 ffi::day_qt_tabs_chrome(h.0, c_int::from(p.native));
4280 nav_suite_sync(h.0);
4281 return;
4282 }
4283 if let Some(NavPatch::Reorder(order)) = patch.downcast_ref::<NavPatch>() {
4284 NAV_SUITES.with(|m| {
4285 let mut m = m.borrow_mut();
4286 if let Some(s) = m.get_mut(&(h.0 as usize)) {
4287 let old = s.pages.clone();
4288 s.pages =
4289 order.iter().filter_map(|i| old.get(*i).copied()).collect();
4290 for (i, (page, _)) in s.pages.iter().enumerate() {
4291 ffi::day_qt_tabs_move_page(h.0, page.0, i as c_int);
4292 }
4293 }
4294 });
4295 suite_apply_rows(h.0);
4296 return;
4297 }
4298 if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
4299 let beside =
4305 next.is_split() || *next == day_spec::props::NavPresentation::Rail;
4306 nav_present(h.0, beside);
4307 return;
4308 }
4309 if let Some(NavPatch::Select(i)) = patch.downcast_ref::<NavPatch>()
4317 && NAV_SUITES.with(|m| m.borrow().contains_key(&(h.0 as usize)))
4318 {
4319 ffi::day_qt_tabs_set_current(h.0, *i as c_int);
4320 nav_suite_sync(h.0);
4321 return;
4322 }
4323 if let Some(p) = patch.downcast_ref::<NavPatch>() {
4324 let mut list_apply: Option<(*mut c_void, bool, Option<f64>)> = None;
4328 NAV_STATE.with(|m| {
4329 let mut m = m.borrow_mut();
4330 let Some(state) = m.get_mut(&(h.0 as usize)) else {
4331 return;
4332 };
4333 let split_now = state.split;
4337 let detail: Vec<(QtHandle, NodeId)> = state
4338 .pages
4339 .iter()
4340 .filter(|(p, _)| {
4341 !(split_now && is_sidebar_page(p.0) || is_list_page(p.0))
4342 })
4343 .copied()
4344 .collect();
4345 let detail = &detail[..];
4346 match p {
4347 NavPatch::Pushed { title, .. } => {
4348 let last = detail.len().saturating_sub(1);
4349 for (i, (page, _)) in detail.iter().enumerate() {
4350 ffi::day_qt_set_visible(page.0, (i == last).into());
4351 }
4352 state.titles.push(title.clone());
4353 }
4354 NavPatch::Popped => {
4355 let n = detail.len();
4356 if let Some((top, _)) = detail.last() {
4357 ffi::day_qt_set_visible(top.0, 0);
4358 }
4359 if n >= 2 {
4360 ffi::day_qt_set_visible(detail[n - 2].0.0, 1);
4361 }
4362 if state.titles.len() > 1 {
4363 state.titles.pop();
4364 }
4365 }
4366 NavPatch::Title(t) => {
4367 if let Some(last) = state.titles.last_mut() {
4368 last.clone_from(t);
4369 }
4370 }
4371 #[expect(
4374 clippy::match_same_arms,
4375 reason = "each group of no-op patches keeps its own arm and the comment saying why"
4376 )]
4377 NavPatch::GuardTop(_) | NavPatch::Reorder(_) => {}
4378 #[expect(
4380 clippy::match_same_arms,
4381 reason = "each group of no-op patches keeps its own arm and the comment saying why"
4382 )]
4383 NavPatch::Presentation(_) => {}
4384 NavPatch::Select(i) => {
4387 for (n, (page, _)) in detail.iter().enumerate() {
4393 ffi::day_qt_set_visible(page.0, c_int::from(n == *i));
4394 }
4395 }
4396 NavPatch::ListVisible(v) => {
4401 state.list_shown = *v;
4402 if state.list_width.is_some() {
4403 let place = if *v && !state.list_positioned {
4407 state.list_positioned = true;
4408 state.list_width
4409 } else {
4410 None
4411 };
4412 list_apply = Some((state.list_pane, *v, place));
4413 }
4414 }
4415 NavPatch::ListInStack(_) => {}
4419 }
4420 });
4421 if let Some((pane, shown, place)) = list_apply {
4422 ffi::day_qt_set_visible(pane, c_int::from(shown));
4423 if let Some(w) = place {
4424 ffi::day_qt_splitter_set_pane_width(h.0, 1, w);
4425 }
4426 }
4427 let host = h.0 as usize;
4433 <Qt as Platform>::post(Box::new(move || {
4434 nav_sync_header(host as *mut std::os::raw::c_void);
4435 }));
4436 }
4437 }
4438 kinds::LABEL => {
4439 if let Some(p) = patch.downcast_ref::<LabelPatch>() {
4440 match p {
4441 LabelPatch::Paragraph(p) => apply_paragraph(h.0, p),
4442 LabelPatch::Text(t) => {
4443 ffi::day_qt_label_set_text(h.0, cstr(t).as_ptr());
4444 remember_inks(h.0, |i| i.label_runs = None);
4445 }
4446 LabelPatch::Font(f) => {
4447 apply_label_font(h.0, *f);
4448 apply_custom_family(h.0, *f);
4449 remember_label_pt(h.0, *f);
4450 }
4451 LabelPatch::Runs(text, runs) => apply_label_runs(h.0, text, runs),
4452 LabelPatch::Color(c) => apply_label_color(h.0, *c),
4453 }
4454 }
4455 }
4456 kinds::BUTTON => {
4457 if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
4458 match p {
4459 ButtonPatch::Content(c) => {
4460 apply_button_content(h.0, &c.title, c.icon.as_ref(), c.icon_only);
4461 }
4462 ButtonPatch::Title(t) => {
4463 ffi::day_qt_button_set_title(h.0, cstr(t).as_ptr());
4464 }
4465 ButtonPatch::Enabled(e) => {
4466 ffi::day_qt_set_enabled(h.0, c_int::from(*e));
4467 }
4468 ButtonPatch::Selected(on) => {
4469 ffi::day_qt_button_set_selected(h.0, c_int::from(*on));
4470 }
4471 ButtonPatch::Style(s) => apply_button_style_ink(h.0, *s),
4472 }
4473 }
4474 }
4475 kinds::TOGGLE => {
4476 if let Some(p) = patch.downcast_ref::<TogglePatch>() {
4477 match p {
4478 TogglePatch::On(on) => ffi::day_qt_checkbox_set(h.0, c_int::from(*on)),
4479 TogglePatch::Enabled(e) => {
4480 ffi::day_qt_set_enabled(h.0, c_int::from(*e));
4481 }
4482 }
4483 }
4484 }
4485 kinds::SLIDER => {
4486 if let Some(p) = patch.downcast_ref::<SliderPatch>() {
4487 match p {
4488 SliderPatch::Value(v) => {
4489 let (min, max) = RANGES_BY_PTR
4490 .with(|r| r.get(h.0 as usize))
4491 .unwrap_or((0.0, 1.0));
4492 ffi::day_qt_slider_set(h.0, slider_ticks(*v, min, max));
4493 }
4494 SliderPatch::Enabled(e) => {
4495 ffi::day_qt_set_enabled(h.0, c_int::from(*e));
4496 }
4497 }
4498 }
4499 }
4500 kinds::PROGRESS => {
4501 if let Some(p @ ProgressPatch::Animating(_)) =
4502 patch.downcast_ref::<ProgressPatch>()
4503 {
4504 crate::controls::spinner::update(self, h, p);
4505 return;
4506 }
4507
4508 if let Some(ProgressPatch::Value(Some(v))) =
4509 patch.downcast_ref::<ProgressPatch>()
4510 {
4511 ffi::day_qt_progress_set(h.0, progress_ticks(*v));
4512 }
4513 }
4514 kinds::PICKER => picker::update_any(self, *h, patch),
4515 kinds::TEXT_AREA => textarea::update_any(self, *h, patch),
4516 kinds::TEXT_FIELD => {
4517 if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
4518 match p {
4519 TextFieldPatch::Text { text, from_native } => {
4520 if !*from_native {
4521 ffi::day_qt_lineedit_set_text(h.0, cstr(text).as_ptr());
4522 }
4523 }
4524 TextFieldPatch::Placeholder(t) => {
4525 ffi::day_qt_lineedit_set_placeholder(h.0, cstr(t).as_ptr());
4526 }
4527 TextFieldPatch::Enabled(e) => {
4528 ffi::day_qt_set_enabled(h.0, c_int::from(*e));
4529 }
4530 TextFieldPatch::Select(sel) => {
4531 let at = |n: usize| n.min(c_int::MAX as usize) as c_int;
4532 ffi::day_qt_lineedit_select(h.0, at(sel.start), at(sel.end));
4533 }
4534 }
4535 }
4536 }
4537 kinds::LIST => match patch.downcast_ref::<ListPatch>() {
4538 Some(ListPatch::Reload) => queue_rows(h.0 as usize, RowWork::Reload),
4539 Some(ListPatch::Splice(deltas)) => {
4541 queue_rows(h.0 as usize, RowWork::Splice(deltas.clone()));
4542 }
4543 Some(ListPatch::ScrollToEnd) => schedule_list_scroll_end(h.0 as usize),
4544 Some(ListPatch::ScrollToRow(row)) => {
4545 schedule_list_scroll_row(h.0 as usize, *row);
4546 }
4547 Some(ListPatch::Selected(rows)) => {
4548 let rows: Vec<c_int> = rows.iter().map(|r| *r as c_int).collect();
4551 ffi::day_qt_list_set_selected(h.0, rows.as_ptr(), rows.len() as c_int);
4552 }
4553 Some(ListPatch::RowSizeInvalidated { cell, height }) => {
4554 schedule_list_row_height(h.0 as usize, *cell, *height);
4555 }
4556 Some(ListPatch::Editing(_)) | None => {}
4558 },
4559 _ => {
4560 if let Some(update) = self.registry.get(kind).map(|r| r.update) {
4561 update(self, h, patch);
4562 }
4563 }
4564 }
4565 }
4566 }
4567
4568 fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
4570 let f = self.registry.get(kind).and_then(|r| r.release);
4573 if let Some(f) = f {
4574 f(self, h);
4575 }
4576 }
4577 fn release(&mut self, h: QtHandle) {
4578 let toolbars = &mut self.toolbars;
4582 self.secondary.retain(|w| {
4583 if w.content == h.0 {
4584 #[cfg(target_os = "macos")]
4585 day_platform_macos::window_tabs::unregister(w.id);
4586 toolbars.remove(&(w.win as usize));
4587 unsafe { ffi::day_qt_window_destroy(w.win) };
4588 false
4589 } else {
4590 true
4591 }
4592 });
4593 let key = h.0 as usize;
4594 tree::release(key);
4595 if let Some(entry) = LIST_STATE.with(|m| m.borrow_mut().remove(&key)) {
4596 LIST_BY_NODE.with(|m| {
4597 m.borrow_mut().remove(&entry.node);
4598 });
4599 let source = entry.source.borrow().clone();
4602 if let (Some(pin), Some(source)) = (entry.pin, source) {
4603 (source.release)(pin as *mut c_void);
4604 }
4605 }
4606 NAV_STATE.with(|m| {
4610 m.borrow_mut().remove(&key);
4611 });
4612 NAV_PAGE_IDS.with(|m| {
4613 m.borrow_mut().remove(&key);
4614 });
4615 NAV_MENU_ROWS.with(|m| {
4616 m.borrow_mut().remove(&key);
4617 });
4618 SPLIT_STATE.with(|m| {
4619 m.borrow_mut().remove(&key);
4620 });
4621 SPLIT_PANE_IDS.with(|m| {
4622 m.borrow_mut().remove(&key);
4623 });
4624 INSPECTOR_STATE.with(|m| {
4626 m.borrow_mut().remove(&key);
4627 });
4628 INSPECTOR_PANE_IDS.with(|m| {
4629 m.borrow_mut().remove(&key);
4630 });
4631 NAV_SUITES.with(|m| {
4635 m.borrow_mut().remove(&key);
4636 });
4637 NAV_SUITE_ROWS.with(|m| {
4638 m.borrow_mut().remove(&key);
4639 });
4640 NAV_SUITE_PAGES.with(|m| {
4641 m.borrow_mut().remove(&key);
4642 });
4643 GESTURES.with(|g| {
4644 g.borrow_mut().retain(|(ptr, _)| *ptr != key);
4645 });
4646 COVERS.with(|c| c.borrow_mut().retain(|(w, _)| *w != h.0));
4650 COVER_HALF.with(|s| s.borrow_mut().remove(&(h.0 as usize)));
4651 COVER_IDS.with(|m| {
4652 m.borrow_mut().remove(&key);
4653 });
4654 day_spec::sidetable::sweep(key);
4659 unsafe {
4660 ffi::day_qt_remove_child(h.0);
4661 ffi::day_qt_delete(h.0);
4662 }
4663 }
4664
4665 fn insert(&mut self, parent: &QtHandle, child: &QtHandle, index: usize) {
4666 if COVER_IDS.with(|m| m.borrow().contains_key(&(child.0 as usize))) {
4673 unsafe {
4674 ffi::day_qt_add_child(content_of(parent), child.0);
4675 ffi::day_qt_set_visible(child.0, 0);
4676 }
4677 return;
4678 }
4679 let suite_handled = NAV_SUITES.with(|m| {
4685 let mut m = m.borrow_mut();
4686 let Some(suite) = m.get_mut(&(parent.0 as usize)) else {
4687 return false;
4688 };
4689 unsafe {
4690 if index == 0 {
4691 ffi::day_qt_tabs_park(parent.0, child.0);
4692 } else {
4693 ffi::day_qt_tabs_add_page(
4694 parent.0,
4695 child.0,
4696 cstr("").as_ptr(),
4697 (index - 1) as c_int,
4698 );
4699 let id = NAV_PAGE_IDS
4700 .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
4701 .unwrap_or(NodeId(0));
4702 suite.pages.push((*child, id));
4703 if suite.pages.len() == 1 {
4705 ffi::day_qt_tabs_set_current(parent.0, 0);
4706 }
4707 }
4708 NAV_SUITE_PAGES.with(|m| m.borrow_mut().insert(child.0 as usize));
4709 }
4710 true
4711 });
4712 if suite_handled {
4713 suite_apply_rows(parent.0);
4714 nav_suite_sync(parent.0);
4715 return;
4716 }
4717 if let Some((node, titles, icons, keys)) =
4720 NAV_SUITE_ROWS.with(|m| m.borrow().get(&(child.0 as usize)).cloned())
4721 {
4722 let suite = unsafe { ffi::day_qt_enclosing_tabs(parent.0) };
4723 if !suite.is_null() {
4724 NAV_SUITES.with(|m| {
4725 if let Some(s) = m.borrow_mut().get_mut(&(suite as usize)) {
4726 s.menu_node = node;
4727 s.titles = titles;
4728 s.icons = icons;
4729 s.keys = keys;
4730 }
4731 });
4732 suite_apply_rows(suite);
4733 }
4734 }
4735 let sidebar = is_sidebar_page(child.0);
4737 let list = is_list_page(child.0);
4738 let handled = NAV_STATE.with(|m| {
4739 let mut m = m.borrow_mut();
4740 let Some(state) = m.get_mut(&(parent.0 as usize)) else {
4741 return false;
4742 };
4743 let id = NAV_PAGE_IDS
4744 .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
4745 .unwrap_or(NodeId(0));
4746 if sidebar {
4747 state.sidebar_page = Some(*child);
4748 }
4749 if list {
4750 state.list_page = Some(*child);
4751 }
4752 let pane = if list {
4755 state.list_pane
4756 } else if state.split && sidebar {
4757 state.sidebar_pane
4758 } else {
4759 state.detail_pane
4760 };
4761 unsafe { ffi::day_qt_add_child(pane, child.0) };
4762 state.pages.push((*child, id));
4763 true
4764 });
4765 if handled {
4766 nav_sync_panes(parent.0);
4767 return;
4768 }
4769 let split_pane = SPLIT_STATE.with(|m| {
4771 let mut m = m.borrow_mut();
4772 let Some(state) = m.get_mut(&(parent.0 as usize)) else {
4773 return false;
4774 };
4775 let (pane_id, second) = SPLIT_PANE_IDS
4776 .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
4777 .unwrap_or((NodeId(0), index == 1));
4778 let pane = if second {
4779 state.second_pane
4780 } else {
4781 state.first_pane
4782 };
4783 unsafe { ffi::day_qt_add_child(pane, child.0) };
4784 state.panes.push((pane_id, second));
4785 true
4786 });
4787 if split_pane {
4788 split_sync_panes(parent.0);
4789 return;
4790 }
4791 let inspected = INSPECTOR_STATE.with(|m| {
4793 let mut m = m.borrow_mut();
4794 let Some(state) = m.get_mut(&(parent.0 as usize)) else {
4795 return false;
4796 };
4797 let (pane_id, panel) = INSPECTOR_PANE_IDS
4798 .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
4799 .unwrap_or((NodeId(0), index == 1));
4800 let pane = if panel {
4801 state.panel_pane
4802 } else {
4803 state.content_pane
4804 };
4805 unsafe { ffi::day_qt_add_child(pane, child.0) };
4806 state.panes.push((pane_id, panel));
4807 true
4808 });
4809 if inspected {
4810 inspector_sync_panes(parent.0);
4811 } else {
4812 unsafe { ffi::day_qt_add_child(content_of(parent), child.0) };
4813 }
4814 }
4815
4816 fn remove(&mut self, parent: &QtHandle, child: &QtHandle) {
4817 PAGE_PANE.with(|m| m.borrow_mut().remove(&(child.0 as usize)));
4818 NAV_STATE.with(|m| {
4819 if let Some(state) = m.borrow_mut().get_mut(&(parent.0 as usize)) {
4820 state.pages.retain(|(p, _)| p.0 != child.0);
4821 if state.sidebar_page.map(|p| p.0) == Some(child.0) {
4822 state.sidebar_page = None;
4823 }
4824 if state.list_page.map(|p| p.0) == Some(child.0) {
4825 state.list_page = None;
4826 }
4827 }
4828 });
4829 let in_suite = NAV_SUITES.with(|m| {
4832 if let Some(suite) = m.borrow_mut().get_mut(&(parent.0 as usize)) {
4833 suite.pages.retain(|(p, _)| p.0 != child.0);
4834 true
4835 } else {
4836 false
4837 }
4838 });
4839 if in_suite {
4840 unsafe { ffi::day_qt_tabs_remove_page(parent.0, child.0) };
4841 }
4842 unsafe { ffi::day_qt_remove_child(child.0) };
4843 }
4844
4845 fn move_child(&mut self, _parent: &QtHandle, _child: &QtHandle, _to: usize) {}
4846
4847 fn measure(&mut self, h: &QtHandle, kind: PieceKind, p: Proposal) -> Size {
4848 let mut w = 0.0;
4849 let mut hh = 0.0;
4850 if kind != kinds::LABEL {
4853 unsafe { ffi::day_qt_size_hint(h.0, &raw mut w, &raw mut hh) };
4854 }
4855 match kind {
4856 kinds::NAV_MENU => {
4857 let (rows, headings) = NAV_MENU_ROWS
4858 .with(|m| m.borrow().get(&(h.0 as usize)).copied().unwrap_or((0, 0)));
4859 Size::new(
4863 p.width.unwrap_or(220.0),
4864 p.height
4865 .unwrap_or(rows as f64 * 34.0 + headings as f64 * 30.0 + 8.0),
4866 )
4867 }
4868 kinds::LABEL => {
4869 let nat_w = f64::from(unsafe { ffi::day_qt_label_natural_width(h.0) });
4874 let width = match p.width {
4875 Some(pw) => nat_w.min(pw),
4876 None => nat_w,
4877 };
4878 let hfw = unsafe {
4879 ffi::day_qt_label_height_for_width(h.0, width.round().max(1.0) as c_int)
4880 };
4881 if hfw > 0 {
4882 Size::new(width.ceil(), f64::from(hfw))
4883 } else {
4884 unsafe { ffi::day_qt_size_hint(h.0, &raw mut w, &raw mut hh) };
4885 Size::new(width.ceil(), hh.ceil())
4886 }
4887 }
4888 kinds::BUTTON => Size::new(w.ceil(), hh.ceil()),
4892 kinds::SLIDER => Size::new(p.width.unwrap_or(180.0), hh.max(20.0)),
4893 kinds::PICKER => picker::measure_any(self, *h, p),
4894 kinds::TEXT_AREA => textarea::measure_any(self, *h, p),
4895 kinds::TEXT_FIELD => Size::new(p.width.unwrap_or(180.0), hh.max(24.0)),
4896 kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 2.0),
4897 kinds::PROGRESS => Size::new(p.width.unwrap_or(180.0), hh.max(16.0)),
4898 kinds::LIST => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
4899 _ => {
4900 if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
4901 measure(self, h, p)
4902 } else {
4903 Size::new(p.width.unwrap_or(w), p.height.unwrap_or(hh))
4904 }
4905 }
4906 }
4907 }
4908
4909 fn set_opacity(&mut self, h: &QtHandle, opacity: f64, anim: Option<&AnimSpec>) {
4910 with_qt_anim(anim, |anim| unsafe {
4914 ffi::day_qt_set_opacity(h.0, opacity, anim);
4915 });
4916 }
4917
4918 fn set_transform(&mut self, h: &QtHandle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
4919 with_qt_anim(anim, |anim| unsafe {
4923 ffi::day_qt_set_transform(h.0, t.tx, t.ty, t.sx, t.sy, t.rotation.degrees(), anim);
4924 });
4925 }
4926
4927 fn read_displayed(&self, h: &QtHandle) -> day_spec::Displayed {
4930 if h.0.is_null() {
4931 return day_spec::Displayed::default();
4932 }
4933 let mut d = ffi::DayQtDisplayed::default();
4934 unsafe { ffi::day_qt_read_displayed(h.0, &raw mut d) };
4936 day_spec::Displayed {
4937 opacity: Some(d.opacity),
4938 frame: (d.frame_ok != 0).then(|| Rect::new(d.x, d.y, d.w, d.h)),
4939 translation: Some(day_spec::Point::new(d.tx, d.ty)),
4940 background: (d.fill_ok != 0).then(|| day_spec::Color::rgba(d.r, d.g, d.b, d.a)),
4941 }
4942 }
4943
4944 fn set_cursor(&mut self, h: &QtHandle, cursor: Cursor) {
4945 unsafe { ffi::day_qt_widget_set_cursor(h.0, qt_cursor_shape(&cursor)) };
4949 }
4950
4951 fn set_input_traits(&mut self, h: &QtHandle, traits: &InputTraits) -> Option<QtHandle> {
4952 unsafe {
4961 ffi::day_qt_lineedit_set_traits(
4962 h.0,
4963 c_int::from(traits.secure),
4964 c_int::from(traits.read_only),
4965 qt_input_purpose(traits.purpose),
4966 );
4967 };
4968 None
4969 }
4970
4971 fn set_selectable(&mut self, h: &QtHandle, selectable: bool) -> Option<QtHandle> {
4972 unsafe { ffi::day_qt_label_set_selectable(h.0, c_int::from(selectable)) };
4974 None
4975 }
4976
4977 fn text_scale(&mut self, _style: Font) -> f64 {
4981 unsafe { ffi::day_qt_text_scale() }
4984 }
4985
4986 fn set_layout_direction(
4991 &mut self,
4992 h: &QtHandle,
4993 kind: PieceKind,
4994 direction: day_spec::LayoutDirection,
4995 ) {
4996 if matches!(
4997 kind,
4998 kinds::CONTAINER
4999 | kinds::SCROLL
5000 | kinds::CANVAS
5001 | kinds::IMAGE
5002 | kinds::NAV
5003 | kinds::NAV_PAGE
5004 | kinds::NAV_MENU
5005 | kinds::LIST
5006 | kinds::LIST_CELL
5007 | kinds::TREE
5008 | kinds::COVER
5009 | kinds::INSPECTOR
5010 | kinds::INSPECTOR_PANE
5011 | kinds::SPLIT
5012 | kinds::SPLIT_PANE
5013 ) || h.0.is_null()
5014 {
5015 return;
5016 }
5017 let rtl = c_int::from(direction == day_spec::LayoutDirection::Rtl);
5018 unsafe { ffi::day_qt_widget_set_direction(h.0, rtl) };
5020 }
5021
5022 fn first_baseline(&mut self, h: &QtHandle, kind: PieceKind, size: Size) -> Option<f64> {
5026 if !day_spec::kind_has_baseline(kind) {
5027 return None;
5028 }
5029 let b = unsafe { ffi::day_qt_baseline(h.0, size.height) };
5030 (b >= 0.0).then_some(b)
5031 }
5032
5033 fn set_frame(&mut self, h: &QtHandle, frame: Rect, anim: Option<&AnimSpec>) {
5034 let key = h.0 as usize;
5038 let native_host = NAV_STATE.with(|m| m.borrow().contains_key(&key))
5039 || NAV_SUITES.with(|m| m.borrow().contains_key(&key))
5040 || SPLIT_STATE.with(|m| m.borrow().contains_key(&key))
5041 || INSPECTOR_STATE.with(|m| m.borrow().contains_key(&key))
5042 || LIST_STATE.with(|m| m.borrow().contains_key(&key));
5043 let anim = if native_host { None } else { anim };
5044 with_qt_anim(anim, |anim| unsafe {
5046 ffi::day_qt_set_frame(
5047 h.0,
5048 frame.origin.x.round() as c_int,
5049 frame.origin.y.round() as c_int,
5050 frame.size.width.round() as c_int,
5051 frame.size.height.round() as c_int,
5052 anim,
5053 );
5054 });
5055 if NAV_STATE.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
5057 nav_sync_panes(h.0);
5058 }
5059 if NAV_SUITES.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
5060 nav_suite_sync(h.0);
5061 }
5062 if SPLIT_STATE.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
5064 split_sync_panes(h.0);
5065 }
5066 if INSPECTOR_STATE.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
5068 inspector_sync_panes(h.0);
5069 }
5070 let width_changed = LIST_STATE.with(|m| {
5073 m.borrow()
5074 .get(&(h.0 as usize))
5075 .is_some_and(|st| st.last_width != frame.size.width.round() as c_int)
5076 });
5077 let framed_h = frame.size.height.round() as c_int;
5081 let height_changed = LIST_STATE.with(|m| {
5082 let mut m = m.borrow_mut();
5083 let Some(st) = m.get_mut(&(h.0 as usize)) else {
5084 return false;
5085 };
5086 let changed = st.frame_height != framed_h;
5087 st.frame_height = framed_h;
5088 changed
5089 });
5090 if width_changed {
5091 schedule_list_populate(h.0 as usize);
5092 } else if height_changed {
5093 schedule_list_fill(h.0 as usize);
5094 }
5095 }
5096
5097 fn scroll_bar_inset(&mut self, h: &QtHandle, vertical: bool) -> f64 {
5098 f64::from(unsafe { ffi::day_qt_scroll_bar_inset(h.0, c_int::from(vertical)) })
5099 }
5100
5101 fn set_scroll_content(&mut self, h: &QtHandle, content: Size) {
5102 unsafe {
5103 ffi::day_qt_scroll_set_content_size(
5104 h.0,
5105 content.width.round() as c_int,
5106 content.height.round() as c_int,
5107 );
5108 };
5109 }
5110
5111 fn list_row_metrics(&mut self, _h: &QtHandle) -> day_spec::RowMetrics {
5113 day_spec::RowMetrics {
5114 insets: day_spec::Insets {
5115 top: 4.0,
5116 leading: 8.0,
5117 bottom: 4.0,
5118 trailing: 8.0,
5119 },
5120 min_height: 28.0,
5121 }
5122 }
5123
5124 fn scroll_to(&mut self, h: &QtHandle, target: Rect, animated: bool) {
5125 unsafe {
5128 ffi::day_qt_scroll_to_rect(
5129 h.0,
5130 target.origin.x.round() as c_int,
5131 target.origin.y.round() as c_int,
5132 target.size.width.round() as c_int,
5133 target.size.height.round() as c_int,
5134 c_int::from(animated),
5135 );
5136 };
5137 }
5138
5139 fn scroll_offset(&mut self, h: &QtHandle) -> day_spec::Point {
5140 let (mut x, mut y) = (0.0_f64, 0.0_f64);
5141 unsafe { ffi::day_qt_scroll_offset(h.0, &raw mut x, &raw mut y) };
5142 day_spec::Point::new(x, y)
5143 }
5144
5145 fn list_scroll(&mut self, h: &QtHandle, to: day_spec::ListScroll) -> bool {
5146 let host_key = h.0 as usize;
5152 let row = to
5153 .row
5154 .map_or(-1, |r| c_int::try_from(r).unwrap_or(c_int::MAX));
5155 let align = row_align_code(to.align);
5156 let animated = c_int::from(to.animated);
5157 Qt::post(Box::new(move || {
5158 if let Some(host) = LIST_STATE.with(|m| m.borrow().get(&host_key).map(|st| st.host)) {
5159 unsafe { ffi::day_qt_list_scroll(host, row, align, animated) };
5160 }
5161 }));
5162 true
5163 }
5164
5165 fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
5166 use day_spec::present::PresentSpec;
5167 let parent = self.present_parent();
5168 match spec {
5169 PresentSpec::Dialog { .. } => unsafe {
5170 ffi::day_qt_present_dialog(
5171 req,
5172 cstr(spec.title()).as_ptr(),
5173 cstr(spec.message().unwrap_or("")).as_ptr(),
5174 cstr(&spec.buttons_joined()).as_ptr(),
5175 cstr(&spec.roles_joined()).as_ptr(),
5176 parent,
5177 );
5178 },
5179 PresentSpec::Prompt {
5180 placeholder,
5181 initial,
5182 ok,
5183 cancel,
5184 ..
5185 } => unsafe {
5186 ffi::day_qt_present_prompt(
5187 req,
5188 cstr(spec.title()).as_ptr(),
5189 cstr(spec.message().unwrap_or("")).as_ptr(),
5190 cstr(placeholder).as_ptr(),
5191 cstr(initial).as_ptr(),
5192 cstr(ok).as_ptr(),
5193 cstr(cancel).as_ptr(),
5194 parent,
5195 );
5196 },
5197 PresentSpec::OpenFile { multiple, .. } => unsafe {
5198 ffi::day_qt_present_file_open(
5199 req,
5200 cstr(spec.title()).as_ptr(),
5201 cstr(&spec.filters_joined()).as_ptr(),
5202 c_int::from(*multiple),
5203 parent,
5204 );
5205 },
5206 PresentSpec::OpenFolder { .. } => unsafe {
5207 ffi::day_qt_present_folder_open(req, cstr(spec.title()).as_ptr(), parent);
5208 },
5209 PresentSpec::SaveFile { suggested_name, .. } => unsafe {
5210 ffi::day_qt_present_file_save(
5212 req,
5213 cstr(spec.title()).as_ptr(),
5214 cstr(suggested_name).as_ptr(),
5215 cstr(&spec.filters_joined()).as_ptr(),
5216 parent,
5217 );
5218 },
5219 }
5220 }
5221
5222 fn dismiss(&mut self, req: u64) {
5223 unsafe { ffi::day_qt_dismiss_present(req) };
5224 }
5225
5226 #[cfg(target_os = "macos")]
5227 fn share_support(&self) -> day_spec::Support {
5228 day_spec::Support::Native
5229 }
5230 #[cfg(target_os = "macos")]
5231 fn share(&mut self, spec: &day_spec::share::ShareSpec, _anchor: Option<&Self::Handle>) -> bool {
5232 unsafe { ffi::day_qt_share_url(cstr(&spec.url).as_ptr(), cstr(&spec.title).as_ptr()) }
5233 }
5234 fn open_url(&mut self, url: &str) {
5235 if let Ok(c) = std::ffi::CString::new(url) {
5236 unsafe { ffi::day_qt_open_url(c.as_ptr()) };
5237 }
5238 }
5239
5240 fn set_focusable(&mut self, h: &QtHandle, node: NodeId, focusable: bool) {
5241 if focusable {
5242 unsafe {
5243 ffi::day_qt_enable_keys(h.0, node.0, on_key);
5244 ffi::day_qt_enable_focus(h.0, node.0, on_focus);
5245 ffi::day_qt_set_focusable(h.0);
5246 }
5247 }
5248 }
5249
5250 fn focus(&mut self, h: &QtHandle, _node: NodeId, focused: bool) {
5251 unsafe { ffi::day_qt_widget_focus(h.0, c_int::from(focused)) };
5254 }
5255
5256 fn set_event_sink(&mut self, sink: EventSink) {
5257 SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
5258 }
5259
5260 fn enable_gesture(&mut self, h: &QtHandle, node: NodeId, kind: day_spec::GestureKind) {
5261 use day_spec::GestureKind as K;
5262 let key = (h.0 as usize, kind);
5263 if !GESTURES.with(|g| g.borrow_mut().insert(key)) {
5264 return; }
5266 let code: c_int = match kind {
5267 K::Tap => 0,
5268 K::Drag => 1,
5269 K::Pinch => 2,
5270 K::Pan => 3,
5271 K::Hover => 4,
5272 K::Rotate => 5,
5273 K::Press => 6,
5274 K::LongPress => 7,
5275 K::DoubleTap => 8,
5276 K::Touches => 9,
5277 };
5278 unsafe { ffi::day_qt_enable_gesture(h.0, node.0, code, on_gesture) };
5279 }
5280
5281 fn gesture_support(&self, kind: day_spec::GestureKind) -> Support {
5288 match kind {
5289 day_spec::GestureKind::Touches if cfg!(target_os = "macos") => Support::Unsupported,
5290 _ => Support::Native,
5291 }
5292 }
5293
5294 fn set_hit_slop(&mut self, h: &QtHandle, _node: NodeId, slop: day_spec::Insets) {
5295 unsafe {
5296 ffi::day_qt_set_hit_slop(h.0, slop.top, slop.leading, slop.bottom, slop.trailing);
5297 }
5298 }
5299
5300 fn set_drag_axis(&mut self, h: &QtHandle, _node: NodeId, axis: Option<day_spec::DragAxis>) {
5301 let code = match axis {
5302 None => 0,
5303 Some(day_spec::DragAxis::Horizontal) => 1,
5304 Some(day_spec::DragAxis::Vertical) => 2,
5305 };
5306 unsafe { ffi::day_qt_set_drag_axis(h.0, code) };
5307 }
5308
5309 fn set_subtree_enabled(&mut self, h: &QtHandle, _node: NodeId, enabled: bool) {
5313 unsafe { ffi::day_qt_subtree_enabled(h.0, c_int::from(enabled)) };
5314 }
5315
5316 fn edit_toolbar(&mut self, h: &QtHandle, ops: &[day_spec::ToolbarOp]) -> bool {
5317 self.edit_toolbar(h, ops)
5318 }
5319
5320 fn update_toolbar(&mut self, h: &QtHandle, patch: &day_spec::ToolbarPatch) {
5321 self.patch_toolbar(h, patch);
5322 }
5323
5324 fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
5325 if self.window.is_null() {
5326 return;
5327 }
5328 let items = day_core::menu::standard_menu_bar_for(
5330 day_core::menu::MenuBarStyle::Kde,
5331 items.to_vec(),
5332 );
5333 let items = &items[..];
5334 let bar = unsafe { ffi::day_qt_window_menubar(self.window) };
5335 for item in items {
5337 match item {
5338 day_spec::MenuItem::Submenu { label, items, .. } => {
5339 let menu = unsafe { ffi::day_qt_menubar_add_menu(bar, cstr(label).as_ptr()) };
5340 build_qt_menu(menu, items);
5341 }
5342 other => {
5343 let menu = unsafe { ffi::day_qt_menubar_add_menu(bar, cstr("").as_ptr()) };
5344 build_qt_menu(menu, std::slice::from_ref(other));
5345 }
5346 }
5347 }
5348 unsafe { ffi::day_qt_window_menubar_done(self.window) };
5351 }
5352
5353 fn modifiers(&mut self) -> day_spec::Modifiers {
5354 let m = unsafe { ffi::day_qt_modifiers() };
5355 day_spec::Modifiers::from_bits((m & 7) as u8)
5357 }
5358
5359 fn set_drag_source(&mut self, h: &QtHandle, source: day_spec::transfer::Source) {
5360 transfer::source(h, source);
5361 }
5362 fn set_drop_target(&mut self, h: &QtHandle, target: day_spec::transfer::Target) {
5363 transfer::target(h, target);
5364 }
5365 fn set_context_menu_fn(&mut self, h: &QtHandle, node: NodeId, f: day_spec::ContextMenuFn) {
5366 CTX_MENU_FNS.with(|m| m.borrow_mut().insert(node.0, f));
5367 unsafe { ffi::day_qt_context_menu_fn(h.0, node.0, on_context_menu_summon) };
5368 }
5369
5370 fn set_button_menu(&mut self, h: &QtHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
5371 BUTTON_MENUS.with(|t| t.insert(h.0 as usize, f));
5372 unsafe { ffi::day_qt_button_menu_fn(h.0, h.0 as u64, on_button_menu) };
5375 }
5376
5377 fn set_context_menu(&mut self, h: &QtHandle, _node: NodeId, items: &[day_spec::MenuItem]) {
5378 if items.is_empty() {
5379 unsafe { ffi::day_qt_set_context_menu(h.0, std::ptr::null_mut()) };
5380 return;
5381 }
5382 let menu = unsafe { ffi::day_qt_menu_new() };
5383 build_qt_menu(menu, items);
5384 unsafe { ffi::day_qt_set_context_menu(h.0, menu) };
5385 }
5386
5387 fn attach_tree(&mut self, host: &QtHandle, source: day_spec::TreeSource) {
5388 tree::attach(host.0 as usize, source);
5389 }
5390
5391 fn attach_list(&mut self, host: &QtHandle, source: day_spec::ListSource) {
5392 LIST_STATE.with(|m| {
5393 if let Some(st) = m.borrow().get(&(host.0 as usize)) {
5394 *st.source.borrow_mut() = Some(source);
5395 }
5396 });
5397 schedule_list_populate(host.0 as usize);
5399 }
5400
5401 fn adopt(&mut self, raw: day_spec::RawHandle) -> QtHandle {
5402 QtHandle(raw)
5404 }
5405
5406 fn set_a11y(&mut self, h: &QtHandle, a11y: &A11yProps) {
5407 unsafe {
5408 if let Some(id) = &a11y.identifier {
5409 ffi::day_qt_set_object_name(h.0, cstr(id).as_ptr());
5410 }
5411 if let Some(label) = &a11y.label {
5412 ffi::day_qt_set_accessible_name(h.0, cstr(label).as_ptr());
5414 ffi::day_qt_set_tooltip(h.0, cstr(label).as_ptr());
5415 }
5416 if let Some(hint) = &a11y.hint {
5417 ffi::day_qt_set_accessible_description(h.0, cstr(hint).as_ptr());
5418 }
5419 let (role, level) = match a11y.role {
5423 Role::None => (0, 0),
5424 Role::Button => (1, 0),
5425 Role::Toggle => (2, 0),
5426 Role::Slider => (3, 0),
5427 Role::TextInput => (4, 0),
5428 Role::Heading(level) => (5, c_int::from(level.max(1))),
5429 Role::Image => (6, 0),
5430 Role::Meter => (7, 0),
5431 Role::Group => (8, 0),
5432 Role::Tree => (9, 0),
5433 Role::TreeItem => (10, 0),
5434 Role::Tab => (11, 0),
5435 Role::TabList => (12, 0),
5436 };
5437 let value = a11y.value.as_deref().map(cstr);
5438 if role != 0 || value.is_some() || a11y.hidden || a11y.selected.is_some() {
5439 ffi::day_qt_set_a11y_traits(
5440 h.0,
5441 role,
5442 level,
5443 value.as_ref().map_or(std::ptr::null(), |v| v.as_ptr()),
5444 c_int::from(a11y.hidden),
5445 a11y.selected.map_or(-1, c_int::from),
5446 );
5447 }
5448 }
5449 }
5450
5451 fn read_native(&self, h: &QtHandle) -> day_spec::NativeSnapshot {
5455 if h.0.is_null() {
5456 return day_spec::NativeSnapshot::default();
5457 }
5458 let mut n = std::mem::MaybeUninit::<ffi::DayQtNative>::zeroed();
5459 let mut n = unsafe {
5462 ffi::day_qt_read_native(h.0, n.as_mut_ptr());
5463 n.assume_init()
5464 };
5465 let string = |p: *mut c_char| {
5468 (!p.is_null()).then(|| unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned())
5469 };
5470 let role = match n.role {
5471 1 => Role::Button,
5472 2 => Role::Toggle,
5473 3 => Role::Slider,
5474 4 => Role::TextInput,
5475 5 => Role::Heading(u8::try_from(n.level).unwrap_or(1).max(1)),
5476 6 => Role::Image,
5477 7 => Role::Meter,
5478 8 => Role::Group,
5479 9 => Role::Tree,
5480 10 => Role::TreeItem,
5481 11 => Role::Tab,
5482 12 => Role::TabList,
5483 _ => Role::None,
5484 };
5485 let ticks = f64::from(n.number) / 1000.0;
5486 let number = match n.number_kind {
5487 1 => RANGES_BY_PTR
5488 .with(|r| r.get(h.0 as usize))
5489 .map(|(min, max)| {
5490 if max <= min {
5492 min
5493 } else {
5494 min + ticks * (max - min)
5495 }
5496 }),
5497 2 => Some(ticks),
5498 _ => None,
5499 };
5500 let found = n.found != 0;
5501 let snapshot = day_spec::NativeSnapshot {
5502 found,
5503 role: if found { role } else { Role::None },
5504 label: string(n.label),
5505 value: string(n.value),
5506 identifier: string(n.identifier),
5507 text: match crate::picker::selected_text(h.0) {
5509 Some(picked) => picked,
5510 None => string(n.text),
5511 },
5512 number,
5513 checked: (n.checked >= 0).then_some(n.checked != 0),
5514 enabled: Some(n.enabled != 0),
5515 visible: Some(n.visible != 0),
5516 frame: (n.frame_ok != 0).then(|| Rect::new(n.x, n.y, n.w, n.h)),
5517 };
5518 unsafe { ffi::day_qt_native_free(&raw mut n) };
5520 snapshot
5521 }
5522
5523 fn announce(&mut self, text: &str, urgent: bool) {
5524 if self.window.is_null() {
5525 return;
5526 }
5527 unsafe { ffi::day_qt_announce(self.window, cstr(text).as_ptr(), c_int::from(urgent)) };
5530 }
5531
5532 fn request_frame(
5533 &mut self,
5534 host: &QtHandle,
5535 cb: day_spec::FrameCallback,
5536 ) -> day_spec::CancelFrame {
5537 let token = day_core::frame::native::register(cb);
5538 unsafe { ffi::day_qt_request_frame(host.0, token, run_frame) };
5539 Box::new(move || {
5540 day_core::frame::native::cancel(token);
5541 unsafe { ffi::day_qt_cancel_frame(token) };
5542 })
5543 }
5544
5545 fn replay(&mut self, h: &QtHandle, ops: &[DrawOp], _size: Size) {
5546 let (nums, texts) = day_spec::encode_ops(ops);
5547 let joined = cstr(&texts.join("\u{1f}"));
5548 unsafe {
5549 ffi::day_qt_canvas_set_ops(h.0, nums.as_ptr(), nums.len() as c_int, joined.as_ptr());
5550 };
5551 }
5552
5553 fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
5559 let mut rgba = [0.0f64; 4];
5560 if unsafe { ffi::day_qt_system_color(c_int::from(role.wire()), rgba.as_mut_ptr()) } != 0 {
5562 day_spec::Color::rgba(rgba[0], rgba[1], rgba[2], rgba[3])
5563 } else {
5564 role.fallback(self.dark_mode())
5565 }
5566 }
5567
5568 fn set_appearance(&mut self, dark: Option<bool>) {
5571 let mode = match dark {
5572 None => -1,
5573 Some(false) => 0,
5574 Some(true) => 1,
5575 };
5576 if unsafe { ffi::day_qt_set_appearance(mode) } == 0 {
5578 return;
5579 }
5580 day_spec::Palette::set_current(day_spec::Palette {
5584 dark: self.dark_mode(),
5585 colors: day_spec::SystemColor::ALL.map(|role| self.system_color(role)),
5586 });
5587 reapply_inks();
5588 }
5589
5590 fn dark_mode(&mut self) -> bool {
5591 unsafe { ffi::day_qt_dark_mode() != 0 }
5596 }
5597
5598 fn toggle_sidebar(&mut self, host: &QtHandle) -> bool {
5599 crate::toggle_sidebar(host.0)
5600 }
5601
5602 fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
5605 unsafe {
5608 let p = ffi::day_qt_font_families();
5609 if p.is_null() {
5610 return Vec::new();
5611 }
5612 let text = std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned();
5613 ffi::day_qt_string_free(p);
5614 day_spec::parse_font_list(&text)
5615 }
5616 }
5617
5618 fn measure_text(
5620 &mut self,
5621 text: &str,
5622 size: f64,
5623 font: &day_spec::CanvasFont,
5624 ) -> Option<day_spec::TextMetrics> {
5625 let text = cstr(text);
5626 let family = cstr(font.family_str());
5627 let mut out = [0.0f64; 8];
5628 unsafe {
5630 ffi::day_qt_measure_text(
5631 text.as_ptr(),
5632 size,
5633 c_int::from(font.css_weight()),
5634 c_int::from(font.italic),
5635 family.as_ptr(),
5636 out.as_mut_ptr(),
5637 );
5638 };
5639 Some(day_spec::TextMetrics::from_slots(&out))
5640 }
5641
5642 fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
5646 let mut out = [0.0f64; 3];
5647 let ok = unsafe {
5650 ffi::day_qt_image_decode(id.0, bytes.as_ptr(), bytes.len() as c_int, out.as_mut_ptr())
5651 };
5652 let event = if ok != 0 {
5653 let info = day_spec::BitmapInfo {
5654 pixels: Size::new(out[0], out[1]),
5655 scale: 1.0,
5657 format: day_spec::ImageFormat::sniff(bytes),
5658 has_alpha: out[2] > 0.5,
5659 };
5660 BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
5661 Event::ImageDecoded {
5662 req,
5663 result: Ok(info),
5664 }
5665 } else {
5666 Event::ImageDecoded {
5667 req,
5668 result: Err(day_spec::ImageError::Decode),
5669 }
5670 };
5671 emit(day_spec::WINDOW_NODE, event);
5672 }
5673
5674 fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
5675 BITMAP_INFO.with(|m| m.borrow().get(&id.0).copied())
5676 }
5677
5678 fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
5679 let result = encode_bitmap(id, spec);
5680 emit(day_spec::WINDOW_NODE, Event::ImageEncoded { req, result });
5681 }
5682
5683 fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
5687 use day_spec::ImageFormat::{Bmp, Jpeg, Png, Tiff};
5688 vec![Png, Jpeg, Tiff, Bmp]
5689 }
5690
5691 fn release_image(&mut self, id: day_spec::BitmapId) {
5692 release_bitmap(id);
5693 }
5694
5695 fn render_bitmap(
5699 &mut self,
5700 req: u64,
5701 id: day_spec::BitmapId,
5702 ops: &[DrawOp],
5703 size: Size,
5704 scale: f64,
5705 ) {
5706 let (pw, ph) = day_spec::export_pixels(size, scale);
5707 let (nums, texts) = day_spec::encode_ops(ops);
5708 let joined = cstr(&texts.join("\u{1f}"));
5709 let result = match (c_int::try_from(pw), c_int::try_from(ph)) {
5710 (Ok(w), Ok(h)) => {
5712 if unsafe {
5713 ffi::day_qt_canvas_render_image(
5714 id.0,
5715 nums.as_ptr(),
5716 nums.len() as c_int,
5717 joined.as_ptr(),
5718 w,
5719 h,
5720 scale,
5721 )
5722 } == 0
5723 {
5724 Err(day_spec::ExportError::Failed(format!(
5725 "QImage could not allocate {pw} × {ph} pixels"
5726 )))
5727 } else {
5728 let info = day_spec::BitmapInfo {
5729 pixels: Size::new(f64::from(pw), f64::from(ph)),
5730 scale,
5731 format: None,
5732 has_alpha: true,
5733 };
5734 BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
5735 Ok(info)
5736 }
5737 }
5738 _ => Err(day_spec::ExportError::TooLarge {
5739 width: pw,
5740 height: ph,
5741 }),
5742 };
5743 emit(day_spec::WINDOW_NODE, Event::BitmapRendered { req, result });
5744 }
5745
5746 fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
5749 let result = render_pdf_document(pages, info);
5750 emit(day_spec::WINDOW_NODE, Event::PdfRendered { req, result });
5751 }
5752
5753 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
5754 if self.window.is_null() {
5755 return Err("no window".into());
5756 }
5757 snapshot_qt_widget(self.window)
5758 }
5759
5760 fn snapshot_window_of(&mut self, host: &QtHandle) -> Result<Vec<u8>, String> {
5761 snapshot_qt_widget(host.0)
5762 }
5763
5764 fn native_window_tabs(&self) -> bool {
5765 cfg!(target_os = "macos")
5766 }
5767 #[cfg(target_os = "macos")]
5768 fn group_windows(&mut self, hosts: &[QtHandle]) {
5769 for host in hosts {
5772 if let Some(w) = self.secondary.iter().find(|w| w.content == host.0)
5773 && let Some(group) = &w.tab_group
5774 {
5775 unsafe {
5776 ffi::day_qt_window_show(w.win);
5777 let view = ffi::day_qt_window_nsview(w.win);
5778 let raw = day_platform_macos::window_tabs::window_from_view(view);
5779 day_platform_macos::window_tabs::register(raw, w.id, group);
5780 }
5781 }
5782 }
5783 let ids = hosts
5784 .iter()
5785 .filter_map(|h| {
5786 self.secondary
5787 .iter()
5788 .find(|w| w.content == h.0)
5789 .map(|w| w.id)
5790 })
5791 .collect::<Vec<_>>();
5792 day_platform_macos::window_tabs::group(&ids);
5793 }
5794 #[cfg(target_os = "macos")]
5795 fn window_tab_order(&self, host: &QtHandle) -> Vec<NodeId> {
5796 self.secondary
5797 .iter()
5798 .find(|w| w.content == host.0)
5799 .map_or_default(|w| day_platform_macos::window_tabs::order(w.id))
5800 }
5801 fn native_document_tabs(&self) -> bool {
5802 true
5803 }
5804
5805 fn open_window(
5806 &mut self,
5807 id: NodeId,
5808 options: &WindowOptions,
5809 kind: day_spec::WindowKind,
5810 ) -> day_spec::WindowOpenReply<QtHandle> {
5811 let fixed = c_int::from(kind.is_panel());
5812 let win = unsafe {
5813 ffi::day_qt_window_new2(
5814 cstr(&options.title).as_ptr(),
5815 options.size.width as c_int,
5816 options.size.height as c_int,
5817 id.0,
5818 fixed,
5819 )
5820 };
5821 apply_open_options(win, options, fixed == 0);
5822 if !options.start_hidden {
5823 unsafe { ffi::day_qt_window_show(win) };
5824 }
5825 let content = unsafe { ffi::day_qt_window_content(win) };
5826 self.secondary.push(QtWin {
5827 #[cfg(target_os = "macos")]
5828 id,
5829 #[cfg(target_os = "macos")]
5830 tab_group: match &options.tabbing {
5831 day_spec::WindowTabbing::Group(g) | day_spec::WindowTabbing::Preferred(g) => {
5832 Some(g.clone())
5833 }
5834 _ => None,
5835 },
5836 win,
5837 content,
5838 });
5839 day_spec::WindowOpenReply::Open(QtHandle(content))
5840 }
5841
5842 fn close_window(&mut self, host: &QtHandle) {
5843 if let Some(w) = self.secondary.iter().find(|w| w.content == host.0) {
5844 #[cfg(target_os = "macos")]
5847 day_platform_macos::window_tabs::unregister(w.id);
5848 unsafe { ffi::day_qt_window_close(w.win) };
5849 }
5850 }
5851
5852 fn focus_window(&mut self, host: &QtHandle) {
5853 if let Some(w) = self.secondary.iter().find(|w| w.content == host.0) {
5854 unsafe { ffi::day_qt_window_raise(w.win) };
5855 }
5856 }
5857
5858 fn fit_window(&mut self, host: &QtHandle, size: Size) {
5859 if let Some(win) = self.qt_window_for(host) {
5863 unsafe { ffi::day_qt_window_fit(win, size.width, size.height) };
5865 }
5866 }
5867
5868 fn set_window_title(&mut self, host: &QtHandle, title: &str) {
5869 let win = match self.secondary.iter().find(|w| w.content == host.0) {
5873 Some(w) => w.win,
5874 None => self.window,
5875 };
5876 if !win.is_null() {
5877 unsafe { ffi::day_qt_window_set_title(win, cstr(title).as_ptr()) };
5878 }
5879 }
5880
5881 fn apply_window(&mut self, host: &QtHandle, change: &day_spec::WindowChange) {
5882 use day_spec::WindowChange as C;
5883 let Some(win) = self.qt_window_for(host) else {
5886 return;
5887 };
5888 match change {
5889 C::State(state) => unsafe { ffi::day_qt_window_set_state(win, state.code()) },
5892 C::ContentProtected(_) => {}
5896 other => apply_property(win, other),
5897 }
5898 }
5899
5900 fn window_frame(&self, host: &QtHandle) -> Option<day_spec::Rect> {
5901 let win = self.qt_window_for(host)?;
5902 let mut out = [0.0f64; 4];
5903 let known = unsafe { ffi::day_qt_window_frame(win, out.as_mut_ptr()) } != 0;
5906 known.then(|| day_spec::Rect::new(out[0], out[1], out[2], out[3]))
5907 }
5908
5909 fn monitors(&self) -> Vec<day_spec::Monitor> {
5910 qt_monitors()
5911 }
5912
5913 fn set_drag_region(&mut self, h: &QtHandle, drag: bool) {
5914 unsafe { ffi::day_qt_set_drag_region(h.0, c_int::from(drag)) };
5916 }
5917
5918 fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
5919 self.trays.retain(|(spec, tray)| {
5920 let keep = items.iter().any(|i| i.id == spec.id);
5921 if !keep {
5922 unsafe { ffi::day_qt_tray_delete(*tray) };
5924 }
5925 keep
5926 });
5927 for spec in items {
5928 let tray = match self.trays.iter_mut().find(|(s, _)| s.id == spec.id) {
5929 Some((s, _)) if s == spec => continue,
5930 Some((s, tray)) => {
5931 *s = spec.clone();
5932 *tray
5933 }
5934 None => {
5935 let tray = unsafe { ffi::day_qt_tray_new() };
5937 self.trays.push((spec.clone(), tray));
5938 tray
5939 }
5940 };
5941 update_tray(tray, spec);
5942 }
5943 }
5944
5945 fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
5946 #[cfg(target_os = "linux")]
5947 linux::set_progress(progress);
5948 #[cfg(not(target_os = "linux"))]
5949 let _ = progress;
5950 }
5951
5952 fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
5953 #[cfg(target_os = "linux")]
5954 linux::set_badge(badge);
5955 #[cfg(not(target_os = "linux"))]
5956 let _ = badge;
5957 }
5958
5959 fn set_keep_running(&mut self, keep: bool) {
5960 unsafe { ffi::day_qt_set_keep_running(c_int::from(keep)) };
5962 }
5963
5964 fn quit_app(&mut self) {
5965 unsafe { ffi::day_qt_quit() };
5967 }
5968}
5969
5970fn apply_open_options(win: *mut c_void, options: &WindowOptions, resizable: bool) {
5974 let frameless = options.chrome == day_spec::WindowChrome::Frameless;
5975 let transparent = options.background == day_spec::WindowBackground::Transparent;
5976 let resizable = resizable && options.resizable;
5977 unsafe {
5979 if options.min_size.is_some() || options.max_size.is_some() {
5980 let min = options.min_size.unwrap_or(Size::new(-1.0, -1.0));
5981 let max = options.max_size.unwrap_or(Size::new(-1.0, -1.0));
5982 ffi::day_qt_window_set_limits(win, min.width, min.height, max.width, max.height);
5983 }
5984 ffi::day_qt_window_set_chrome(
5985 win,
5986 c_int::from(frameless),
5987 c_int::from(transparent),
5988 c_int::from(options.shadow),
5989 c_int::from(resizable),
5990 );
5991 match options.placement {
5992 day_spec::WindowPlacement::Automatic => {}
5993 day_spec::WindowPlacement::Centered => ffi::day_qt_window_place(win, 1, 0.0, 0.0),
5994 day_spec::WindowPlacement::At(p) => ffi::day_qt_window_place(win, 2, p.x, p.y),
5995 }
5996 }
5997}
5998
5999fn apply_property(win: *mut c_void, change: &day_spec::WindowChange) {
6003 use day_spec::WindowChange as C;
6004 let switch = |which: c_int, on: bool| {
6005 unsafe { ffi::day_qt_window_set_switch(win, which, c_int::from(on)) }
6007 };
6008 match change {
6010 C::Frame { origin, size } => unsafe {
6011 ffi::day_qt_window_set_frame(
6012 win,
6013 c_int::from(origin.is_some()),
6014 origin.map_or(0.0, |p| p.x),
6015 origin.map_or(0.0, |p| p.y),
6016 c_int::from(size.is_some()),
6017 size.map_or(0.0, |s| s.width),
6018 size.map_or(0.0, |s| s.height),
6019 );
6020 },
6021 C::Limits { min, max } => unsafe {
6022 let min = min.unwrap_or(Size::new(-1.0, -1.0));
6023 let max = max.unwrap_or(Size::new(-1.0, -1.0));
6024 ffi::day_qt_window_set_limits(win, min.width, min.height, max.width, max.height);
6025 },
6026 C::Level(level) => switch(0, *level == day_spec::WindowLevel::Floating),
6027 C::SkipTaskbar(skip) => switch(1, *skip),
6028 C::Minimizable(on) => switch(2, *on),
6029 C::Maximizable(on) => switch(3, *on),
6030 C::Closable(on) => switch(4, *on),
6031 C::Resizable(on) => switch(5, *on),
6032 C::Visible(on) => switch(6, *on),
6033 C::RequestAttention(a) => unsafe {
6034 ffi::day_qt_window_alert(win, c_int::from(*a == day_spec::Attention::Critical));
6035 },
6036 _ => {}
6037 }
6038}
6039
6040fn qt_monitors() -> Vec<day_spec::Monitor> {
6043 let n = unsafe { ffi::day_qt_screen_count() };
6045 (0..n)
6046 .filter_map(|i| {
6047 let mut out = [0.0f64; 9];
6048 let mut name = [0 as std::os::raw::c_char; 256];
6049 let mut id = [0 as std::os::raw::c_char; 128];
6050 let primary = unsafe {
6053 ffi::day_qt_screen_info(
6054 i,
6055 out.as_mut_ptr(),
6056 name.as_mut_ptr(),
6057 name.len() as c_int,
6058 id.as_mut_ptr(),
6059 id.len() as c_int,
6060 )
6061 };
6062 if primary < 0 {
6063 return None;
6064 }
6065 let text = |b: &[std::os::raw::c_char]| unsafe {
6067 std::ffi::CStr::from_ptr(b.as_ptr())
6068 .to_string_lossy()
6069 .into_owned()
6070 };
6071 Some(day_spec::Monitor {
6072 id: text(&id),
6073 name: text(&name),
6074 frame: day_spec::Rect::new(out[0], out[1], out[2], out[3]),
6075 work_area: day_spec::Rect::new(out[4], out[5], out[6], out[7]),
6076 scale: out[8],
6077 primary: primary == 1,
6078 })
6079 })
6080 .collect()
6081}
6082
6083fn update_tray(tray: *mut c_void, spec: &day_spec::StatusItemSpec) {
6085 let (icon, fallback) = crate::toolbar::icon_args(spec.icon.as_ref());
6086 let tip = if spec.tooltip.is_empty() {
6087 spec.title.as_str()
6088 } else {
6089 spec.tooltip.as_str()
6090 };
6091 let menu = unsafe { ffi::day_qt_menu_new() };
6093 build_qt_menu(menu, &spec.menu);
6094 let mask = spec.template || matches!(spec.icon, Some(day_spec::Icon::Symbol(_)));
6095 unsafe {
6097 ffi::day_qt_tray_update(
6098 tray,
6099 cstr(&icon).as_ptr(),
6100 fallback,
6101 c_int::from(mask),
6102 cstr(tip).as_ptr(),
6103 menu,
6104 spec.activate,
6105 );
6106 };
6107 log::debug!("qt: status item {} shown", spec.id);
6108}
6109
6110fn snapshot_qt_widget(widget: *mut c_void) -> Result<Vec<u8>, String> {
6112 let path = std::env::temp_dir().join(format!("day-qt-snap-{}.png", std::process::id()));
6113 let cpath = cstr(path.to_str().unwrap_or("/tmp/day-qt-snap.png"));
6114 let scale = day_spec::capture_scale().unwrap_or(0.0);
6116 let rc = unsafe { ffi::day_qt_snapshot_png(widget, cpath.as_ptr(), scale) };
6117 if rc != 0 {
6118 return Err("grab failed".into());
6119 }
6120 let bytes = std::fs::read(&path).map_err(|e| e.to_string())?;
6121 let _ = std::fs::remove_file(&path);
6122 Ok(bytes)
6123}
6124
6125extern "C" fn run_posted(data: *mut c_void) {
6126 let f: Box<Box<dyn FnOnce() + Send>> = unsafe { Box::from_raw(data.cast()) };
6129 ffi_guard::contain((), f);
6130}
6131
6132extern "C" fn run_frame(token: u64, timestamp: f64) {
6134 day_core::frame::native::deliver(token, day_spec::FrameStamp::new(timestamp));
6135}
6136
6137impl Platform for Qt {
6138 const TARGET: &'static str = if cfg!(target_os = "macos") {
6139 "macos-qt"
6140 } else {
6141 "linux-qt"
6142 };
6143 const TOOLKIT: &'static str = "qt";
6144
6145 fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, QtHandle, Size)>) {
6146 #[cfg(target_os = "linux")]
6149 let _instance = linux::claim_instance();
6150 unsafe {
6151 let app_name = options.app_name.as_deref().unwrap_or(&options.title);
6155 let app = ffi::day_qt_app_new(cstr(app_name).as_ptr());
6156 if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
6159 ffi::day_qt_app_set_rtl();
6160 }
6161 ffi::day_qt_on_text_scale(on_text_scale);
6163 for path in day_spec::fonts::bundled_fonts() {
6166 if ffi::day_qt_register_font(cstr(&path.to_string_lossy()).as_ptr()) < 0 {
6167 log::warn!("could not register bundled font {}", path.display());
6168 }
6169 }
6170 if let Ok(icon) = std::env::var("DAY_APP_ICON") {
6172 ffi::day_qt_set_app_icon(cstr(&icon).as_ptr());
6173 }
6174 let window = ffi::day_qt_window_new(
6175 cstr(&options.title).as_ptr(),
6176 options.size.width as c_int,
6177 options.size.height as c_int,
6178 );
6179 self.window = window;
6180 ffi::day_qt_set_present_cb(present_cb);
6181 ffi::day_qt_set_menu_cb(on_menu_action);
6182 ffi::day_qt_set_text_keys(on_text_key_query, on_text_key);
6183 ffi::day_qt_set_touches_cb(on_touches);
6184 ffi::day_qt_install_input_router(on_pointer_kind);
6185 ffi::day_qt_set_toolbar_cb(toolbar::on_toolbar_value);
6186 ffi::day_qt_set_lifecycle_cb(on_lifecycle);
6187 ffi::day_qt_on_appearance(on_appearance);
6189 ready(self, QtHandle(window), options.size);
6190 ffi::day_qt_window_on_resize(window, window_resized);
6191 ffi::day_qt_set_window_events_cb(win_resized, win_closed, win_focused);
6192 ffi::day_qt_set_window_state_cb(win_state);
6193 apply_open_options(window, &options, true);
6194 ffi::day_qt_window_show(window);
6195 ffi::day_qt_app_run(app);
6196 }
6197 }
6198
6199 fn locale_hints(&self) -> Vec<String> {
6200 day_spec::posix_locale_hints()
6203 }
6204
6205 fn post(f: Box<dyn FnOnce() + Send>) {
6206 let data = Box::into_raw(Box::new(f)).cast::<c_void>();
6207 unsafe { ffi::day_qt_post(run_posted, data) };
6208 }
6209
6210 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
6211 const STEP: u32 = c_int::MAX as u32;
6216 if ms > STEP {
6217 Self::post_delayed(STEP, Box::new(move || Self::post_delayed(ms - STEP, f)));
6218 return;
6219 }
6220 let data = Box::into_raw(Box::new(f)).cast::<c_void>();
6221 unsafe { ffi::day_qt_post_delayed(ms as c_int, run_posted, data) };
6222 }
6223}
6224
6225fn release_bitmap(id: day_spec::BitmapId) {
6228 let _ = BITMAP_INFO.try_with(|m| {
6229 m.borrow_mut().remove(&id.0);
6230 unsafe { ffi::day_qt_image_release(id.0) };
6233 });
6234}
6235
6236#[unsafe(no_mangle)]
6243pub unsafe extern "C" fn day_qt_open_file(url: *const std::ffi::c_char) {
6244 day_spec::ffi_guard::contain((), || {
6245 if !url.is_null() {
6246 let file = unsafe { std::ffi::CStr::from_ptr(url) }
6247 .to_string_lossy()
6248 .into_owned();
6249 day_core::request_open_files(vec![file]);
6250 }
6251 });
6252}
6253
6254#[cfg(test)]
6255mod bitmap_teardown_tests {
6256 use super::*;
6257
6258 #[test]
6259 fn releasing_during_bitmap_registry_teardown_does_not_abort() {
6260 const CHILD: &str = "DAY_QT_BITMAP_TEARDOWN_CHILD";
6261 if std::env::var_os(CHILD).is_some() {
6262 struct LateRelease(std::sync::mpsc::Sender<()>);
6263 impl Drop for LateRelease {
6264 fn drop(&mut self) {
6265 assert!(BITMAP_INFO.try_with(|_| ()).is_err());
6266 release_bitmap(day_spec::BitmapId(1));
6267 self.0.send(()).unwrap();
6268 }
6269 }
6270 let (sent, received) = std::sync::mpsc::channel();
6271 std::thread::spawn(move || {
6272 let held = LateRelease(sent);
6273 SINK.with(|sink| {
6276 *sink.borrow_mut() = Some(Rc::new(move |_, _| {
6277 let _ = &held;
6278 }));
6279 });
6280 })
6281 .join()
6282 .unwrap();
6283 received
6284 .recv_timeout(std::time::Duration::from_secs(5))
6285 .unwrap();
6286 return;
6287 }
6288 let output = std::process::Command::new(std::env::current_exe().unwrap())
6289 .args([
6290 "--exact",
6291 "bitmap_teardown_tests::releasing_during_bitmap_registry_teardown_does_not_abort",
6292 "--nocapture",
6293 ])
6294 .env(CHILD, "1")
6295 .output()
6296 .unwrap();
6297 assert!(
6298 output.status.success(),
6299 "{}",
6300 String::from_utf8_lossy(&output.stderr)
6301 );
6302 }
6303}
6304
6305#[cfg(test)]
6306mod input_tests {
6307 use super::{contacts, key_phase, pointer_kind};
6308 use day_spec::{KeyPhase, Point, PointerKind, TouchPhase};
6309
6310 #[test]
6311 fn contact_numbers_decode_in_order() {
6312 let numbers = [
6313 7.0, 0.0, 10.0, 20.0, 0.5, 0.0, 9.0, 2.0, 1.0, 2.0, 1.0, 2.0, 0.0, 4.0, 3.0, 4.0, 1.0, 1.0, 1.0, 3.0, ];
6318 let touches = contacts(&numbers);
6319 assert_eq!(touches.len(), 3);
6320 assert_eq!(touches[0].id, 7);
6321 assert_eq!(touches[0].phase, TouchPhase::Began);
6322 assert_eq!(touches[0].location, Point::new(10.0, 20.0));
6323 assert!((touches[0].pressure - 0.5).abs() < f64::EPSILON);
6324 assert_eq!(touches[0].kind, PointerKind::Touch);
6325 assert_eq!(touches[1].phase, TouchPhase::Stationary);
6326 assert_eq!(touches[1].kind, PointerKind::Stylus);
6327 assert_eq!(touches[2].phase, TouchPhase::Cancelled);
6328 assert_eq!(touches[2].kind, PointerKind::Mouse);
6329 }
6330
6331 #[test]
6332 fn wire_codes_name_phases_and_devices() {
6333 assert_eq!(key_phase(0), KeyPhase::Down);
6334 assert_eq!(key_phase(1), KeyPhase::Repeat);
6335 assert_eq!(key_phase(2), KeyPhase::Up);
6336 assert_eq!(pointer_kind(0), PointerKind::Touch);
6337 assert_eq!(pointer_kind(1), PointerKind::Mouse);
6338 assert_eq!(pointer_kind(2), PointerKind::Stylus);
6339 }
6340}
6341
6342#[cfg(test)]
6343mod surface_tests {
6344 use super::{dynamic, is_styled_surface, surface_is_dynamic, surface_spec};
6345 use day_spec::props::ContainerProps;
6346 use day_spec::{Border, Color, Corners, LinearGradient, Shadow, UnitPoint};
6347
6348 #[test]
6350 fn only_new_fields_take_the_painted_path() {
6351 let plain = ContainerProps {
6352 fill: Some(Color::rgb(1.0, 0.0, 0.0).into()),
6353 corner_radius: 8.0,
6354 clips: true,
6355 ..ContainerProps::default()
6356 };
6357 assert!(!is_styled_surface(&plain));
6358 assert!(!is_styled_surface(&ContainerProps {
6360 corner_radius: 0.0,
6361 corners: Corners::TOP,
6362 ..plain.clone()
6363 }));
6364 assert!(is_styled_surface(&ContainerProps {
6365 corners: Corners::TOP,
6366 ..plain.clone()
6367 }));
6368 assert!(is_styled_surface(&ContainerProps {
6369 border: Some(Border::new(Color::WHITE, 1.0)),
6370 ..plain.clone()
6371 }));
6372 assert!(is_styled_surface(&ContainerProps {
6373 shadow: Some(Shadow::new(Color::WHITE, 4.0)),
6374 ..plain.clone()
6375 }));
6376 assert!(is_styled_surface(&ContainerProps {
6377 fill: Some(LinearGradient::vertical(Color::WHITE, Color::WHITE).into()),
6378 ..plain.clone()
6379 }));
6380 assert!(is_styled_surface(&ContainerProps {
6382 fill: Some(
6383 day_spec::RadialGradient::new(UnitPoint::CENTER, 0.5, [(0.0, Color::WHITE)]).into()
6384 ),
6385 ..plain.clone()
6386 }));
6387 assert!(is_styled_surface(&ContainerProps {
6388 fill: Some(
6389 day_spec::ConicGradient::centered(day_spec::Angle::ZERO, [(0.0, Color::WHITE)])
6390 .into()
6391 ),
6392 ..plain
6393 }));
6394 }
6395
6396 #[test]
6399 fn radial_and_conic_fills_reach_the_shim() {
6400 let red = Color::rgb(1.0, 0.0, 0.0);
6401 let blue = Color::rgb(0.0, 0.0, 1.0);
6402 let radial = ContainerProps {
6403 fill: Some(
6404 day_spec::RadialGradient::new(
6405 UnitPoint::new(0.25, 0.75),
6406 0.4,
6407 [(0.0, red), (1.0, blue)],
6408 )
6409 .into(),
6410 ),
6411 ..ContainerProps::default()
6412 };
6413 let (spec, stops) = surface_spec(&radial);
6414 assert_eq!(spec[19..24], [2.0, 0.25, 0.75, 0.4, 0.0]);
6415 assert_eq!(stops, [0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0]);
6416 let conic = ContainerProps {
6417 fill: Some(
6418 day_spec::ConicGradient::new(
6419 UnitPoint::CENTER,
6420 day_spec::Angle::rad(std::f64::consts::FRAC_PI_2),
6421 [(0.0, red), (0.5, blue)],
6422 )
6423 .into(),
6424 ),
6425 ..ContainerProps::default()
6426 };
6427 let (spec, stops) = surface_spec(&conic);
6428 assert_eq!(spec[19..22], [3.0, 0.5, 0.5]);
6429 assert!((spec[22] - 90.0).abs() < 1e-9);
6430 assert_eq!(stops.len(), 10);
6431 assert_eq!(spec[0..4], [0.0, 0.0, 0.0, 0.0]);
6432 }
6433
6434 #[test]
6436 fn a_surface_follows_the_appearance_only_with_a_dynamic_ink() {
6437 let fixed = ContainerProps {
6438 fill: Some(Color::WHITE.into()),
6439 border: Some(Border::new(Color::WHITE, 1.0)),
6440 ..ContainerProps::default()
6441 };
6442 assert!(!surface_is_dynamic(&fixed));
6443 let pair = day_spec::Ink::adaptive(Color::WHITE, Color::BLACK);
6444 assert!(surface_is_dynamic(&ContainerProps {
6445 fill: Some(pair.into()),
6446 ..fixed.clone()
6447 }));
6448 assert!(surface_is_dynamic(&ContainerProps {
6449 border: Some(Border::new(day_spec::SystemColor::Separator, 1.0)),
6450 ..fixed.clone()
6451 }));
6452 assert!(surface_is_dynamic(&ContainerProps {
6453 fill: Some(LinearGradient::vertical(Color::WHITE, pair).into()),
6454 ..fixed
6455 }));
6456 assert!(dynamic(Some(Color::WHITE.into())).is_none());
6457 assert_eq!(dynamic(Some(pair)), Some(pair));
6458 }
6459
6460 #[test]
6462 fn spec_slots_match_the_shim() {
6463 let props = ContainerProps {
6465 fill: Some(
6466 LinearGradient::vertical(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0))
6467 .into(),
6468 ),
6469 corner_radius: 12.0,
6470 corners: Corners::TOP_LEFT | Corners::BOTTOM_RIGHT,
6471 border: Some(Border::new(Color::rgba(0.5, 0.6, 0.7, 0.8), 2.0)),
6472 shadow: Some(Shadow::new(Color::rgba(0.0, 0.0, 0.0, 0.25), 16.0).offset(1.0, 6.0)),
6473 clips: false,
6474 role: None,
6475 };
6476 let (spec, stops) = surface_spec(&props);
6477 assert_eq!(spec[0..4], [0.0, 0.0, 0.0, 0.0]);
6478 assert_eq!(spec[4..7], [12.0, 5.0, 0.0]);
6479 assert_eq!(spec[7..12], [0.5, 0.6, 0.7, 0.8, 2.0]);
6480 assert_eq!(spec[12..19], [0.0, 0.0, 0.0, 0.25, 16.0, 1.0, 6.0]);
6481 let Some(day_spec::Paint::Linear(g)) = &props.fill else {
6482 unreachable!("the gradient set above")
6483 };
6484 assert_eq!(spec[19..24], [1.0, g.start.x, g.start.y, g.end.x, g.end.y]);
6485 assert_eq!(stops.len(), 10);
6486 assert_eq!(stops[0..5], [0.0, 1.0, 0.0, 0.0, 1.0]);
6487 assert_eq!(stops[5..10], [1.0, 0.0, 0.0, 1.0, 1.0]);
6488
6489 let (spec, stops) = surface_spec(&ContainerProps::default());
6491 assert_eq!(stops, [] as [f64; 0]);
6492 assert!(
6493 spec.iter()
6494 .enumerate()
6495 .all(|(i, v)| (i == 5) == (*v != 0.0))
6496 );
6497 assert_eq!(spec[5], 15.0);
6498 }
6499}
6500
6501#[cfg(test)]
6502mod list_rows_tests {
6503 use super::{RowWork, row_align_code, supplement_rows};
6504 use day_spec::props::RowDelta;
6505 use std::os::raw::c_int;
6506
6507 #[test]
6510 fn row_work_merges_in_arrival_order() {
6511 let a = RowWork::Splice(vec![RowDelta::Insert(0)]);
6512 let b = RowWork::Splice(vec![RowDelta::Move(3, 0), RowDelta::Remove(2)]);
6513 assert_eq!(
6514 RowWork::merge(Some(a), b),
6515 RowWork::Splice(vec![
6516 RowDelta::Insert(0),
6517 RowDelta::Move(3, 0),
6518 RowDelta::Remove(2)
6519 ])
6520 );
6521 let splice = || RowWork::Splice(vec![RowDelta::Insert(1)]);
6522 assert_eq!(RowWork::merge(None, splice()), splice());
6523 assert_eq!(
6524 RowWork::merge(Some(RowWork::Reload), splice()),
6525 RowWork::Reload
6526 );
6527 assert_eq!(
6528 RowWork::merge(Some(splice()), RowWork::Reload),
6529 RowWork::Reload
6530 );
6531 assert_eq!(RowWork::merge(None, RowWork::Reload), RowWork::Reload);
6532 }
6533
6534 #[test]
6536 fn row_work_triples() {
6537 let deltas = [
6538 RowDelta::Insert(4),
6539 RowDelta::Remove(1),
6540 RowDelta::Move(5, 2),
6541 ];
6542 assert_eq!(RowWork::triples(&deltas), vec![0, 4, 0, 1, 1, 0, 2, 5, 2]);
6543 assert_eq!(RowWork::triples(&[]), Vec::<c_int>::new());
6544 }
6545
6546 #[test]
6549 fn supplement_rows_at_both_ends() {
6550 let rows = supplement_rows(10, &|i| !(2..8).contains(&i));
6552 assert_eq!(rows, vec![0, 1, 8, 9]);
6553 assert_eq!(supplement_rows(3, &|_| true), vec![0, 1, 2]);
6554 assert_eq!(supplement_rows(5, &|_| false), Vec::<usize>::new());
6555 assert_eq!(supplement_rows(0, &|_| true), Vec::<usize>::new());
6556 assert_eq!(supplement_rows(4, &|i| i == 3), vec![3]);
6558 let asked = std::cell::Cell::new(0);
6560 let rows = supplement_rows(1_000_000, &|i| {
6561 asked.set(asked.get() + 1);
6562 i == 0 || i == 999_999
6563 });
6564 assert_eq!(rows, vec![0, 999_999]);
6565 assert!(asked.get() <= 4);
6566 }
6567
6568 #[test]
6569 fn row_align_codes_match_the_shim() {
6570 use day_spec::RowAlign;
6571 assert_eq!(row_align_code(RowAlign::Nearest), 0);
6572 assert_eq!(row_align_code(RowAlign::Start), 1);
6573 assert_eq!(row_align_code(RowAlign::Center), 2);
6574 assert_eq!(row_align_code(RowAlign::End), 3);
6575 }
6576}
6577
6578#[cfg(test)]
6579mod cell_pool_tests {
6580 use super::{CellPool, LIST_OVERSCAN};
6581
6582 fn sync(pool: &mut CellPool, band: std::ops::Range<usize>, next: &mut usize) -> Vec<usize> {
6585 let (parked, need) = pool.retarget(band);
6586 for row in need {
6587 let cell = pool.take_free(false).unwrap_or_else(|| {
6588 *next += 1;
6589 *next
6590 });
6591 pool.bind(row, cell);
6592 }
6593 parked
6594 }
6595
6596 fn sync_sectioned(
6598 pool: &mut CellPool,
6599 band: std::ops::Range<usize>,
6600 every: usize,
6601 next: &mut usize,
6602 ) -> (Vec<usize>, usize) {
6603 let (parked, need) = pool.retarget(band);
6604 let mut flips = 0;
6605 for row in need {
6606 let header = row % every == 0;
6607 let cell = pool.take_free(header).unwrap_or_else(|| {
6608 *next += 1;
6609 *next
6610 });
6611 if *next != cell && pool.headers.contains(&cell) != header {
6612 flips += 1;
6613 }
6614 pool.bind(row, cell);
6615 pool.set_kind(cell, header);
6616 }
6617 (parked, flips)
6618 }
6619
6620 #[test]
6621 fn a_scroll_reuses_the_cells_that_left() {
6622 let mut pool = CellPool::default();
6623 let mut next = 0;
6624 assert_eq!(sync(&mut pool, 0..10, &mut next), [] as [usize; 0]);
6625 assert_eq!(pool.len(), 10);
6626 let parked = sync(&mut pool, 5..15, &mut next);
6628 assert_eq!(parked.len(), 5);
6629 assert_eq!(pool.len(), 10);
6630 assert_eq!(next, 10);
6631 for row in 5..15 {
6632 assert!(pool.bound.contains_key(&row), "row {row} has a cell");
6633 }
6634 for cell in parked {
6635 assert!(
6636 pool.row_of(cell).is_some(),
6637 "the parked cell was re-bound to a new row"
6638 );
6639 }
6640 }
6641
6642 #[test]
6643 fn the_pool_stays_a_window_wide_across_a_long_scroll() {
6644 let mut pool = CellPool::default();
6645 let mut next = 0;
6646 let window = 12 + 2 * LIST_OVERSCAN;
6647 let mut top = 0usize;
6648 while top + window < 100_000 {
6649 sync(&mut pool, top..top + window, &mut next);
6650 assert!(pool.len() <= window, "pool grew to {} cells", pool.len());
6651 top += 7;
6652 }
6653 sync(&mut pool, 90_000..90_000 + window, &mut next);
6655 assert_eq!(pool.len(), window);
6656 assert_eq!(next, window);
6657 }
6658
6659 #[test]
6660 fn a_shrunk_band_parks_the_rest_and_keeps_them_spare() {
6661 let mut pool = CellPool::default();
6662 let mut next = 0;
6663 sync(&mut pool, 0..20, &mut next);
6664 let parked = sync(&mut pool, 0..5, &mut next);
6665 assert_eq!(parked.len(), 15);
6666 assert_eq!(pool.bound.len(), 5);
6667 assert_eq!(pool.free.len(), 15);
6668 for cell in &parked {
6669 assert_eq!(pool.row_of(*cell), None);
6670 }
6671 sync(&mut pool, 0..20, &mut next);
6673 assert_eq!(pool.free.len(), 0);
6674 assert_eq!(next, 20);
6675 }
6676
6677 #[test]
6678 fn header_rows_take_header_cells_and_item_rows_item_cells() {
6679 let mut pool = CellPool::default();
6680 let mut next = 0;
6681 let every = 10;
6682 let window = 12 + 2 * LIST_OVERSCAN;
6683 let headers = window.div_ceil(every) + 1;
6686 let mut top = 0usize;
6687 while top + window < 10_000 {
6688 let (_, flips) = sync_sectioned(&mut pool, top..top + window, every, &mut next);
6689 assert_eq!(flips, 0, "a cell changed kind at top {top}");
6690 assert!(
6691 pool.len() <= window + headers,
6692 "pool grew to {} cells",
6693 pool.len()
6694 );
6695 top += 3;
6696 }
6697 let before = next;
6699 sync_sectioned(&mut pool, 9_000..9_000 + window, every, &mut next);
6700 assert_eq!(next, before);
6701 }
6702
6703 #[test]
6704 fn retarget_is_idempotent() {
6705 let mut pool = CellPool::default();
6706 let mut next = 0;
6707 sync(&mut pool, 3..9, &mut next);
6708 let before: Vec<(usize, usize)> = pool.bound.iter().map(|(r, c)| (*r, *c)).collect();
6709 let parked = sync(&mut pool, 3..9, &mut next);
6710 assert_eq!(parked, [] as [usize; 0]);
6711 let after: Vec<(usize, usize)> = pool.bound.iter().map(|(r, c)| (*r, *c)).collect();
6712 assert_eq!(before, after);
6713 }
6714}
6715
6716#[cfg(test)]
6717mod text_tests {
6718 use super::{css_hex, font_params, label_align, qt_label_markup};
6719 use day_spec::props::TextAlign;
6720 use day_spec::{Color, Decoration, DecorationStyle, Font, FontSpec, MarkupDialect, TextRun};
6721
6722 fn run(range: std::ops::Range<usize>) -> TextRun {
6723 TextRun {
6724 range,
6725 ..TextRun::default()
6726 }
6727 }
6728
6729 #[test]
6730 fn runs_without_a_styled_underline_are_the_shared_markup() {
6731 let text = "a < b and c & d\nnext";
6732 let mut bold = run(2..5);
6733 bold.font.weight = Some(day_spec::FontWeight::Bold);
6734 let mut under = run(10..11);
6735 under.underline = Some(Decoration::SINGLE.color(Color::rgb(1.0, 0.0, 0.0)));
6736 let runs = [bold, under];
6737 assert_eq!(
6738 qt_label_markup(text, &runs, 13.0),
6739 day_spec::runs_to_markup(text, &runs, MarkupDialect::QtHtml, 13.0)
6740 );
6741 }
6742
6743 #[test]
6744 fn a_styled_underline_travels_as_qt_css_around_the_run() {
6745 let text = "Check unknown now";
6746 let mut wavy = run(6..13);
6747 wavy.underline = Some(Decoration::wavy().color(Color::rgb(1.0, 0.0, 0.0)));
6748 let html = qt_label_markup(text, &[wavy], 13.0);
6749 assert_eq!(
6750 html,
6751 "Check <span style=\"text-underline-style:wave;text-decoration-color:#ff0000;\">\
6752 unknown</span> now"
6753 );
6754 let mut dotted = run(0..5);
6755 dotted.underline = Some(Decoration::dotted());
6756 let mut double = run(6..13);
6757 double.underline = Some(Decoration::double());
6758 let html = qt_label_markup(text, &[dotted, double], 13.0);
6759 assert!(html.starts_with("<span style=\"text-underline-style:dotted;\">Check</span> "));
6760 assert!(html.contains("<span style=\"text-underline-style:solid;\">unknown</span>"));
6761 assert!(!html.contains("<u>"));
6762 }
6763
6764 #[test]
6765 fn a_strikethrough_color_is_dropped_and_the_line_kept() {
6766 let mut struck = run(0..6);
6767 struck.strikethrough =
6768 Some(Decoration::new(DecorationStyle::Double).color(Color::rgb(1.0, 0.0, 0.0)));
6769 let html = qt_label_markup("Struck", &[struck], 13.0);
6770 assert_eq!(html, "<s>Struck</s>");
6771 assert_eq!(css_hex(Color::rgb(0.0, 0.5, 1.0)), "#007fff");
6772 }
6773
6774 #[test]
6775 fn a_run_asks_for_no_synthesized_small_caps() {
6776 let mut caps = run(0..4);
6777 caps.font.small_caps = true;
6778 assert_eq!(qt_label_markup("Caps", &[caps], 13.0), "Caps");
6779 }
6780
6781 #[test]
6782 fn a_run_that_misses_the_text_is_skipped() {
6783 let html = qt_label_markup("short", &[run(2..40)], 13.0);
6784 assert_eq!(html, "short");
6785 }
6786
6787 #[test]
6788 fn the_font_carries_scale_and_features() {
6789 let spec = FontSpec {
6790 style: Font::System(20.0),
6791 scale: 1.5,
6792 tabular: true,
6793 small_caps: true,
6794 oldstyle_figures: true,
6795 ..FontSpec::default()
6796 };
6797 let f = font_params(spec);
6798 assert!((f.pt - 30.0).abs() < 1e-9);
6799 assert_eq!((f.tabular, f.small_caps, f.oldstyle), (1, 1, 1));
6800 assert_eq!(label_align(TextAlign::Justified), 3);
6801 assert_eq!(label_align(TextAlign::Trailing), 2);
6802 }
6803}
6804
6805#[cfg(test)]
6806mod anim_tests {
6807 use super::*;
6808
6809 #[test]
6810 fn a_spec_lowers_to_its_delay_cycles_and_direction() {
6811 let run = QtAnim::new(&AnimSpec::linear(600).delay(900));
6812 assert_eq!((run.delay_ms, run.duration_ms, run.cycles), (900, 600, 1));
6813 assert!(!run.autoreverse);
6814 assert_eq!(run.keys, vec![0.0, 1.0]);
6816 let run = QtAnim::new(&AnimSpec::linear(800).repeat(2, true));
6817 assert_eq!((run.cycles, run.autoreverse), (3, true));
6818 let run = QtAnim::new(&AnimSpec::linear(600).repeat_forever(true));
6819 assert_eq!(run.cycles, -1);
6820 }
6821
6822 #[test]
6823 fn a_spring_carries_its_overshooting_samples() {
6824 let spec = AnimSpec::spring(0.9, 0.25);
6825 let run = QtAnim::new(&spec);
6826 assert_eq!(run.keys.len(), spec.keyframes().len());
6827 assert_eq!(run.keys.first().copied(), Some(0.0));
6828 assert_eq!(run.keys.last().copied(), Some(1.0));
6829 assert!(run.keys.iter().copied().fold(0.0, f64::max) > 1.35);
6831 }
6832
6833 #[test]
6834 fn an_easing_curve_is_sampled_exactly() {
6835 let spec = AnimSpec::ease_in_out(1000);
6836 let run = QtAnim::new(&spec);
6837 let n = run.keys.len() - 1;
6838 let mid = run.keys[n / 2];
6839 assert!((mid - spec.cycle_progress(0.5)).abs() < 1e-12);
6841 let quarter = run.keys[n / 4];
6842 let t = (n / 4) as f64 / n as f64;
6843 assert!((quarter - t * t * (3.0 - 2.0 * t)).abs() < 1e-12);
6844 }
6845
6846 #[test]
6847 fn the_shim_sees_the_samples_and_none_is_null() {
6848 let spec = AnimSpec::spring(0.4, 0.8).delay(50);
6849 let run = QtAnim::new(&spec);
6850 let raw = run.raw();
6851 assert_eq!(raw.n_keys as usize, run.keys.len());
6852 assert_eq!(raw.keys, run.keys.as_ptr());
6853 assert_eq!(raw.delay_ms, 50);
6854 assert!(with_qt_anim(None, <*const ffi::DayQtAnim>::is_null));
6855 assert!(!with_qt_anim(Some(&spec), <*const ffi::DayQtAnim>::is_null));
6856 }
6857}