Skip to main content

yse_ui/dsl/
mod.rs

1//! Laminar-style retained widget composition.
2//!
3//! Widget constructors return inert [`View`] descriptions. A view is mounted
4//! once with [`Window::mount`]; reactive modifiers install subscriptions owned
5//! by the resulting widget tree.
6//!
7//! ```no_run
8//! use yse_model::Var;
9//! use yse_ui::*;
10//!
11//! let app = Application::init();
12//! let window = Window::new();
13//! let count = Var::new(0u32);
14//! let caption = count.signal().map(|count| format!("Count: {count}"));
15//! window.mount(column((
16//!     label(caption),
17//!     row((
18//!         spacer(),
19//!         button("Increment")
20//!             .on_click(clone!(count => move |_| count.set(*count.value() + 1))),
21//!     )),
22//! )));
23//! ```
24
25use crate::bridge as ffi;
26use crate::component::Component;
27use crate::{
28    Button, CheckBox, ComboBox, DateEdit, DateTimeEdit, DiskMap, Label, LineChart, LineEdit,
29    ListView, Menu, ProgressBar, SelectionBridge, Slider, SpinBox, StackedWidget, StringListModel,
30    StringTableModel, TabWidget, TableView, TimeEdit, TreeModel, TreeView, Window,
31};
32use std::cell::RefCell;
33use std::rc::Rc;
34use yse_model::Subscription;
35use yse_model::{Signal, Var};
36
37/// A retained widget description that can be mounted into a window.
38///
39/// This is Yse's equivalent of a Laminar `ReactiveElement`: constructors
40/// return inert values, modifiers configure those values, and [`Window::mount`]
41/// performs the Qt side effects in one place.
42pub trait View {
43    /// Handles returned after this view is mounted.
44    type Output;
45
46    /// Mount this view below `context`.
47    #[doc(hidden)]
48    fn mount_in(self, context: &MountContext) -> Self::Output;
49}
50
51/// Parent information supplied while a [`View`] is mounted.
52#[doc(hidden)]
53pub struct MountContext {
54    parent: Rc<Component>,
55    is_layout: bool,
56}
57
58impl MountContext {
59    fn child(&self, ptr: *mut ffi::Widget) -> Rc<Component> {
60        let child = unsafe { Component::from_raw_child(ptr, &self.parent) };
61        if self.is_layout {
62            unsafe { ffi::layout_add(self.parent.raw(), child.raw()) };
63        }
64        child
65    }
66}
67
68/// A static or reactive string property.
69#[doc(hidden)]
70pub enum TextValue {
71    Static(String),
72    Reactive(Signal<String>),
73}
74
75/// Convert a static string or a `Signal<String>` into a reactive property.
76pub trait IntoTextValue {
77    /// Perform the conversion.
78    fn into_text_value(self) -> TextValue;
79}
80
81impl IntoTextValue for String {
82    fn into_text_value(self) -> TextValue {
83        TextValue::Static(self)
84    }
85}
86
87impl IntoTextValue for &str {
88    fn into_text_value(self) -> TextValue {
89        TextValue::Static(self.to_owned())
90    }
91}
92
93impl IntoTextValue for Signal<String> {
94    fn into_text_value(self) -> TextValue {
95        TextValue::Reactive(self)
96    }
97}
98
99/// A static or reactive boolean property.
100#[doc(hidden)]
101pub enum BoolValue {
102    Static(bool),
103    Reactive(Signal<bool>),
104}
105
106/// Convert a boolean or `Signal<bool>` into a reactive property.
107pub trait IntoBoolValue {
108    /// Perform the conversion.
109    fn into_bool_value(self) -> BoolValue;
110}
111
112impl IntoBoolValue for bool {
113    fn into_bool_value(self) -> BoolValue {
114        BoolValue::Static(self)
115    }
116}
117
118impl IntoBoolValue for Signal<bool> {
119    fn into_bool_value(self) -> BoolValue {
120        BoolValue::Reactive(self)
121    }
122}
123
124/// A static or reactive integer property.
125#[doc(hidden)]
126pub enum IntValue {
127    Static(i32),
128    Reactive(Signal<i32>),
129    Controlled(Var<i32>),
130}
131
132/// Convert an `i32`, `Signal<i32>`, or `Var<i32>` into a reactive property.
133pub trait IntoIntValue {
134    /// Perform the conversion.
135    fn into_int_value(self) -> IntValue;
136}
137
138impl IntoIntValue for i32 {
139    fn into_int_value(self) -> IntValue {
140        IntValue::Static(self)
141    }
142}
143
144impl IntoIntValue for Signal<i32> {
145    fn into_int_value(self) -> IntValue {
146        IntValue::Reactive(self)
147    }
148}
149
150impl IntoIntValue for Var<i32> {
151    fn into_int_value(self) -> IntValue {
152        IntValue::Controlled(self)
153    }
154}
155
156enum LayoutAxis {
157    Row,
158    Column,
159}
160
161/// A row or column whose children are mounted in tuple order.
162pub struct LayoutView<C> {
163    axis: LayoutAxis,
164    children: C,
165}
166
167/// Describe a horizontal layout.
168pub fn row<C: View>(children: C) -> LayoutView<C> {
169    LayoutView {
170        axis: LayoutAxis::Row,
171        children,
172    }
173}
174
175/// Describe a vertical layout.
176pub fn column<C: View>(children: C) -> LayoutView<C> {
177    LayoutView {
178        axis: LayoutAxis::Column,
179        children,
180    }
181}
182
183impl<C: View> View for LayoutView<C> {
184    type Output = C::Output;
185
186    fn mount_in(self, context: &MountContext) -> Self::Output {
187        let ptr = match self.axis {
188            LayoutAxis::Row => unsafe { ffi::widget_new_row(context.parent.raw()) },
189            LayoutAxis::Column => unsafe { ffi::widget_new_column(context.parent.raw()) },
190        };
191        let layout = context.child(ptr);
192        self.children.mount_in(&MountContext {
193            parent: layout,
194            is_layout: true,
195        })
196    }
197}
198
199mod views;
200pub use views::{
201    ButtonView, CheckBoxView, ComboBoxView, LabelView, LineEditView, ProgressBarView, SliderView,
202    SpinBoxView, button, checkbox, combo_box, label, line_edit, progress_bar, slider, spin_box,
203};
204/// A stretchable empty item that consumes spare layout space.
205pub struct SpacerView;
206
207/// Describe a stretch spacer.
208pub fn spacer() -> SpacerView {
209    SpacerView
210}
211
212impl View for SpacerView {
213    type Output = ();
214
215    fn mount_in(self, context: &MountContext) {
216        assert!(context.is_layout, "spacers must live inside a layout");
217        unsafe { ffi::layout_add_spacer(context.parent.raw()) };
218    }
219}
220
221impl View for () {
222    type Output = ();
223
224    fn mount_in(self, _context: &MountContext) {}
225}
226
227macro_rules! tuple_views {
228    ($(($($view:ident),+)),+ $(,)?) => {$(
229        impl<$($view: View),+> View for ($($view,)+) {
230            type Output = ($($view::Output,)+);
231
232            #[allow(non_snake_case)]
233            fn mount_in(self, context: &MountContext) -> Self::Output {
234                let ($($view,)+) = self;
235                ($($view.mount_in(context),)+)
236            }
237        }
238    )+};
239}
240
241tuple_views! {
242    (A),
243    (A, B),
244    (A, B, C),
245    (A, B, C, D),
246    (A, B, C, D, E),
247    (A, B, C, D, E, F),
248    (A, B, C, D, E, F, G),
249    (A, B, C, D, E, F, G, H),
250}
251
252#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253enum ParentKind {
254    Window,
255    Layout,
256}
257
258/// A scoped builder for a retained Qt widget tree.
259///
260/// A `Ui` value can only create widgets below its own parent. Use a nested
261/// `row` or `column` before creating leaf widgets; this mirrors Qt's layout
262/// requirement in the public API rather than relying on ambient state.
263pub struct Ui {
264    kind: ParentKind,
265    parent: Rc<Component>,
266}
267
268impl Ui {
269    fn layout_parent(&self) -> &Rc<Component> {
270        assert_eq!(
271            self.kind,
272            ParentKind::Layout,
273            "leaf widgets must live inside a row() or column(); the top of a window tree should be a layout"
274        );
275        &self.parent
276    }
277
278    fn leaf(&self, ptr: *mut ffi::Widget) -> Rc<Component> {
279        let parent = self.layout_parent();
280        let inner = unsafe { Component::from_raw_child(ptr, parent) };
281        unsafe { ffi::layout_add(parent.raw(), inner.raw()) };
282        inner
283    }
284
285    fn layout<R, F: FnOnce(&Ui) -> R>(
286        &self,
287        new_container: unsafe fn(*mut ffi::Widget) -> *mut ffi::Widget,
288        f: F,
289    ) -> R {
290        let inner =
291            unsafe { Component::from_raw_child(new_container(self.parent.raw()), &self.parent) };
292        if self.kind == ParentKind::Layout {
293            unsafe { ffi::layout_add(self.parent.raw(), inner.raw()) };
294        }
295        f(&Ui {
296            kind: ParentKind::Layout,
297            parent: inner,
298        })
299    }
300
301    /// Nest children into a horizontal row.
302    pub fn row<R, F: FnOnce(&Ui) -> R>(&self, f: F) -> R {
303        self.layout(ffi::widget_new_row, f)
304    }
305
306    /// Nest children into a vertical column.
307    pub fn column<R, F: FnOnce(&Ui) -> R>(&self, f: F) -> R {
308        self.layout(ffi::widget_new_column, f)
309    }
310
311    /// Create a label in this layout.
312    pub fn label(&self, text: impl Into<String>) -> Label {
313        let parent = self.layout_parent();
314        let inner = self.leaf(unsafe { ffi::widget_new_label(&text.into(), parent.raw()) });
315        Label { inner }
316    }
317
318    /// Create a button in this layout.
319    pub fn button(&self, text: impl Into<String>) -> Button {
320        let parent = self.layout_parent();
321        let inner = self.leaf(unsafe { ffi::widget_new_button(&text.into(), parent.raw()) });
322        Button { inner }
323    }
324
325    /// Create a line edit in this layout.
326    pub fn line_edit(&self, text: impl Into<String>) -> LineEdit {
327        let parent = self.layout_parent();
328        let inner = self.leaf(unsafe { ffi::widget_new_line_edit(&text.into(), parent.raw()) });
329        LineEdit { inner }
330    }
331
332    /// Create a native Qt date/time editor with a calendar popup.
333    pub fn date_time_edit(&self, iso_datetime: impl Into<String>) -> DateTimeEdit {
334        let parent = self.layout_parent();
335        let inner =
336            self.leaf(unsafe { ffi::widget_new_datetime_edit(&iso_datetime.into(), parent.raw()) });
337        DateTimeEdit { inner }
338    }
339
340    /// Create a native Qt calendar date editor.
341    pub fn date_edit(&self, iso_date: impl Into<String>) -> DateEdit {
342        let parent = self.layout_parent();
343        let inner = self.leaf(unsafe { ffi::widget_new_date_edit(&iso_date.into(), parent.raw()) });
344        DateEdit { inner }
345    }
346
347    /// Create a native Qt time editor with hour and minute spin controls.
348    pub fn time_edit(&self, iso_time: impl Into<String>) -> TimeEdit {
349        let parent = self.layout_parent();
350        let inner = self.leaf(unsafe { ffi::widget_new_time_edit(&iso_time.into(), parent.raw()) });
351        TimeEdit { inner }
352    }
353
354    /// Create a proportional disk-usage overview.
355    pub fn disk_map(&self) -> DiskMap {
356        let parent = self.layout_parent();
357        let inner = self.leaf(unsafe { ffi::widget_new_disk_map(parent.raw()) });
358        DiskMap { inner }
359    }
360
361    /// Create a checkbox in this layout.
362    pub fn checkbox(&self, text: impl Into<String>) -> CheckBox {
363        let parent = self.layout_parent();
364        let inner = self.leaf(unsafe { ffi::widget_new_checkbox(&text.into(), parent.raw()) });
365        CheckBox { inner }
366    }
367
368    /// Create a combo box with `items` in this layout.
369    pub fn combo_box<I, S>(&self, items: I) -> ComboBox
370    where
371        I: IntoIterator<Item = S>,
372        S: Into<String>,
373    {
374        let parent = self.layout_parent();
375        let inner = self.leaf(unsafe {
376            ffi::widget_new_combo(items.into_iter().map(Into::into).collect(), parent.raw())
377        });
378        ComboBox { inner }
379    }
380
381    /// Create a numeric spinner (default range `0..=100`) in this layout.
382    pub fn spin_box(&self, value: i32) -> SpinBox {
383        let parent = self.layout_parent();
384        let inner = self.leaf(unsafe { ffi::widget_new_spin_box(0, 100, value, parent.raw()) });
385        SpinBox { inner }
386    }
387
388    /// Create a horizontal slider (default range `0..=100`) in this layout.
389    pub fn slider(&self, value: i32) -> Slider {
390        let parent = self.layout_parent();
391        let inner = self.leaf(unsafe { ffi::widget_new_slider(0, 100, value, parent.raw()) });
392        Slider { inner }
393    }
394
395    /// Create a progress bar (default range `0..=100`) in this layout.
396    pub fn progress_bar(&self, value: i32) -> ProgressBar {
397        let parent = self.layout_parent();
398        let inner = self.leaf(unsafe { ffi::widget_new_progress_bar(0, 100, value, parent.raw()) });
399        ProgressBar { inner }
400    }
401
402    /// Create a tabbed container in this layout.
403    pub fn tab_widget(&self) -> TabWidget {
404        let parent = self.layout_parent();
405        let inner = self.leaf(unsafe { ffi::widget_new_tab_widget(parent.raw()) });
406        TabWidget { inner }
407    }
408
409    /// Create a stacked content widget in this layout.
410    pub fn stacked_widget(&self) -> StackedWidget {
411        let parent = self.layout_parent();
412        let inner = self.leaf(unsafe { ffi::widget_new_stacked_widget(parent.raw()) });
413        StackedWidget { inner }
414    }
415
416    /// Create a painted line chart in this layout.
417    pub fn line_chart(&self) -> LineChart {
418        let parent = self.layout_parent();
419        let inner = self.leaf(unsafe { ffi::widget_new_line_chart(parent.raw()) });
420        LineChart { inner }
421    }
422
423    /// Add a stretch spacer to this layout.
424    pub fn spacer(&self) {
425        let parent = self.layout_parent();
426        unsafe { ffi::layout_add_spacer(parent.raw()) };
427    }
428
429    /// Create a list view bound to `model` in this layout.
430    pub fn list_view(&self, model: &StringListModel) -> ListView {
431        let parent = self.layout_parent();
432        let inner = unsafe {
433            Component::from_raw_child(
434                ffi::widget_new_list_view(model.state.model, parent.raw()),
435                parent,
436            )
437        };
438        unsafe { ffi::layout_add(parent.raw(), inner.raw()) };
439        let selection = Rc::new(SelectionBridge {
440            view: inner.raw(),
441            sink: RefCell::new(None),
442            created_on: std::thread::current().id(),
443        });
444        inner.retain(model.state.clone());
445        inner.retain(selection.clone());
446        ListView {
447            inner,
448            model: model.state.clone(),
449            selection,
450        }
451    }
452
453    /// Create a table view bound to `model` in this layout.
454    pub fn table_view(&self, model: &StringTableModel) -> TableView {
455        let parent = self.layout_parent();
456        let inner = unsafe {
457            Component::from_raw_child(
458                ffi::widget_new_table_view(model.state.table, parent.raw()),
459                parent,
460            )
461        };
462        unsafe { ffi::layout_add(parent.raw(), inner.raw()) };
463        let selection = Rc::new(SelectionBridge {
464            view: inner.raw(),
465            sink: RefCell::new(None),
466            created_on: std::thread::current().id(),
467        });
468        inner.retain(model.state.clone());
469        inner.retain(selection.clone());
470        TableView {
471            inner,
472            table: model.state.clone(),
473            selection,
474        }
475    }
476
477    /// Create a tree view bound to `model`.
478    pub fn tree_view(&self, model: &TreeModel) -> TreeView {
479        let parent = self.layout_parent();
480        let inner = unsafe {
481            Component::from_raw_child(
482                ffi::widget_new_tree_view(model.state.tree, parent.raw()),
483                parent,
484            )
485        };
486        unsafe { ffi::layout_add(parent.raw(), inner.raw()) };
487        let selection = Rc::new(SelectionBridge {
488            view: inner.raw(),
489            sink: RefCell::new(None),
490            created_on: std::thread::current().id(),
491        });
492        inner.retain(model.state.clone());
493        inner.retain(selection.clone());
494        TreeView { inner, selection }
495    }
496
497    /// Retain a non-widget subscription until this subtree is destroyed.
498    pub fn own(&self, subscription: Subscription) {
499        self.parent.owner.borrow_mut().add(subscription);
500    }
501}
502
503impl Window {
504    /// Mount a Laminar-style retained view description into this window.
505    pub fn mount<V: View>(&self, view: V) -> V::Output {
506        view.mount_in(&MountContext {
507            parent: self.inner.clone(),
508            is_layout: false,
509        })
510    }
511
512    /// Return the root builder for this window's widget tree.
513    ///
514    /// Start with a [`Ui::row`] or [`Ui::column`]; their closure return values
515    /// let callers retain only the handles needed for imperative operations or
516    /// tests.
517    pub fn ui(&self) -> Ui {
518        Ui {
519            kind: ParentKind::Window,
520            parent: self.inner.clone(),
521        }
522    }
523
524    /// Create a standalone menu (not attached to a menu bar) that can be
525    /// shown as a popup, e.g. for context menus.
526    pub fn menu(&self, title: impl Into<String>) -> Menu {
527        Menu {
528            inner: unsafe {
529                Component::from_raw_child(
530                    ffi::window_menu_new(&title.into(), self.inner.raw()),
531                    &self.inner,
532                )
533            },
534        }
535    }
536}
537
538impl TabWidget {
539    /// Append a tab and return a builder scoped to its page. Widgets created
540    /// through the returned [`Ui`] are owned by the page and released with the
541    /// tab widget.
542    pub fn add_tab(&self, label: impl Into<String>) -> Ui {
543        let page = unsafe {
544            Component::from_raw_child(
545                ffi::tab_widget_add_page(self.inner.raw(), &label.into()),
546                &self.inner,
547            )
548        };
549        Ui {
550            kind: ParentKind::Layout,
551            parent: page,
552        }
553    }
554
555    /// Select the tab at `index` (used by tests and headless smoke runs).
556    pub fn set_current(&self, index: usize) {
557        if self.inner.is_alive() {
558            unsafe { ffi::tab_widget_set_current(self.inner.raw(), index as i32) };
559        }
560    }
561
562    /// The number of tabs.
563    pub fn count(&self) -> usize {
564        unsafe { ffi::tab_widget_count(self.inner.raw()) as usize }
565    }
566}
567
568impl StackedWidget {
569    /// Append a page and return a builder scoped to it.
570    pub fn add_page(&self) -> Ui {
571        let page = unsafe {
572            Component::from_raw_child(ffi::stacked_add_page(self.inner.raw()), &self.inner)
573        };
574        Ui {
575            kind: ParentKind::Layout,
576            parent: page,
577        }
578    }
579
580    /// Show the page at `index`.
581    pub fn set_current(&self, index: usize) {
582        if self.inner.is_alive() {
583            unsafe { ffi::stacked_set_current(self.inner.raw(), index as i32) };
584        }
585    }
586
587    /// The number of pages.
588    pub fn count(&self) -> usize {
589        unsafe { ffi::stacked_count(self.inner.raw()) as usize }
590    }
591}