wxdragon 0.9.15

Safe Rust bindings for wxWidgets via the wxDragon C wrapper
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
// use crate::event::WxEvtHandler; // This might be unused if all macros import it directly.

//! Macros to simplify implementation of common patterns in the codebase.

/// Creates a builder pattern for widgets
///
/// This macro generates a builder struct with standard fields and methods
/// following the WxDragon convention.
///
/// # Parameters
///
/// * `name` - The name of the widget (e.g., `Button`, `CheckBox`)
/// * `parent_type` - The type of the parent parameter (e.g., `&'a dyn WxWidget`)
/// * `style_type` - The type of the style parameter (e.g., `ButtonStyle`)
/// * `fields` - Additional fields for the builder, including label if needed
/// * `build_impl` - A closure that implements the build logic
///
/// # Example
///
/// ```ignore
/// widget_builder!(
///     name: Button,
///     parent_type: &'a dyn WxWidget,
///     style_type: ButtonStyle,
///     fields: {
///         label: String = String::new()
///     },
///     build_impl: |slf| {
///         let parent_ptr = slf.parent.handle_ptr();
///         Button::new_impl(
///             parent_ptr,
///             slf.id,
///             &slf.label,
///             slf.pos,
///             slf.size,
///             slf.style.bits(),
///         )
///     }
/// );
/// ```
#[macro_export]
macro_rules! widget_builder {
    (
        name: $name:ident,
        parent_type: &'a dyn WxWidget,
        style_type: $style_type:ty,
        fields: {
            $(
                $field_name:ident: $field_type:ty $(= $field_default:expr)?
            ),*
        },
        build_impl: |$self_param:ident| $build_impl:block
    ) => {
        paste::paste! {
            #[derive(Clone)]
            pub struct [<$name Builder>]<'a> {
                parent: &'a dyn WxWidget,
                id: Id,
                pos: Point,
                size: Size,
                style: $style_type,
                $(
                    $field_name: $field_type,
                )*
            }

            impl<'a> [<$name Builder>]<'a> {
                pub fn new(parent: &'a dyn WxWidget) -> Self {
                    Self {
                        parent,
                        id: $crate::id::ID_ANY as Id,
                        pos: $crate::geometry::Point::DEFAULT_POSITION,
                        size: $crate::geometry::Size::DEFAULT_SIZE,
                        style: <$style_type>::default(),
                        $(
                            $field_name: $crate::__widget_builder_default!($($field_default)?),
                        )*
                    }
                }

                /// Sets the window identifier.
                pub fn with_id(mut self, id: Id) -> Self {
                    self.id = id;
                    self
                }

                /// Sets the position.
                pub fn with_pos(mut self, pos: Point) -> Self {
                    self.pos = pos;
                    self
                }

                /// Sets the size.
                pub fn with_size(mut self, size: Size) -> Self {
                    self.size = size;
                    self
                }

                /// Sets the window style flags.
                pub fn with_style(mut self, style: $style_type) -> Self {
                    self.style = style;
                    self
                }

                $(
                    $crate::__widget_builder_field_method!($field_name: $field_type);
                )*

                /// Builds the widget.
                pub fn build(self) -> $name {
                    let build_fn = |$self_param: [<$name Builder>]<'a>| $build_impl;
                    build_fn(self)
                }
            }
        }
    };
}

/// Implements common widget traits.
///
/// This macro generates implementations for:
/// - WxWidget trait
/// - Deref/DerefMut to Window
/// - WxEvtHandler trait
///
/// Note: Drop is NOT implemented, as wxWidgets manages child window lifetimes.
/// This allows widgets to implement Copy for convenient use in closures.
///
/// # Parameters
///
/// * `name` - The name of the widget struct
/// * `field` - The name of the field within the struct that is a Window
///
/// # Example
///
/// ```ignore
/// implement_widget_traits!(MyWidget, window_field);
/// ```
#[macro_export]
macro_rules! implement_widget_traits {
    ($widget_name:ident, $window_field:ident) => {
        // Don't import WxEvtHandler here as modules might already have it imported
        // use $crate::event::WxEvtHandler;

        impl $crate::window::WxWidget for $widget_name {
            fn handle_ptr(&self) -> *mut wxdragon_sys::wxd_Window_t {
                self.$window_field.handle_ptr()
            }
        }

        impl std::ops::Deref for $widget_name {
            type Target = $crate::window::Window;
            fn deref(&self) -> &Self::Target {
                &self.$window_field
            }
        }

        impl std::ops::DerefMut for $widget_name {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.$window_field
            }
        }

        impl $crate::event::WxEvtHandler for $widget_name {
            unsafe fn get_event_handler_ptr(&self) -> *mut wxdragon_sys::wxd_EvtHandler_t {
                self.$window_field.get_event_handler_ptr()
            }
        }

        // Note: Drop is intentionally NOT implemented for widgets.
        // Child windows are managed by their parent in wxWidgets.
        // This allows widgets to implement Copy for convenient use in closures.
    };
}

/// Implements common widget traits with a custom target type for Deref
///
/// This macro generates implementations for:
/// - WxWidget trait
/// - Deref/DerefMut to the specified target type
/// - WxEvtHandler trait
/// - MenuEvents trait (for context menus and menu handling)
/// - WindowEvents trait (for standard window events)
///
/// Note: Drop is NOT implemented, as wxWidgets manages child window lifetimes.
/// This allows widgets to implement Copy for convenient use in closures.
///
/// # Parameters
///
/// * `name` - The name of the widget struct
/// * `field` - The name of the field within the struct that implements WxWidget
/// * `target_type` - The target type for Deref/DerefMut implementations
///
/// # Note on Clone
///
/// The generated Clone implementation only explicitly clones the target field.
/// Other fields in the struct must either:
/// - Be Copy types (like raw pointers, PhantomData)
/// - Or the struct should manually implement Clone
///
/// # Example
///
/// ```ignore
/// // For a widget that wraps a Window:
/// implement_widget_traits_with_target!(MyWidget, window, Window);
///
/// // For a widget that wraps another widget type:
/// implement_widget_traits_with_target!(MyCompositeWidget, inner_widget, OtherWidgetType);
/// ```
#[macro_export]
macro_rules! implement_widget_traits_with_target {
    ($widget_name:ident, $window_field:ident, $target_ty:ty) => {
        // Don't import WxEvtHandler here as modules might already have it imported
        // use $crate::event::WxEvtHandler;

        impl $crate::window::WxWidget for $widget_name {
            fn handle_ptr(&self) -> *mut wxdragon_sys::wxd_Window_t {
                self.$window_field.handle_ptr()
            }
        }

        impl std::ops::Deref for $widget_name {
            type Target = $target_ty;
            fn deref(&self) -> &Self::Target {
                &self.$window_field
            }
        }

        impl std::ops::DerefMut for $widget_name {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.$window_field
            }
        }

        impl $crate::event::WxEvtHandler for $widget_name {
            unsafe fn get_event_handler_ptr(&self) -> *mut wxdragon_sys::wxd_EvtHandler_t {
                unsafe { self.$window_field.get_event_handler_ptr() }
            }
        }

        // Note: Drop is intentionally NOT implemented for widgets.
        // Child windows are managed by their parent in wxWidgets.
        // This allows widgets to implement Copy for convenient use in closures.

        // Auto-implement common event traits that all Window-based widgets support
        impl $crate::event::MenuEvents for $widget_name {}
        impl $crate::event::WindowEvents for $widget_name {}
    };
}

/// Defines a style enum for a widget with standard implementations
///
/// This macro creates a style enum with variants from wxWidgets constants
/// and implements common traits like Default, BitOr, BitOrAssign, and bits().
///
/// # Parameters
///
/// * `name` - The name of the style enum (e.g., `ButtonStyle`, `RadioBoxStyle`)
/// * `doc` - Documentation for the enum (e.g., "Style flags for Button")
/// * `variants` - A list of variants with their names, wxWidgets constants, and docs
/// * `default_variant` - The name of the variant to use as Default
///
/// # Example
///
/// ```ignore
/// widget_style_enum!(
///     name: ButtonStyle,
///     doc: "Style flags for Button.",
///     variants: {
///         Default: 0, "Default style (no specific alignment).",
///         Left: ffi::WXD_BU_LEFT, "Align label to the left.",
///         Right: ffi::WXD_BU_RIGHT, "Align label to the right."
///     },
///     default_variant: Default
/// );
/// ```
#[macro_export]
macro_rules! widget_style_enum {
    (
        name: $name:ident,
        doc: $doc:expr,
        variants: {
            $(
                $variant:ident: $value:expr, $variant_doc:expr
            ),+
        },
        default_variant: $default:ident
    ) => {
        bitflags::bitflags! {
            #[doc = $doc]
            #[doc = "\n\nThese flags can be combined using the bitwise OR operator (`|`)."]
            #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
            pub struct $name : i64 {
                $(
                    #[doc = $variant_doc]
                    const $variant = $value;
                )+
            }
        }

        impl Default for $name {
            fn default() -> Self {
                $name::$default
            }
        }
    };
}

// Helper macro for generating appropriate setter methods based on field type
#[doc(hidden)]
#[macro_export]
macro_rules! __widget_builder_field_method {
    // Special case for String fields - allow &str parameters and convert to String
    // This applies to any field with type String, regardless of name
    ($field_name:ident: String) => {
        paste::paste! {
            /// Sets the $field_name.
            #[allow(non_snake_case)]
            pub fn [<with_ $field_name>](mut self, $field_name: &str) -> Self {
                self.$field_name = $field_name.to_string();
                self
            }
        }
    };
    // Default case for all other fields - generate a method that takes the same type as the field
    ($field_name:ident: $field_type:ty) => {
        paste::paste! {
            /// Sets the $field_name.
            #[allow(non_snake_case)]
            pub fn [<with_ $field_name>](mut self, $field_name: $field_type) -> Self {
                self.$field_name = $field_name;
                self
            }
        }
    };
}

// Helper macro for default values in fields
#[doc(hidden)]
#[macro_export]
macro_rules! __widget_builder_default {
    () => {
        Default::default()
    };
    ($expr:expr) => {
        $expr
    };
}

/// Implements XrcSupport trait for a widget with custom field initialization
///
/// This macro generates the XrcSupport implementation for widgets, handling
/// different field patterns that widgets may have.
///
/// # Parameters
///
/// * `widget_name` - The name of the widget struct
/// * `fields` - Block containing field initialization expressions
///
/// # Example
///
/// ```ignore
/// // For widgets with just a window field:
/// impl_xrc_support!(TextCtrl, {
///     window
/// });
///
/// // For widgets with window and parent_ptr fields:
/// impl_xrc_support!(Button, {
///     window,
///     parent_ptr: std::ptr::null_mut()
/// });
/// ```
#[macro_export]
#[cfg(feature = "xrc")]
macro_rules! impl_xrc_support {
    // Handle the simple case where only window field is specified
    ($widget_name:ident, { window }) => {
        #[cfg(feature = "xrc")]
        impl $crate::xrc::XrcSupport for $widget_name {
            unsafe fn from_xrc_ptr(ptr: *mut wxdragon_sys::wxd_Window_t) -> Self {
                let window = unsafe { $crate::window::Window::from_ptr(ptr) };
                Self { window }
            }
        }
    };
    // Handle the more complex case with additional fields
    ($widget_name:ident, { window, $($field_name:ident: $field_value:expr),* $(,)? }) => {
        #[cfg(feature = "xrc")]
        impl $crate::xrc::XrcSupport for $widget_name {
            unsafe fn from_xrc_ptr(ptr: *mut wxdragon_sys::wxd_Window_t) -> Self {
                let window = unsafe { $crate::window::Window::from_ptr(ptr) };
                Self {
                    window,
                    $(
                        $field_name: $field_value,
                    )*
                }
            }
        }
    };
}

// Empty version when xrc feature is disabled
#[macro_export]
#[cfg(not(feature = "xrc"))]
macro_rules! impl_xrc_support {
    // Accept the same patterns but generate no code
    ($widget_name:ident, { window }) => {};
    ($widget_name:ident, { window, $($field_name:ident: $field_value:expr),* $(,)? }) => {};
}

/// Creates a custom widget with builder pattern based on Panel
///
/// This macro simplifies custom widget development by:
/// - Creating a Panel-based widget struct
/// - Generating a builder pattern with customizable fields
/// - Automatically implementing WxWidget, Deref, DerefMut, and WxEvtHandler traits
/// - Handling memory management properly
///
/// # Parameters
///
/// * `name` - The name of the custom widget (e.g., `AniFillButton`)
/// * `fields` - Additional fields for configuration with default values
/// * `setup_impl` - Implementation block for widget setup (receives config and panel)
///
/// # Example
///
/// ```ignore
/// custom_widget!(
///     name: AniFillButton,
///     fields: {
///         text: String = "Button".to_string(),
///         border_color: Colour = Colour::new(100, 100, 100, 255),
///         border_width: i32 = 2
///     },
///     setup_impl: |config, panel| {
///         // Your setup code here
///         // config contains all the field values
///         // panel is the underlying Panel widget
///     }
/// );
/// ```
#[macro_export]
macro_rules! custom_widget {
    (
        name: $name:ident,
        fields: {
            $(
                $field_name:ident: $field_type:ty = $field_default:expr
            ),* $(,)?
        },
        setup_impl: |$config_param:ident, $panel_param:ident| $setup_impl:block
    ) => {
        paste::paste! {
            /// Configuration struct for the custom widget
            #[derive(Debug, Clone)]
            pub struct [<$name Config>] {
                $(
                    pub $field_name: $field_type,
                )*
            }

            impl Default for [<$name Config>] {
                fn default() -> Self {
                    Self {
                        $(
                            $field_name: $field_default,
                        )*
                    }
                }
            }

            /// Builder for the custom widget
            #[derive(Clone)]
            pub struct [<$name Builder>]<'a> {
                parent: &'a dyn $crate::window::WxWidget,
                size: $crate::geometry::Size,
                $(
                    $field_name: $field_type,
                )*
            }

            impl<'a> [<$name Builder>]<'a> {
                /// Creates a new builder
                pub fn new(parent: &'a dyn $crate::window::WxWidget) -> Self {
                    Self {
                        parent,
                        size: $crate::geometry::Size::DEFAULT_SIZE,
                        $(
                            $field_name: $field_default,
                        )*
                    }
                }

                /// Sets the widget size
                pub fn with_size(mut self, size: $crate::geometry::Size) -> Self {
                    self.size = size;
                    self
                }

                $(
                    paste::paste! {
                        /// Sets the field value
                        pub fn [<with_ $field_name>](mut self, $field_name: $field_type) -> Self {
                            self.$field_name = $field_name;
                            self
                        }
                    }
                )*

                /// Builds the custom widget
                pub fn build(self) -> $name {
                    let panel = $crate::widgets::panel::Panel::builder(self.parent)
                        .with_size(self.size)
                        .build();

                    let config = [<$name Config>] {
                        $(
                            $field_name: self.$field_name,
                        )*
                    };

                    let widget = $name {
                        panel: panel.clone(),
                        config: config.clone(),
                    };

                    // Call the setup implementation
                    let setup_fn = |$config_param: [<$name Config>], $panel_param: $crate::widgets::panel::Panel| $setup_impl;
                    setup_fn(config, panel);

                    widget
                }
            }

            /// The custom widget struct
            pub struct $name {
                panel: $crate::widgets::panel::Panel,
                config: [<$name Config>],
            }

            impl $name {
                /// Returns a reference to the configuration
                pub fn config(&self) -> &[<$name Config>] {
                    &self.config
                }

                /// Creates a new builder for this widget type
                pub fn builder(parent: &dyn $crate::window::WxWidget) -> [<$name Builder>]<'_> {
                    [<$name Builder>]::new(parent)
                }
            }

            // Implement the necessary traits
            impl $crate::window::WxWidget for $name {
                fn handle_ptr(&self) -> *mut $crate::ffi::wxd_Window_t {
                    self.panel.handle_ptr()
                }
            }

            impl std::ops::Deref for $name {
                type Target = $crate::widgets::panel::Panel;
                fn deref(&self) -> &Self::Target {
                    &self.panel
                }
            }

            impl std::ops::DerefMut for $name {
                fn deref_mut(&mut self) -> &mut Self::Target {
                    &mut self.panel
                }
            }

            impl $crate::event::WxEvtHandler for $name {
                unsafe fn get_event_handler_ptr(&self) -> *mut $crate::ffi::wxd_EvtHandler_t {
                    unsafe { self.panel.get_event_handler_ptr() }
                }
            }

            // Let the underlying Panel handle memory management
        }
    };
}

/// Implements widget casting capability for a widget type.
///
/// This macro generates the FromWindowWithClassName trait implementation
/// for a widget, enabling it to be safely cast from a generic Window
/// using wxWidgets' built-in RTTI system.
///
/// # Parameters
/// * `widget` - The widget type name (e.g., StaticText, Button)
/// * `class_name` - The corresponding wxWidgets class name (e.g., "wxStaticText")
/// * `construction` - How to construct the widget from a Window:
///   - `{ window }` - For widgets that only need a window field (like StaticText)
///   - `composition` - For widgets that use new_from_composition (like Button)
///
/// # Examples
/// ```ignore
/// // For StaticText (simple window field pattern):
/// impl_widget_cast!(StaticText, "wxStaticText", { window });
///
/// // For Button (composition pattern):
/// impl_widget_cast!(Button, "wxButton", composition);
///
/// // Usage:
/// if let Some(text) = window.as_widget::<StaticText>() {
///     text.set_label("Hello");
/// }
/// ```
#[macro_export]
macro_rules! impl_widget_cast {
    // Pattern for widgets that use new_from_composition
    ($widget:ident, $class_name:literal, composition) => {
        impl $crate::window::FromWindowWithClassName for $widget {
            fn class_name() -> &'static str {
                $class_name
            }

            unsafe fn from_ptr(ptr: *mut wxdragon_sys::wxd_Window_t) -> Self {
                let window = unsafe { $crate::window::Window::from_ptr(ptr) };
                Self::new_from_composition(window, std::ptr::null_mut())
            }
        }
    };

    // Pattern for widgets that only need { window }
    ($widget:ident, $class_name:literal, { $field:ident }) => {
        impl $crate::window::FromWindowWithClassName for $widget {
            fn class_name() -> &'static str {
                $class_name
            }

            unsafe fn from_ptr(ptr: *mut wxdragon_sys::wxd_Window_t) -> Self {
                let $field = unsafe { $crate::window::Window::from_ptr(ptr) };
                Self { $field }
            }
        }
    };
}

/// Helper macro to implement Clone, Drop, AsRef, and Deref for models that wrap a
/// refcounted native pointer.
///
/// Usage (explicit native pointer type and refcount functions are required):
/// ```ignore
///   impl_refcounted_object!(
///       TypeName,
///       ptr_field,
///       ffi::wxd_DataViewModel_t,
///       ffi::wxd_DataViewModel_AddRef,
///       ffi::wxd_DataViewModel_GetRefCount,
///       ffi::wxd_DataViewModel_Release
///   );
///   impl_refcounted_object!(
///       TypeName,
///       ptr_field,
///       ffi::wxd_DataViewModel_t,
///       ffi::wxd_DataViewModel_AddRef,
///       ffi::wxd_DataViewModel_GetRefCount,
///       ffi::wxd_DataViewModel_Release,
///       other1, other2, ...
///   );
/// ```
/// If you explicitly want Send/Sync (rare for GUI models), opt-in with:
/// ```ignore
///   impl_refcounted_object!(
///       send_sync TypeName,
///       ptr_field,
///       ffi::wxd_DataViewModel_t,
///       ffi::wxd_DataViewModel_AddRef,
///       ffi::wxd_DataViewModel_GetRefCount,
///       ffi::wxd_DataViewModel_Release,
///       other1, ...
///   );
/// ```
#[macro_export]
macro_rules! impl_refcounted_object {
    // Internal arm shared by both public forms
    (@base $ty:ty, $ptr_field:ident, $ptr_ty:ty, $add_ref:path, $get_refcount:path, $release:path $(, $other_field:ident )* ) => {
        impl Clone for $ty {
            fn clone(&self) -> Self {
                if !self.$ptr_field.is_null() {
                    unsafe { $add_ref(self.$ptr_field) };
                }
                Self {
                    $ptr_field: self.$ptr_field,
                    $( $other_field: self.$other_field.clone(), )*
                }
            }
        }

        impl Drop for $ty {
            fn drop(&mut self) {
                if !self.$ptr_field.is_null() {
                    let count = unsafe { $get_refcount(self.$ptr_field) } - 1;
                    let text = if count == 0 { "it destroyed" } else { "it still alive" };
                    log::debug!(
                        "{} dropped, inner object RefCount is {} now, {}.",
                        stringify!($ty),
                        count,
                        text
                    );
                    unsafe { $release(self.$ptr_field) };
                }
            }
        }

        impl AsRef<*mut $ptr_ty> for $ty {
            fn as_ref(&self) -> &*mut $ptr_ty {
                &self.$ptr_field
            }
        }

        impl std::ops::Deref for $ty {
            type Target = *mut $ptr_ty;
            fn deref(&self) -> &Self::Target {
                &self.$ptr_field
            }
        }
    };

    // Default: no Send/Sync (safer for GUI models) - requires explicit ptr type and refcount fns
    ($ty:ty, $ptr_field:ident, $ptr_ty:ty, $add_ref:path, $get_refcount:path, $release:path $(, $other_field:ident )* ) => {
        impl_refcounted_object!(@base $ty, $ptr_field, $ptr_ty, $add_ref, $get_refcount, $release $(, $other_field )* );
    };

    // Opt-in for Send/Sync with explicit native pointer type and refcount fns (only if truly thread-safe)
    (send_sync $ty:ty, $ptr_field:ident, $ptr_ty:ty, $add_ref:path, $get_refcount:path, $release:path $(, $other_field:ident )* ) => {
        impl_refcounted_object!(@base $ty, $ptr_field, $ptr_ty, $add_ref, $get_refcount, $release $(, $other_field )* );
        unsafe impl Send for $ty {}
        unsafe impl Sync for $ty {}
    };
}