qtrs 0.4.0

qtrs - A type-safe, builder-pattern-driven Qt6 GUI library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Base widget type and the [`AsWidget`] trait.
//!
//! [`Widget`] wraps [`QWidget`](https://doc.qt.io/qt-6/qwidget.html) —
//! it can serve as a top-level window or as a container for child widgets.
//! The [`AsWidget`] trait is implemented by every widget type in the
//! library so that layouts can accept any widget polymorphically.

use cxx::let_cxx_string;

use crate::ffi;
use crate::Point;

/// Polymorphic access to the underlying `QWidget*` pointer.
///
/// Every widget type in qtrs implements this trait. Layout containers
/// call [`widget_ptr`](AsWidget::widget_ptr) to add widgets without
/// knowing their concrete Rust type.
///
/// # Implementation note
///
/// The trait uses internal `set_has_parent` rather than a shared
/// ownership model. When a widget is added to a layout, the layout
/// calls `set_has_parent(true)` so that the widget's [`Drop`]
/// implementation skips C++ deletion (Qt's parent-child tree will
/// handle it instead).
pub trait AsWidget {
    /// Return the underlying `QWidget*` pointer.
    ///
    /// This is a raw C++ pointer — the caller must ensure the widget
    /// outlives any use of the pointer.
    fn widget_ptr(&self) -> *mut ffi::QWidget;

    /// Mark this widget as having a Qt parent.
    ///
    /// When `has_parent` is true, the [`Drop`] implementation will
    /// **not** delete the C++ object — Qt's parent-child ownership
    /// tree handles cleanup instead. This prevents double-free when
    /// a widget is added to a layout or created with an explicit parent.
    ///
    /// # Memory safety note
    ///
    /// When a widget has a parent and also has connected signals,
    /// the signal closures are **intentionally leaked** on Drop to
    /// prevent use-after-free (the C++ widget may still fire signals
    /// after the Rust wrapper is gone). Keep the Rust wrapper alive
    /// for the widget's full lifetime to avoid this leak.
    fn set_has_parent(&mut self);
}

/// A generic `QWidget` — can be a top-level window or a container.
///
/// `Widget` uses a **builder pattern**: call [`Widget::new`] to obtain
/// a [`Builder`], chain configuration methods, then call [`Builder::build`]
/// (or [`Builder::show`]) to construct the C++ object and return the Rust
/// wrapper.
///
/// # Memory safety
///
/// Every public method asserts (in debug builds) that the internal C++
/// pointer is non-null. This catches use-after-build-failure bugs early.
///
/// # Lifecycle
///
/// When a `Widget` is dropped:
/// - If the widget has **no** Qt parent: signal closures are reclaimed,
///   then the C++ `QWidget` is deleted via `delete`.
/// - If the widget **has** a Qt parent: signal closures are intentionally
///   **leaked** (to prevent use-after-free), and the C++ object is left
///   alone (Qt deletes it when the parent is destroyed).
///
/// # Example
///
/// ```no_run
/// use qtrs::Widget;
///
/// let window = Widget::new()
///     .title("My Window")
///     .size(800, 600)
///     .build();
/// window.show();
/// ```
pub struct Widget {
    ptr: *mut ffi::QWidget,
    has_parent: bool,
    #[allow(dead_code)]
    title: Option<String>,
    #[allow(dead_code)]
    width: i32,
    #[allow(dead_code)]
    height: i32,
    // Signal closure tokens. On Drop:
    //   has_parent=false → reclaimed (safe: C++ object is deleted right after)
    //   has_parent=true  → leaked   (safe: prevents use-after-free)
    signal_handles: Vec<crate::signal::SignalHandle>,
}

// Safety: Widget owns a unique C++ QWidget*. It is not Send/Sync because
// Qt GUI objects must only be accessed from the main thread.
// These negative impls are automatic due to the raw pointer field.

impl Widget {
    /// Start building a new, parentless `QWidget`.
    ///
    /// Returns a [`Builder`] — chain `.title()`, `.size()`, `.parent()`,
    /// then call `.build()` or `.show()`.
    pub fn new() -> Builder {
        Builder::new()
    }

    /// Create a `Widget` from a raw C++ pointer (internal use only).
    #[doc(hidden)]
    pub(crate) fn from_raw(ptr: *mut ffi::QWidget, has_parent: bool) -> Self {
        debug_assert!(!ptr.is_null(), "from_raw called with null pointer");
        Self {
            ptr,
            has_parent,
            title: None,
            width: 0,
            height: 0,
            signal_handles: Vec::new(),
        }
    }

    /// Show this widget (makes it visible).
    ///
    /// For top-level windows, this displays the window. For child widgets
    /// added to a layout, visibility is managed by the parent.
    pub fn show(&self) {
        debug_assert!(!self.ptr.is_null(), "Widget::show on null pointer");
        unsafe { ffi::QWidget_show(self.ptr) };
    }

    /// Hide this widget.
    pub fn hide(&self) {
        debug_assert!(!self.ptr.is_null(), "Widget::hide on null pointer");
        unsafe { ffi::QWidget_hide(self.ptr) };
    }

    /// Set the window title at runtime.
    ///
    /// This is equivalent to
    /// [`QWidget::setWindowTitle`](https://doc.qt.io/qt-6/qwidget.html#windowTitle-prop).
    pub fn set_title(&self, title: &str) {
        debug_assert!(!self.ptr.is_null(), "Widget::set_title on null pointer");
        let_cxx_string!(c_title = title);
        unsafe {
            ffi::QWidget_setWindowTitle(self.ptr, &c_title);
        }
    }

    /// Resize the widget at runtime.
    ///
    /// Width and height are in logical pixels.
    pub fn resize(&self, width: i32, height: i32) {
        debug_assert!(!self.ptr.is_null(), "Widget::resize on null pointer");
        unsafe {
            ffi::QWidget_resize(self.ptr, width, height);
        }
    }

    /// Install a vertical box layout on this widget.
    ///
    /// After calling this, the layout manages the geometry of all child
    /// widgets added to it.
    ///
    /// # Safety note
    ///
    /// The layout must outlive this widget. Dropping the layout first is
    /// fine — children are dropped, then the C++ layout is deleted.
    pub fn set_vlayout(&mut self, layout_ptr: *mut ffi::QVBoxLayout) {
        debug_assert!(!self.ptr.is_null(), "Widget::set_vlayout on null pointer");
        debug_assert!(!layout_ptr.is_null(), "set_vlayout with null layout");
        unsafe {
            ffi::QWidget_setLayout(
                self.ptr,
                layout_ptr as *mut u8 as *mut ffi::QLayout,
            );
        }
    }

    /// Install a grid layout on this widget.
    pub fn set_grid(&mut self, grid: &crate::GridLayout) {
        debug_assert!(!self.ptr.is_null());
        unsafe {
            ffi::QWidget_setLayout(
                self.ptr,
                grid.layout_ptr() as *mut u8 as *mut ffi::QLayout,
            );
        }
    }

    /// Install a horizontal box layout on this widget.
    ///
    /// See [`set_vlayout`](Self::set_vlayout) for details.
    pub fn set_hlayout(&mut self, layout_ptr: *mut ffi::QHBoxLayout) {
        debug_assert!(!self.ptr.is_null(), "Widget::set_hlayout on null pointer");
        debug_assert!(!layout_ptr.is_null(), "set_hlayout with null layout");
        unsafe {
            ffi::QWidget_setLayout(
                self.ptr,
                layout_ptr as *mut u8 as *mut ffi::QLayout,
            );
        }
    }

    /// Install any layout (unified API — works with all layout types).
    ///
    /// ```no_run
    /// # use qtrs::*;
    /// let mut window = Widget::new().build();
    /// let vbox = VBoxLayout::with_parent(&window);
    /// window.set_layout(&vbox);
    /// ```
    pub fn set_layout(&mut self, layout: &impl crate::layout::AsLayout) {
        assert!(!self.ptr.is_null(), "Widget::set_layout on null pointer");
        let lp = layout.layout_ptr();
        assert!(!lp.is_null(), "set_layout with null layout");
        unsafe { ffi::QWidget_setLayout(self.ptr, lp); }
    }

    /// Set the window icon from an image file.
    pub fn set_icon(&self, icon_path: &str) {
        debug_assert!(!self.ptr.is_null(), "Widget::set_icon on null pointer");
        let_cxx_string!(c_path = icon_path);
        unsafe { ffi::QWidget_setWindowIcon(self.ptr, &c_path); }
    }

    /// Enable or disable this widget (and all children).
    pub fn set_enabled(&self, enabled: bool) {
        debug_assert!(!self.ptr.is_null());
        unsafe { ffi::QWidget_setEnabled(self.ptr, enabled); }
    }

    /// Show or hide this widget (alternative to [`show`](Self::show)/[`hide`](Self::hide)).
    pub fn set_visible(&self, visible: bool) {
        debug_assert!(!self.ptr.is_null());
        unsafe { ffi::QWidget_setVisible(self.ptr, visible); }
    }

    /// Set a tooltip that appears on hover.
    pub fn set_tooltip(&self, tip: &str) {
        debug_assert!(!self.ptr.is_null());
        let_cxx_string!(c_tip = tip);
        unsafe { ffi::QWidget_setToolTip(self.ptr, &c_tip); }
    }

    /// Set the minimum size in pixels.
    pub fn set_min_size(&self, w: i32, h: i32) {
        debug_assert!(!self.ptr.is_null());
        unsafe { ffi::QWidget_setMinimumSize(self.ptr, w, h); }
    }

    /// Set the maximum size in pixels.
    pub fn set_max_size(&self, w: i32, h: i32) {
        debug_assert!(!self.ptr.is_null());
        unsafe { ffi::QWidget_setMaximumSize(self.ptr, w, h); }
    }

    /// Lock the widget to a fixed size (sets both min and max).
    pub fn set_fixed_size(&self, w: i32, h: i32) {
        debug_assert!(!self.ptr.is_null());
        unsafe { ffi::QWidget_setFixedSize(self.ptr, w, h); }
    }

    /// Apply a CSS stylesheet to this widget (cascades to children).
    ///
    /// Uses [`QWidget::setStyleSheet`](https://doc.qt.io/qt-6/stylesheet.html).
    pub fn set_style_sheet(&self, css: &str) {
        debug_assert!(!self.ptr.is_null());
        let_cxx_string!(c_css = css);
        unsafe { ffi::QWidget_setStyleSheet(self.ptr, &c_css); }
    }

    /// Move widget to (x, y) coordinates.
    pub fn move_to(&self, x: i32, y: i32) {
        debug_assert!(!self.ptr.is_null(), "Widget::move_to on null pointer");
        unsafe { ffi::QWidget_move(self.ptr, x, y); }
    }

    /// Move widget to a Point position.
    pub fn move_to_point(&self, point: Point) {
        debug_assert!(!self.ptr.is_null(), "Widget::move_to_point on null pointer");
        unsafe { ffi::QWidget_moveToPoint(self.ptr, point.to_raw()); }
    }

    /// Find a named child widget by its `objectName`.
    ///
    /// `kind` selects the widget type to find. Returns the wrapped widget
    /// on success, or `None` if no child with that name and type exists.
    ///
    /// ```no_run
    /// # use qtrs::*;
    /// let window = Widget::new().title("demo").build();
    /// if let Some(FoundWidget::PushButton(mut btn)) =
    ///     window.find(WidgetKind::PushButton, "myButton")
    /// {
    ///     btn.connect_clicked(|| println!("clicked!"));
    /// }
    /// ```
    pub fn find(&self, kind: WidgetKind, name: &str) -> Option<FoundWidget> {
        assert!(!self.ptr.is_null(), "Widget::find on null pointer");
        let_cxx_string!(c_name = name);

        // Generate all find arms from a compact spec in a single macro call.
        // Entries separated by `;`. Last token before `;` is `0` (no name) or `1` (with name).
        macro_rules! find_match {
            ($($kind:ident $ffi:ident $found:ident $use_name:ident $ty:path);* $(;)?) => {
                match kind {
                    $(
                        WidgetKind::$kind => {
                            let ptr = unsafe { ffi::$ffi(self.ptr, &c_name) };
                            if ptr.is_null() { None }
                            else {
                                find_match!(@raw $use_name, $found, $ty, ptr)
                            }
                        }
                    ),*
                    WidgetKind::Any => {
                        let ptr = unsafe { ffi::QWidget_findWidget(self.ptr, &c_name) };
                        if ptr.is_null() { None }
                        else { Some(FoundWidget::Widget(Widget::from_raw(ptr, true))) }
                    }
                }
            };
            (@raw YES, $found:ident, $ty:path, $ptr:ident) => {
                Some(FoundWidget::$found(<$ty>::from_raw($ptr, name)))
            };
            (@raw NO, $found:ident, $ty:path, $ptr:ident) => {
                Some(FoundWidget::$found(<$ty>::from_raw($ptr)))
            };
        }

        find_match! {
            PushButton QWidget_findPushButton PushButton YES crate::PushButton;
            LineEdit QWidget_findLineEdit LineEdit YES crate::LineEdit;
            CheckBox QWidget_findCheckBox CheckBox YES crate::CheckBox;
            ComboBox QWidget_findComboBox ComboBox YES crate::ComboBox;
            Slider QWidget_findSlider Slider YES crate::Slider;
            TextEdit QWidget_findTextEdit TextEdit YES crate::TextEdit;
            Label QWidget_findLabel Label YES crate::Label;
            ProgressBar QWidget_findProgressBar ProgressBar NO crate::ProgressBar;
            RadioButton QWidget_findRadioButton RadioButton NO crate::RadioButton;
            GroupBox QWidget_findGroupBox GroupBox NO crate::GroupBox;
            TabWidget QWidget_findTabWidget TabWidget NO crate::TabWidget;
            SpinBox QWidget_findSpinBox SpinBox NO crate::SpinBox;
            ListWidget QWidget_findListWidget ListWidget YES crate::ListWidget;
            ProgressDialog QWidget_findProgressDialog ProgressDialog NO crate::ProgressDialog;
            ScrollArea QWidget_findScrollArea ScrollArea NO crate::ScrollArea;
            TableWidget QWidget_findTableWidget TableWidget NO crate::TableWidget;
            TreeWidget QWidget_findTreeWidget TreeWidget NO crate::TreeWidget;
            StackedWidget QWidget_findStackedWidget StackedWidget NO crate::StackedWidget;
            Splitter QWidget_findSplitter Splitter NO crate::Splitter;
            DateEdit QWidget_findDateEdit DateEdit YES crate::DateEdit;
            TimeEdit QWidget_findTimeEdit TimeEdit YES crate::TimeEdit;
            DateTimeEdit QWidget_findDateTimeEdit DateTimeEdit YES crate::DateTimeEdit;
            PlainTextEdit QWidget_findPlainTextEdit PlainTextEdit YES crate::PlainTextEdit;
            TextBrowser QWidget_findTextBrowser TextBrowser YES crate::TextBrowser;
        }
    }
}

// ============================================================
// Widget find enums
// ============================================================

/// Widget type selector for [`Widget::find`].
#[derive(Clone, Copy)]
pub enum WidgetKind {
    PushButton,
    LineEdit,
    CheckBox,
    ComboBox,
    Slider,
    TextEdit,
    Label,
    ProgressBar,
    RadioButton,
    GroupBox,
    TabWidget,
    SpinBox,
    ListWidget,
    ProgressDialog,
    ScrollArea,
    TableWidget,
    TreeWidget,
    StackedWidget,
    Splitter,
    DateEdit,
    TimeEdit,
    DateTimeEdit,
    PlainTextEdit,
    TextBrowser,
    /// Any `QWidget` (no signal support).
    Any,

}

/// Returned by [`Widget::find`] — match to unwrap and connect signals.
pub enum FoundWidget {
    PushButton(crate::PushButton),
    LineEdit(crate::LineEdit),
    CheckBox(crate::CheckBox),
    ComboBox(crate::ComboBox),
    Slider(crate::Slider),
    TextEdit(crate::TextEdit),
    Label(crate::Label),
    ProgressBar(crate::ProgressBar),
    RadioButton(crate::RadioButton),
    GroupBox(crate::GroupBox),
    TabWidget(crate::TabWidget),
    SpinBox(crate::SpinBox),
    ListWidget(crate::ListWidget),
    ProgressDialog(crate::ProgressDialog),
    ScrollArea(crate::ScrollArea),
    TableWidget(crate::TableWidget),
    TreeWidget(crate::TreeWidget),
    StackedWidget(crate::StackedWidget),
    Splitter(crate::Splitter),
    DateEdit(crate::DateEdit),
    TimeEdit(crate::TimeEdit),
    DateTimeEdit(crate::DateTimeEdit),
    PlainTextEdit(crate::PlainTextEdit),
    TextBrowser(crate::TextBrowser),
    Widget(Widget),
}

impl AsWidget for Widget {
    fn widget_ptr(&self) -> *mut ffi::QWidget {
        debug_assert!(!self.ptr.is_null(), "widget_ptr on null pointer");
        unsafe { ffi::toQWidget_QWidget(self.ptr) }
    }

    fn set_has_parent(&mut self) {
        self.has_parent = true;
    }
}

impl Drop for Widget {
    fn drop(&mut self) {
        if self.ptr.is_null() { return; }
        if self.has_parent {
            unsafe { ffi::QWidget_disconnectAll(self.ptr); }
            for h in self.signal_handles.drain(..) {
                unsafe { h.reclaim(); }
            }
        } else {
            for h in self.signal_handles.drain(..) {
                unsafe { h.reclaim(); }
            }
            unsafe { ffi::QWidget_delete(self.ptr) };
        }
        self.ptr = std::ptr::null_mut();
    }
}

// ============================================================
// Builder
// ============================================================

/// Builder for [`Widget`].
///
/// Collects configuration and creates the C++ `QWidget` in
/// [`build`](Self::build).
///
/// # Example
///
/// ```no_run
/// let window = Widget::new()
///     .title("Demo")
///     .size(640, 480)
///     .build();
/// ```
pub struct Builder {
    title: Option<String>,
    icon: Option<String>,
    width: i32,
    height: i32,
    parent: Option<*mut ffi::QWidget>,
}

impl Builder {
    fn new() -> Self {
        Self {
            title: None,
            icon: None,
            width: 400,
            height: 300,
            parent: None,
        }
    }

    /// Set the window title (displayed in the title bar).
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the window icon from an image file path.
    ///
    /// Supports PNG, JPEG, BMP, GIF, SVG, and other formats Qt can read.
    /// The path is resolved relative to the working directory when the
    /// application runs.
    ///
    /// > **Wayland note:** Per-window icons may not display on Wayland.
    /// > Use [`Application::set_icon`] for reliable cross-platform icons.
    ///
    /// [`Application::set_icon`]: crate::Application::set_icon
    pub fn icon(mut self, path: impl Into<String>) -> Self {
        self.icon = Some(path.into());
        self
    }

    /// Set the window size in logical pixels.
    ///
    /// Default is 400×300.
    pub fn size(mut self, width: i32, height: i32) -> Self {
        self.width = width;
        self.height = height;
        self
    }

    /// Attach this widget as a child of `parent`.
    ///
    /// The parent widget will manage this widget's C++ lifetime.
    /// Do **not** drop the parent before the child — Qt will delete
    /// the child automatically.
    pub fn parent(mut self, parent: &dyn AsWidget) -> Self {
        self.parent = Some(parent.widget_ptr());
        self
    }

    /// Create the C++ `QWidget`, apply configuration, and return the Rust
    /// wrapper.
    ///
    /// This is the terminal method of the builder pattern.
    pub fn build(self) -> Widget {
        let ptr = unsafe {
            ffi::QWidget_new(
                self.parent.unwrap_or(std::ptr::null_mut()),
            )
        };
        assert!(!ptr.is_null(), "QWidget_new returned null");

        let has_parent = self.parent.is_some();

        let widget = Widget {
            ptr,
            has_parent,
            title: self.title.clone(),
            width: self.width,
            height: self.height,
            signal_handles: Vec::new(),
        };

        // Apply initial configuration.
        if let Some(ref t) = self.title {
            let_cxx_string!(c_title = t);
            unsafe { ffi::QWidget_setWindowTitle(widget.ptr, &c_title) };
        }
        if let Some(ref icon_path) = self.icon {
            let_cxx_string!(c_icon = icon_path);
            unsafe { ffi::QWidget_setWindowIcon(widget.ptr, &c_icon) };
        }
        unsafe { ffi::QWidget_resize(widget.ptr, self.width, self.height) };

        widget
    }

    /// Build the widget and immediately call [`Widget::show`].
    ///
    /// Convenience shorthand for `.build()` followed by `.show()`.
    pub fn show(self) -> Widget {
        let w = self.build();
        w.show();
        w
    }
}