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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
use crate::accessible::Accessible;
use crate::event::{EventType, WxEvtHandler};
use crate::font::Font;
use crate::geometry::{Point, Size};
use crate::sizers::WxSizer;
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::CStr;
use std::sync::atomic::{AtomicU64, Ordering};
use wxdragon_sys as ffi;

// ============================================================================
// WindowHandle: Safe, Copy-able handle to wxWidgets windows
// ============================================================================

/// Counter for generating unique handle IDs
static NEXT_HANDLE_ID: AtomicU64 = AtomicU64::new(1);

thread_local! {
    /// Maps handle IDs to raw window pointers
    static WINDOW_REGISTRY: RefCell<HashMap<u64, *mut ffi::wxd_Window_t>> =
        RefCell::new(HashMap::new());
    /// Reverse mapping: pointer address to handle ID (for destroy callback lookup)
    static REVERSE_REGISTRY: RefCell<HashMap<usize, u64>> =
        RefCell::new(HashMap::new());
}

/// A safe, Copy-able handle to a wxWidgets window.
///
/// Unlike raw pointers, `WindowHandle` automatically tracks when the underlying
/// window is destroyed (via wxEVT_DESTROY) and returns `None` from `get_ptr()`
/// after destruction. This prevents use-after-free bugs.
///
/// # Example
/// ```ignore
/// let button = Button::builder(&frame).build();
///
/// // WindowHandle is Copy - no clone needed for closures!
/// button.bind_click(move |_| {
///     // Safe: if button was destroyed, this is a no-op
///     button.set_label("Clicked!");
/// });
///
/// frame.destroy();
/// assert!(!button.is_valid()); // Handle knows window is gone
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub struct WindowHandle(u64);

impl WindowHandle {
    /// Creates a new handle for a window pointer and registers for destroy notification.
    ///
    /// # Safety
    /// The caller must ensure `ptr` points to a valid wxWindow that hasn't been destroyed.
    pub(crate) fn new(ptr: *mut ffi::wxd_Window_t) -> Self {
        if ptr.is_null() {
            return WindowHandle(0); // Invalid handle for null pointers
        }

        let handle_id = NEXT_HANDLE_ID.fetch_add(1, Ordering::SeqCst);

        // Register in both directions for O(1) lookup either way
        WINDOW_REGISTRY.with(|r| r.borrow_mut().insert(handle_id, ptr));
        REVERSE_REGISTRY.with(|r| r.borrow_mut().insert(ptr as usize, handle_id));

        // Bind destroy event using existing event infrastructure
        // This closure runs when wxWidgets destroys the window (by any cause)
        let window = unsafe { Window::from_ptr(ptr) };
        // Bind a destroy event handler _on the window itself_.
        // wxWidgets bubbles destroy events from children up to parents, so without
        // filtering we would mistakenly invalidate the parent when any child is
        // destroyed.  Only invalidate the handle when the event's object matches the
        // tracked window pointer.
        window.bind_internal(EventType::DESTROY, move |_event| {
            if let Some(obj) = _event.get_event_object() {
                // Compare the raw pointer addresses
                if obj.as_ptr() == ptr {
                    Self::invalidate(handle_id);
                } else {
                    // ignore destroys from child windows
                }
            }
        });

        WindowHandle(handle_id)
    }

    /// Get the raw pointer if the window is still valid, `None` if destroyed.
    #[inline]
    pub fn get_ptr(&self) -> Option<*mut ffi::wxd_Window_t> {
        if self.0 == 0 {
            return None;
        }
        WINDOW_REGISTRY.with(|r| r.borrow().get(&self.0).copied())
    }

    /// Check if the underlying window is still valid (not destroyed).
    #[inline]
    pub fn is_valid(&self) -> bool {
        self.get_ptr().is_some()
    }

    /// Internal: Remove handle from registry (called when window is destroyed)
    fn invalidate(handle_id: u64) {
        WINDOW_REGISTRY.with(|r| {
            if let Some(ptr) = r.borrow_mut().remove(&handle_id) {
                log::trace!("WindowHandle::invalidate id={handle_id} ptr={ptr:p}");
                REVERSE_REGISTRY.with(|rr| {
                    rr.borrow_mut().remove(&(ptr as usize));
                });
            }
        });
    }

    /// Look up an existing handle by pointer address.
    /// Returns None if no handle exists for this pointer.
    #[allow(dead_code)]
    pub(crate) fn from_ptr(ptr: *mut ffi::wxd_Window_t) -> Option<Self> {
        if ptr.is_null() {
            return None;
        }
        REVERSE_REGISTRY.with(|r| r.borrow().get(&(ptr as usize)).map(|&id| WindowHandle(id)))
    }
}

// Forward declare the new FFI functions until they're auto-generated by bindgen
unsafe extern "C" {
    unsafe fn wxd_Window_FindWindowByName(
        window: *mut ffi::wxd_Window_t,
        name: *const std::os::raw::c_char,
    ) -> *mut ffi::wxd_Window_t;
    unsafe fn wxd_Window_FindWindowById(window: *mut ffi::wxd_Window_t, id: std::os::raw::c_int) -> *mut ffi::wxd_Window_t;
    #[cfg(target_os = "windows")]
    unsafe fn wxd_Window_MSWDisableComposited(window: *mut ffi::wxd_Window_t);
}

// Use the widget_style_enum macro to define ExtraWindowStyle
crate::widget_style_enum!(
    name: ExtraWindowStyle,
    doc: "Extra window style flags that control special window behaviors beyond standard styles.",
    variants: {
        ValidateRecursively: ffi::WXD_WS_EX_VALIDATE_RECURSIVELY, "Enable recursive validation - validation will be applied to child windows as well. This is the default behavior on most platforms.",
        BlockEvents: ffi::WXD_WS_EX_BLOCK_EVENTS, "Block all events from being processed in this window. Events are still generated but are not delivered to the window's event handlers.",
        Transient: ffi::WXD_WS_EX_TRANSIENT, "Mark this window as transient for its parent. This is primarily used for dialogs and popup windows.",
        ContextHelp: ffi::WXD_WS_EX_CONTEXTHELP, "Enable context help for this window. Shows a question mark cursor when hovering over the window.",
        ProcessIdle: ffi::WXD_WS_EX_PROCESS_IDLE, "Process idle events for this window. When IdleMode is set to ProcessSpecified, only windows with this flag receive idle events. This is essential for async integration with idle event processing.",
        ProcessUiUpdates: ffi::WXD_WS_EX_PROCESS_UI_UPDATES, "Process UI update events for this window. Similar to ProcessIdle but for UI update events."
    },
    default_variant: ValidateRecursively
);

// Use the widget_style_enum macro to define WindowStyle
crate::widget_style_enum!(
    name: WindowStyle,
    doc: "Standard window style flags that control fundamental window behaviors and appearance according to wxWidgets 3.3.0.",
    variants: {
        Border: ffi::WXD_WS_BORDER, "The window has a thin-line border.",
        Child: ffi::WXD_WS_CHILD, "The window is a child window. Cannot have a menu bar and cannot be used with Popup style.",
        ClipChildren: ffi::WXD_WS_CLIPCHILDREN, "Excludes the area occupied by child windows when drawing occurs within the parent window.",
        ClipSiblings: ffi::WXD_WS_CLIPSIBLINGS, "Clips child windows relative to each other to prevent overlap drawing issues.",
        Disabled: ffi::WXD_WS_DISABLED, "The window is initially disabled and cannot receive user input.",
        Group: ffi::WXD_WS_GROUP, "The window is the first control of a group of controls for dialog navigation.",
        Maximize: ffi::WXD_WS_MAXIMIZE, "The window is initially maximized.",
        MaximizeBox: ffi::WXD_WS_MAXIMIZEBOX, "The window has a maximize button. Cannot be combined with ContextHelp extra style.",
        Minimize: ffi::WXD_WS_MINIMIZE, "The window is initially minimized.",
        MinimizeBox: ffi::WXD_WS_MINIMIZEBOX, "The window has a minimize button. Cannot be combined with ContextHelp extra style.",
        Overlapped: ffi::WXD_WS_OVERLAPPED, "The window is an overlapped window with a title bar and border.",
        Popup: ffi::WXD_WS_POPUP, "The window is a pop-up window. Cannot be used with Child style.",
        SysMenu: ffi::WXD_WS_SYSMENU, "The window has a system menu on its title bar. Caption style must also be specified.",
        TabStop: ffi::WXD_WS_TABSTOP, "The window can receive keyboard focus when the user presses the TAB key.",
        ThickFrame: ffi::WXD_WS_THICKFRAME, "The window has a sizing border.",
        Visible: ffi::WXD_WS_VISIBLE, "The window is initially visible.",
        VScroll: ffi::WXD_WS_VSCROLL, "The window has a vertical scroll bar."
    },
    default_variant: Overlapped
);

impl WindowStyle {
    /// Alias for `Child` - marks the window as a child window.
    pub const CHILD_WINDOW: WindowStyle = WindowStyle::Child;

    /// Alias for `Minimize` - the window is initially minimized/iconified.
    pub const ICONIC: WindowStyle = WindowStyle::Minimize;

    /// Alias for `ThickFrame` - the window has a sizing border.
    pub const SIZE_BOX: WindowStyle = WindowStyle::ThickFrame;

    /// Alias for `Overlapped` - the window is an overlapped window with title bar and border.
    pub const TILED: WindowStyle = WindowStyle::Overlapped;
}

/// Background style for windows, affecting how background painting is handled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackgroundStyle {
    /// The background is erased automatically by the system.
    /// This is the default for most controls and is suitable for most cases.
    Erase,
    /// The background is erased by the system as in Erase, but using the
    /// current background color instead of the default one.
    System,
    /// The background is not erased automatically, and the application
    /// is responsible for painting the entire background in its paint handler.
    /// This is optimal for custom drawing and animation as it prevents flicker.
    Paint,
    /// Similar to Paint, but the background is filled with the background colour
    /// before calling the paint event handler.
    Colour,
}

impl BackgroundStyle {
    /// Convert to the raw FFI value
    pub fn to_raw(&self) -> i32 {
        match self {
            BackgroundStyle::Erase => wxdragon_sys::WXD_BG_STYLE_ERASE as i32,
            BackgroundStyle::System => wxdragon_sys::WXD_BG_STYLE_SYSTEM as i32,
            BackgroundStyle::Paint => wxdragon_sys::WXD_BG_STYLE_PAINT as i32,
            BackgroundStyle::Colour => wxdragon_sys::WXD_BG_STYLE_COLOUR as i32,
        }
    }

    /// Create from raw FFI value
    pub fn from_raw(value: i32) -> Self {
        match value as i64 {
            v if v == wxdragon_sys::WXD_BG_STYLE_ERASE => BackgroundStyle::Erase,
            v if v == wxdragon_sys::WXD_BG_STYLE_SYSTEM => BackgroundStyle::System,
            v if v == wxdragon_sys::WXD_BG_STYLE_PAINT => BackgroundStyle::Paint,
            v if v == wxdragon_sys::WXD_BG_STYLE_COLOUR => BackgroundStyle::Colour,
            _ => BackgroundStyle::System, // Default fallback
        }
    }
}

/// Represents a pointer to any wxDragon window object.
/// This is typically used as a base struct or in trait objects.
/// Note: Deliberately NOT Copy or Clone, as it represents unique FFI resource ownership.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Window(pub(crate) *mut ffi::wxd_Window_t);

impl std::fmt::Debug for Window {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Window").field("ptr", &self.0).finish()
    }
}

impl Window {
    /// Creates a new Window wrapper from a raw pointer.
    /// # Safety
    /// The caller must ensure the pointer is valid and manages its lifetime correctly.
    /// This is typically called internally by concrete widget constructors.
    pub(crate) unsafe fn from_ptr(ptr: *mut ffi::wxd_Window_t) -> Self {
        Self(ptr)
    }

    /// Returns the raw underlying pointer.
    /// Temporary: Made public for FFI callbacks until safe event handling is done.
    pub fn as_ptr(&self) -> *mut ffi::wxd_Window_t {
        self.0
    }

    /// Checks if the underlying pointer is null.
    pub fn is_null(&self) -> bool {
        self.0.is_null()
    }

    /// Sets the window's sizer.
    /// Takes ownership of the Sizer object (caller should `std::mem::forget` it).
    /// `delete_old_sizer`: If true, the previous sizer (if any) is deleted.
    pub fn set_sizer(&self, sizer: impl WxSizer, delete_old_sizer: bool) {
        let window_ptr = self.handle_ptr();
        let sizer_ptr = sizer.as_sizer_ptr(); // Get pointer before potential forget
        if !window_ptr.is_null() && !sizer_ptr.is_null() {
            // Forget the Rust wrapper BEFORE passing pointer ownership to C++
            std::mem::forget(sizer);
            unsafe {
                ffi::wxd_Window_SetSizer(window_ptr, sizer_ptr, delete_old_sizer);
            }
        }
        // Sizer ownership is transferred to C++.
    }

    /// Sets the window's sizer and calls `Fit()` on the window.
    /// Takes ownership of the Sizer object (caller should `std::mem::forget` it).
    /// `delete_old_sizer`: If true, the previous sizer (if any) is deleted.
    pub fn set_sizer_and_fit(&self, sizer: impl WxSizer, delete_old_sizer: bool) {
        let window_ptr = self.handle_ptr();
        let sizer_ptr = sizer.as_sizer_ptr(); // Get pointer before potential forget
        if !window_ptr.is_null() && !sizer_ptr.is_null() {
            // Forget the Rust wrapper BEFORE passing pointer ownership to C++
            std::mem::forget(sizer);
            unsafe {
                ffi::wxd_Window_SetSizerAndFit(window_ptr, sizer_ptr, delete_old_sizer);
            }
        }
        // Sizer ownership is transferred to C++.
    }
}

/// Trait for common wxWidget operations.
pub trait WxWidget: std::any::Any {
    /// Returns the raw underlying window pointer.
    /// Unsafe because the lifetime is not tied to self.
    /// Primarily for internal use or passing back to FFI.
    ///
    /// Note: For widgets using WindowHandle internally, this returns
    /// `None` (as null pointer) if the window has been destroyed.
    fn handle_ptr(&self) -> *mut ffi::wxd_Window_t;

    /// Check if this widget is still valid (not destroyed).
    ///
    /// Returns `true` if the underlying wxWidgets window exists and can be used.
    /// Returns `false` if the window has been destroyed (by explicit destroy()
    /// call, parent destruction, or any other means).
    ///
    /// # Example
    /// ```ignore
    /// let button = Button::builder(&frame).build();
    /// assert!(button.is_valid());
    ///
    /// frame.destroy();
    /// assert!(!button.is_valid()); // Button was destroyed with frame
    /// ```
    fn is_valid(&self) -> bool {
        // Default implementation: check if pointer is non-null
        // Widgets using WindowHandle will override this
        !self.handle_ptr().is_null()
    }

    /// Returns the window ID for this widget.
    fn get_id(&self) -> i32 {
        let handle = self.handle_ptr();
        if handle.is_null() {
            ffi::WXD_ID_ANY as i32 // Return ID_ANY if handle is null
        } else {
            // Call the new C API function to get the real ID
            unsafe { ffi::wxd_Window_GetId(handle) }
        }
    }

    /// Adjusts the window size to fit its contents or its sizer.
    fn fit(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Fit(handle) };
        }
    }

    /// Forces the window to recalculate its layout using its sizer.
    /// This is called when the window size changes to update the positions
    /// and sizes of child widgets according to the sizer constraints.
    fn layout(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Layout(handle) };
        }
    }

    /// Gets the window's sizer-calculated best size.
    fn get_best_size(&self) -> crate::geometry::Size {
        let handle = self.handle_ptr();
        if handle.is_null() {
            crate::geometry::Size { width: -1, height: -1 }
        } else {
            let c_size = unsafe { ffi::wxd_Window_GetBestSize(handle) };
            crate::geometry::Size {
                width: c_size.width,
                height: c_size.height,
            }
        }
    }

    /// Shows or hides the widget.
    fn show(&self, show: bool) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Show(handle, show) };
        }
    }

    /// Sets the window's background color.
    fn set_background_color(&self, color: crate::color::Colour) {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe {
                ffi::wxd_Window_SetBackgroundColor(window_ptr, color.into());
            }
        }
    }

    /// Sets the background style for the window.
    ///
    /// The background style determines how the window's background is painted:
    /// - `BackgroundStyle::Erase`: Default behavior, background erased automatically
    /// - `BackgroundStyle::System`: Background erased with current background color  
    /// - `BackgroundStyle::Paint`: No automatic background erasing, app handles it
    /// - `BackgroundStyle::Colour`: Background filled with background color before paint
    ///
    /// For smooth custom drawing and animations, use `BackgroundStyle::Paint`.
    fn set_background_style(&self, style: BackgroundStyle) {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe {
                ffi::wxd_Window_SetBackgroundStyle(window_ptr, style.to_raw());
            }
        }
    }

    /// Gets the background style for the window.
    fn get_background_style(&self) -> BackgroundStyle {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            let raw_style = unsafe { ffi::wxd_Window_GetBackgroundStyle(window_ptr) };
            BackgroundStyle::from_raw(raw_style)
        } else {
            BackgroundStyle::System // Default fallback
        }
    }

    /// Sets the window's minimum size.
    fn set_min_size(&self, size: crate::geometry::Size) {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe { ffi::wxd_Window_SetMinSize(window_ptr, size.into()) };
        }
    }

    /// Refreshes the window, optionally erasing the background and specifying a rectangle.
    fn refresh(&self, erase_background: bool, rect: Option<&crate::geometry::Rect>) {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            let c_rect_storage: wxdragon_sys::wxd_Rect;
            let c_rect_ptr: *const wxdragon_sys::wxd_Rect;
            if let Some(r_borrowed) = rect {
                // Need to convert from &crate::base::Rect to wxdragon_sys::wxd_Rect
                // Assuming crate::base::Rect has an into() or from() for wxdragon_sys::wxd_Rect
                // or we construct it manually if fields are compatible.
                // Let's assume Rect has x, y, width, height and `into()` exists
                c_rect_storage = (*r_borrowed).into();
                c_rect_ptr = &c_rect_storage as *const _;
            } else {
                c_rect_ptr = std::ptr::null();
            }
            unsafe {
                // Ensure eraseBackground is passed as int (0 or 1)
                ffi::wxd_Window_Refresh(window_ptr, if erase_background { 1 } else { 0 }, c_rect_ptr);
            }
        }
    }

    /// Repaints all invalid areas of the window immediately.
    ///
    /// This function forces an immediate repaint of any areas marked as invalid
    /// by previous calls to `refresh()`. Unlike `refresh()` which only marks
    /// areas as needing repaint, `update()` causes the paint event to be processed
    /// immediately rather than waiting for the next event loop iteration.
    ///
    /// This is typically used when you need to ensure the window is redrawn
    /// before continuing with other operations, such as during animation or
    /// progress display.
    ///
    /// # Example
    /// ```ignore
    /// // Mark the window as needing repaint
    /// window.refresh(true, None);
    /// // Force immediate repaint
    /// window.update();
    /// ```
    fn update(&self) {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe {
                ffi::wxd_Window_Update(window_ptr);
            }
        }
    }

    /// Sets the tooltip string for this widget.
    fn set_tooltip(&self, tip: &str) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            match std::ffi::CString::new(tip) {
                Ok(c_tip) => unsafe {
                    ffi::wxd_Window_SetToolTip(handle, c_tip.as_ptr());
                },
                Err(_) => {
                    // Handle CString creation error, perhaps log it or do nothing
                    // For now, do nothing if the string can't be converted (e.g., contains null bytes)
                }
            }
        }
    }

    /// Explicitly destroys the underlying wxWidgets object.
    /// After calling this, the widget wrapper should not be used further.
    /// This is useful for dynamically creating and destroying widgets.
    fn destroy(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            // It's important that the Rust wrapper doesn't try to access
            // the object after this. The object will be scheduled for deletion.
            unsafe { ffi::wxd_Window_Destroy(handle) };
            // Note: We might want to nullify the internal pointer in the specific widget's struct
            // if the struct allows mutable access to itself after destroy is called, though
            // typically after destroy(), the Rust wrapper instance should be dropped or not used.
        }
    }

    fn set_font(&self, font: &Font) {
        // Create a new Font object owned by the widget to avoid ownership issues
        let font_copy = font.to_owned();
        unsafe {
            ffi::wxd_Window_SetFont(self.handle_ptr(), font_copy.as_ptr());
        }
        // Intentionally leak the font as the C++ side now owns it
        std::mem::forget(font_copy);
    }

    /// Gets the font currently used for this widget.
    ///
    /// Returns `Some(Font)` if a valid font is found, or `None` if no font is set or the widget handle is invalid.
    fn get_font(&self) -> Option<crate::font::Font> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        let font_ptr = unsafe { ffi::wxd_Window_GetFont(handle) };
        if font_ptr.is_null() {
            return None;
        }

        // Create a Font object that takes ownership of the returned font pointer
        Some(unsafe { crate::font::Font::from_ptr(font_ptr, true) })
    }

    /// Gets the sizer currently assigned to this widget.
    ///
    /// Returns `Some(Sizer)` if a sizer is assigned, or `None` if no sizer is set or the widget handle is invalid.
    /// The returned sizer is a wrapper around the existing sizer - no ownership is transferred.
    fn get_sizer(&self) -> Option<crate::sizers::Sizer> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        let sizer_ptr = unsafe { ffi::wxd_Window_GetSizer(handle) };
        if sizer_ptr.is_null() {
            return None;
        }

        // Create a Sizer wrapper around the existing sizer pointer
        // Note: This does not take ownership - the sizer is still owned by the window
        unsafe { crate::sizers::Sizer::from_ptr(sizer_ptr) }
    }

    /// Sets the window's sizer.
    ///
    /// Takes ownership of the Sizer object.
    /// `delete_old_sizer`: If true, the previous sizer (if any) is deleted.
    ///
    /// No-op if the widget has been destroyed.
    fn set_sizer(&self, sizer: impl crate::sizers::WxSizer, delete_old_sizer: bool)
    where
        Self: Sized,
    {
        let window_ptr = self.handle_ptr();
        let sizer_ptr = sizer.as_sizer_ptr();
        if !window_ptr.is_null() && !sizer_ptr.is_null() {
            // Forget the Rust wrapper BEFORE passing pointer ownership to C++
            std::mem::forget(sizer);
            unsafe {
                ffi::wxd_Window_SetSizer(window_ptr, sizer_ptr, delete_old_sizer);
            }
        }
        // Sizer ownership is transferred to C++.
    }

    /// Sets the window's sizer and calls `Fit()` on the window.
    ///
    /// Takes ownership of the Sizer object.
    /// `delete_old_sizer`: If true, the previous sizer (if any) is deleted.
    ///
    /// No-op if the widget has been destroyed.
    fn set_sizer_and_fit(&self, sizer: impl crate::sizers::WxSizer, delete_old_sizer: bool)
    where
        Self: Sized,
    {
        let window_ptr = self.handle_ptr();
        let sizer_ptr = sizer.as_sizer_ptr();
        if !window_ptr.is_null() && !sizer_ptr.is_null() {
            // Forget the Rust wrapper BEFORE passing pointer ownership to C++
            std::mem::forget(sizer);
            unsafe {
                ffi::wxd_Window_SetSizerAndFit(window_ptr, sizer_ptr, delete_old_sizer);
            }
        }
        // Sizer ownership is transferred to C++.
    }

    /// Enables or disables the widget.
    ///
    /// A disabled widget does not receive user input and is usually visually distinct.
    fn enable(&self, enable: bool) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Enable(handle, enable) }
        }
    }

    /// Returns `true` if the widget is enabled, `false` otherwise.
    fn is_enabled(&self) -> bool {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_IsEnabled(handle) }
        } else {
            false // If handle is null, widget can't be enabled
        }
    }

    /// Gets the window's position relative to its parent.
    fn get_position(&self) -> Point {
        let handle = self.handle_ptr();
        if handle.is_null() {
            Point { x: -1, y: -1 }
        } else {
            let pos = unsafe { ffi::wxd_Window_GetPosition(handle) };
            Point { x: pos.x, y: pos.y }
        }
    }

    /// Gets the window's size.
    fn get_size(&self) -> Size {
        let handle = self.handle_ptr();
        if handle.is_null() {
            Size { width: -1, height: -1 }
        } else {
            let size = unsafe { ffi::wxd_Window_GetSize(handle) };
            Size {
                width: size.width,
                height: size.height,
            }
        }
    }

    /// Sets the window's size.
    fn set_size(&self, size: Size) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_SetSize(handle, size.into()) }
        }
    }

    /// Sets the window's position and size.
    fn set_size_with_pos(&self, x: i32, y: i32, width: i32, height: i32) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_SetSizeWithPos(handle, x, y, width, height, ffi::WXD_SIZE_AUTO as i32) }
        }
    }

    /// Sets the window's client area size (the area inside borders, scrollbars, etc).
    fn set_client_size(&self, size: Size) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_SetClientSize(handle, size.into()) }
        }
    }

    /// Gets the client area size.
    fn get_client_size(&self) -> Size {
        let handle = self.handle_ptr();
        if handle.is_null() {
            Size { width: -1, height: -1 }
        } else {
            let size = unsafe { ffi::wxd_Window_GetClientSize(handle) };
            Size {
                width: size.width,
                height: size.height,
            }
        }
    }

    /// Gets the window's minimum size.
    fn get_min_size(&self) -> Size {
        let handle = self.handle_ptr();
        if handle.is_null() {
            Size { width: -1, height: -1 }
        } else {
            let size = unsafe { ffi::wxd_Window_GetMinSize(handle) };
            Size {
                width: size.width,
                height: size.height,
            }
        }
    }

    /// Moves the window to the specified position.
    fn move_window(&self, x: i32, y: i32) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Move(handle, x, y) }
        }
    }

    /// Centers the window relative to its parent.
    fn center(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Center(handle) }
        }
    }

    /// UK spelling alias for center()
    fn centre(&self) {
        self.center()
    }

    /// Converts client coordinates to screen coordinates.
    fn client_to_screen(&self, pt: Point) -> Point {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return pt; // Return the same point if the handle is null
        }

        let result = unsafe { ffi::wxd_Window_ClientToScreen(handle, pt.into()) };
        Point {
            x: result.x,
            y: result.y,
        }
    }

    /// Converts screen coordinates to client coordinates.
    fn screen_to_client(&self, pt: Point) -> Point {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return pt; // Return the same point if the handle is null
        }

        let result = unsafe { ffi::wxd_Window_ScreenToClient(handle, pt.into()) };
        Point {
            x: result.x,
            y: result.y,
        }
    }

    /// Gets the window label (title or text).
    /// Returns `None` if the label is not set, cannot be converted to UTF-8, or an error occurs.
    fn get_label(&self) -> Option<String> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        let len = unsafe { ffi::wxd_Window_GetLabel(handle, std::ptr::null_mut(), 0) };
        if len < 0 {
            return None; // No label set
        }

        let mut buf = vec![0; len as usize + 1];
        unsafe { ffi::wxd_Window_GetLabel(handle, buf.as_mut_ptr(), buf.len()) };
        Some(unsafe { CStr::from_ptr(buf.as_ptr()).to_string_lossy().to_string() })
    }

    /// Sets the window label (title or text).
    ///
    /// # Arguments
    /// * `label` - The label text to set
    fn set_label(&self, label: &str) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            match std::ffi::CString::new(label) {
                Ok(c_label) => unsafe {
                    ffi::wxd_Window_SetLabel(handle, c_label.as_ptr());
                },
                Err(_) => {
                    // Handle CString creation error (e.g., contains null bytes)
                    // For now, do nothing if the string can't be converted
                }
            }
        }
    }

    /// Sets the extra window style flags.
    ///
    /// Extra window styles are additional style flags that control special window behaviors.
    /// You can combine multiple styles using the bitwise OR operator (`|`).
    ///
    /// # Arguments
    /// * `extra_style` - The extra style flags to set
    ///
    /// # Example
    /// ```ignore
    /// use wxdragon::prelude::*;
    ///
    /// // Enable idle event processing for this window
    /// window.set_extra_style(ExtraWindowStyle::ProcessIdle);
    ///
    /// // Enable multiple features
    /// window.set_extra_style(ExtraWindowStyle::ProcessIdle | ExtraWindowStyle::ValidateRecursively);
    /// ```
    fn set_extra_style(&self, extra_style: ExtraWindowStyle) {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe {
                ffi::wxd_Window_SetExtraStyle(window_ptr, extra_style.bits());
            }
        }
    }

    /// Sets extra window style flags using raw i64 value.
    ///
    /// This is provided for cases where you need to set flags not covered by the enum.
    /// For normal usage, prefer `set_extra_style()` with the enum.
    fn set_extra_style_raw(&self, extra_style: i64) {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe {
                ffi::wxd_Window_SetExtraStyle(window_ptr, extra_style);
            }
        }
    }

    /// Gets the current extra window style flags as raw value.
    ///
    /// # Returns
    /// The currently set extra style flags for this window as a raw i64 value.
    /// Use `ExtraWindowStyle` variants to check for specific flags.
    fn get_extra_style_raw(&self) -> i64 {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe { ffi::wxd_Window_GetExtraStyle(window_ptr) }
        } else {
            0
        }
    }

    /// Checks if a specific extra window style flag is set.
    ///
    /// # Arguments
    /// * `style` - The style flag to check for
    ///
    /// # Returns
    /// `true` if the style flag is set, `false` otherwise
    ///
    /// # Example
    /// ```ignore
    /// if window.has_extra_style(ExtraWindowStyle::ProcessIdle) {
    ///     println!("Window will receive idle events");
    /// }
    /// ```
    fn has_extra_style(&self, style: ExtraWindowStyle) -> bool {
        let current_style = self.get_extra_style_raw();
        (current_style & style.bits()) != 0
    }

    /// Adds extra window style flags to the current set.
    ///
    /// This is equivalent to `set_extra_style(get_extra_style_raw() | new_style.bits())`
    /// but more convenient for adding flags without removing existing ones.
    fn add_extra_style(&self, style: ExtraWindowStyle) {
        let current_style = self.get_extra_style_raw();
        self.set_extra_style_raw(current_style | style.bits());
    }

    /// Removes extra window style flags from the current set.
    ///
    /// This removes the specified flags while preserving other flags.
    fn remove_extra_style(&self, style: ExtraWindowStyle) {
        let current_style = self.get_extra_style_raw();
        self.set_extra_style_raw(current_style & !style.bits());
    }

    /// Gets the parent window of this widget.
    ///
    /// # Returns
    /// `Some(Window)` if the widget has a parent, `None` if it's a top-level window or an error occurs.
    fn get_parent(&self) -> Option<Window> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        let parent_ptr = unsafe { ffi::wxd_Window_GetParent(handle) };
        if parent_ptr.is_null() {
            None
        } else {
            Some(unsafe { Window::from_ptr(parent_ptr) })
        }
    }

    // --- Color Management ---

    /// Sets the foreground color of the window.
    ///
    /// The foreground color is typically used for text and other foreground elements.
    fn set_foreground_color(&self, color: crate::color::Colour) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe {
                ffi::wxd_Window_SetForegroundColor(handle, color.into());
            }
        }
    }

    /// Gets the foreground color of the window.
    ///
    /// # Returns
    /// The current foreground color, or black if the window handle is invalid.
    fn get_foreground_color(&self) -> crate::color::Colour {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return crate::color::Colour::new(0, 0, 0, 255); // Default black
        }
        let color = unsafe { ffi::wxd_Window_GetForegroundColor(handle) };
        crate::color::Colour::new(color.r, color.g, color.b, color.a)
    }

    /// Gets the background color of the window.
    ///
    /// # Returns
    /// The current background color, or white if the window handle is invalid.
    fn get_background_color(&self) -> crate::color::Colour {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return crate::color::Colour::new(255, 255, 255, 255); // Default white
        }
        let color = unsafe { ffi::wxd_Window_GetBackgroundColor(handle) };
        crate::color::Colour::new(color.r, color.g, color.b, color.a)
    }

    // --- Focus Management ---

    /// Sets the focus to this window.
    ///
    /// This makes the window the active window that receives keyboard input.
    fn set_focus(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_SetFocus(handle) };
        }
    }

    /// Returns `true` if this window currently has focus.
    fn has_focus(&self) -> bool {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_HasFocus(handle) }
        } else {
            false
        }
    }

    /// Returns `true` if this window can accept focus.
    ///
    /// This is typically `true` for interactive controls like buttons and text fields,
    /// and `false` for static controls like labels.
    fn can_accept_focus(&self) -> bool {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_CanAcceptFocus(handle) }
        } else {
            false
        }
    }

    /// Returns `true` if this window accepts focus from keyboard navigation.
    ///
    /// This determines whether the window can receive focus when the user presses Tab
    /// or other keyboard navigation keys. By default, this returns the same as `can_accept_focus()`,
    /// but some controls may override this to accept focus from mouse clicks but not keyboard navigation.
    fn accepts_focus_from_keyboard(&self) -> bool {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_AcceptsFocusFromKeyboard(handle) }
        } else {
            false
        }
    }

    /// Sets whether this window can accept focus.
    ///
    /// This can be used to enable or disable focus for a window. When set to `false`,
    /// the window will not be able to receive keyboard focus through any means.
    /// When set to `true`, the window's ability to receive focus depends on its type
    /// and other factors.
    ///
    /// # Arguments
    /// * `can_focus` - Whether the window should be able to accept focus
    ///
    /// # Example
    /// ```ignore
    /// // Disable focus for a button
    /// button.set_can_focus(false);
    ///
    /// // Re-enable focus later
    /// button.set_can_focus(true);
    /// ```
    fn set_can_focus(&self, can_focus: bool) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_SetCanFocus(handle, can_focus) };
        }
    }

    // --- Visibility ---

    /// Returns `true` if the window is currently shown.
    ///
    /// This checks the window's visibility state, which may be different from
    /// whether it's actually visible on screen (e.g., if it's covered by other windows).
    fn is_shown(&self) -> bool {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_IsShown(handle) }
        } else {
            false
        }
    }

    /// Hides the window.
    ///
    /// This is equivalent to calling `show(false)`.
    fn hide(&self) {
        self.show(false);
    }

    // --- Size Constraints ---

    /// Sets the maximum size for the window.
    ///
    /// The window will not be allowed to grow larger than this size.
    /// Use `Size { width: -1, height: -1 }` to remove size constraints.
    fn set_max_size(&self, size: crate::geometry::Size) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe {
                ffi::wxd_Window_SetMaxSize(handle, size.into());
            }
        }
    }

    /// Gets the maximum size for the window.
    ///
    /// # Returns
    /// The maximum size, or `Size { width: -1, height: -1 }` if no maximum is set
    /// or the window handle is invalid.
    fn get_max_size(&self) -> crate::geometry::Size {
        let handle = self.handle_ptr();
        if handle.is_null() {
            crate::geometry::Size { width: -1, height: -1 }
        } else {
            let size = unsafe { ffi::wxd_Window_GetMaxSize(handle) };
            crate::geometry::Size {
                width: size.width,
                height: size.height,
            }
        }
    }

    // --- Window Properties ---

    /// Sets the window name.
    ///
    /// The window name is different from the label and is used for identification
    /// purposes, such as finding windows by name.
    fn set_name(&self, name: &str) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            match std::ffi::CString::new(name) {
                Ok(c_name) => unsafe {
                    ffi::wxd_Window_SetName(handle, c_name.as_ptr());
                },
                Err(_) => {
                    // Handle CString creation error (e.g., contains null bytes)
                    // For now, do nothing if the string can't be converted
                }
            }
        }
    }

    /// Gets the window name.
    ///
    /// # Returns
    /// The window name, or an empty string if no name is set or an error occurs.
    fn get_name(&self) -> String {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return String::new();
        }

        let len = unsafe { ffi::wxd_Window_GetName(handle, std::ptr::null_mut(), 0) };
        if len <= 0 {
            return String::new();
        }

        let mut b = vec![0; len as usize + 1];
        unsafe { ffi::wxd_Window_GetName(handle, b.as_mut_ptr(), b.len()) };
        unsafe { CStr::from_ptr(b.as_ptr()).to_string_lossy().to_string() }
    }

    /// Attempts to close the window.
    ///
    /// This generates a close event which can be vetoed by the application.
    /// For top-level windows, this is typically equivalent to clicking the close button.
    ///
    /// # Arguments
    /// * `force` - If `true`, the window is destroyed even if the close event is vetoed
    ///
    /// # Returns
    /// `true` if the window was closed, `false` if the close was vetoed
    fn close(&self, force: bool) -> bool {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Close(handle, force) }
        } else {
            false
        }
    }

    // --- Window Finding ---

    /// Finds a child window by name.
    ///
    /// This searches all child windows recursively for a window with the specified name.
    /// The name is set using `set_name()` and is different from the label.
    ///
    /// # Arguments
    /// * `name` - The name of the window to find
    ///
    /// # Returns
    /// `Some(Window)` if a window with the given name is found, `None` otherwise
    ///
    /// # Example
    /// ```ignore
    /// // Set a name on a child control
    /// label.set_name("status_label");
    ///
    /// // Later, find it by name
    /// if let Some(status_label) = panel.find_window_by_name("status_label") {
    ///     // Use the found window
    /// }
    /// ```
    fn find_window_by_name(&self, name: &str) -> Option<Window> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        match std::ffi::CString::new(name) {
            Ok(c_name) => {
                let child_ptr = unsafe { wxd_Window_FindWindowByName(handle, c_name.as_ptr()) };
                if child_ptr.is_null() {
                    None
                } else {
                    Some(unsafe { Window::from_ptr(child_ptr) })
                }
            }
            Err(_) => None, // CString creation failed (e.g., name contains null bytes)
        }
    }

    /// Finds a child window by ID.
    ///
    /// This searches all child windows recursively for a window with the specified ID.
    ///
    /// # Arguments
    /// * `id` - The ID of the window to find
    ///
    /// # Returns
    /// `Some(Window)` if a window with the given ID is found, `None` otherwise
    ///
    /// # Example
    /// ```ignore
    /// // Find a window by its ID
    /// if let Some(button) = panel.find_window_by_id(1001) {
    ///     // Use the found window
    /// }
    /// ```
    fn find_window_by_id(&self, id: i32) -> Option<Window> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        let child_ptr = unsafe { wxd_Window_FindWindowById(handle, id) };
        if child_ptr.is_null() {
            None
        } else {
            Some(unsafe { Window::from_ptr(child_ptr) })
        }
    }

    // --- Cursor Management ---

    /// Sets the cursor for this window.
    ///
    /// The cursor will be displayed when the mouse pointer is over this window.
    /// Pass `None` to reset to the default cursor.
    ///
    /// # Arguments
    /// * `cursor` - The cursor to set, or `None` for default
    fn set_cursor(&self, cursor: Option<&crate::cursor::Cursor>) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            let cursor_ptr = cursor.map(|c| c.as_ptr()).unwrap_or(std::ptr::null_mut());
            unsafe {
                ffi::wxd_Window_SetCursor(handle, cursor_ptr);
            }
        }
    }

    /// Gets the cursor currently associated with this window.
    ///
    /// # Returns
    /// `Some(Cursor)` if a cursor is set, `None` if no cursor is set or an error occurs
    fn get_cursor(&self) -> Option<crate::cursor::Cursor> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        let cursor_ptr = unsafe { ffi::wxd_Window_GetCursor(handle) };
        if cursor_ptr.is_null() {
            None
        } else {
            unsafe { crate::cursor::Cursor::from_ptr(cursor_ptr) }
        }
    }

    // --- Z-Order Management ---

    /// Raises the window to the top of the window hierarchy (Z-order).
    ///
    /// This makes the window appear on top of other windows.
    fn raise(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Raise(handle) };
        }
    }

    /// Lowers the window to the bottom of the window hierarchy (Z-order).
    ///
    /// This makes the window appear behind other windows.
    fn lower(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Lower(handle) };
        }
    }

    // --- Mouse Capture ---

    /// Directs all mouse input to this window.
    ///
    /// Use `release_mouse()` to release the capture.
    /// Only one window can capture the mouse at a time.
    fn capture_mouse(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_CaptureMouse(handle) };
        }
    }

    /// Releases mouse capture.
    ///
    /// This should be called after `capture_mouse()` when mouse capture is no longer needed.
    fn release_mouse(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_ReleaseMouse(handle) };
        }
    }

    /// Returns `true` if this window currently has mouse capture.
    fn has_capture(&self) -> bool {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_HasCapture(handle) }
        } else {
            false
        }
    }

    /// Returns the window that currently has mouse capture.
    ///
    /// This is a static function that can be called on any window instance.
    ///
    /// # Returns
    /// `Some(Window)` if a window has capture, `None` if no window has capture
    fn get_capture() -> Option<Window>
    where
        Self: Sized,
    {
        let window_ptr = unsafe { ffi::wxd_Window_GetCapture() };
        if window_ptr.is_null() {
            None
        } else {
            Some(unsafe { Window::from_ptr(window_ptr) })
        }
    }

    // --- Painting The Window ---

    /// Freeze the window: don't redraw it until it is thawed
    fn freeze(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Freeze(handle) }
        }
    }

    /// Thaw the window: redraw it after it had been frozen
    fn thaw(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_Thaw(handle) }
        }
    }

    /// Return true if window had been frozen and not unthawed yet
    fn is_frozen(&self) -> bool {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_IsFrozen(handle) }
        } else {
            false
        }
    }

    // --- Text Measurement ---

    /// Gets the dimensions of the string as it would be drawn on the window with the currently selected font.
    ///
    /// # Arguments
    /// * `text` - The text to measure
    ///
    /// # Returns
    /// The size of the text in pixels
    fn get_text_extent(&self, text: &str) -> crate::geometry::Size {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return crate::geometry::Size { width: 0, height: 0 };
        }

        match std::ffi::CString::new(text) {
            Ok(c_text) => {
                let size = unsafe { ffi::wxd_Window_GetTextExtent(handle, c_text.as_ptr()) };
                crate::geometry::Size {
                    width: size.width,
                    height: size.height,
                }
            }
            Err(_) => crate::geometry::Size { width: 0, height: 0 },
        }
    }

    /// Gets the full dimensions of the string as it would be drawn on the window.
    ///
    /// This provides more detailed information than `get_text_extent()`.
    ///
    /// # Arguments
    /// * `text` - The text to measure
    /// * `font` - Optional font to use for measurement (uses window's font if None)
    ///
    /// # Returns
    /// A tuple containing:
    /// - `Size`: The width and height of the text
    /// - `i32`: The descent (portion below baseline)
    /// - `i32`: The external leading (spacing between lines)
    fn get_full_text_extent(&self, text: &str, font: Option<&crate::font::Font>) -> (crate::geometry::Size, i32, i32) {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return (crate::geometry::Size { width: 0, height: 0 }, 0, 0);
        }

        match std::ffi::CString::new(text) {
            Ok(c_text) => {
                let mut size = wxdragon_sys::wxd_Size { width: 0, height: 0 };
                let mut descent = 0i32;
                let mut external_leading = 0i32;
                let font_ptr = font.map(|f| f.as_ptr()).unwrap_or(std::ptr::null_mut());

                unsafe {
                    ffi::wxd_Window_GetFullTextExtent(
                        handle,
                        c_text.as_ptr(),
                        &mut size as *mut _,
                        &mut descent as *mut _,
                        &mut external_leading as *mut _,
                        font_ptr,
                    );
                }

                (
                    crate::geometry::Size {
                        width: size.width,
                        height: size.height,
                    },
                    descent,
                    external_leading,
                )
            }
            Err(_) => (crate::geometry::Size { width: 0, height: 0 }, 0, 0),
        }
    }

    /// Returns the character height for this window using the current font.
    ///
    /// # Returns
    /// The height of a character in pixels
    fn get_char_height(&self) -> i32 {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_GetCharHeight(handle) }
        } else {
            0
        }
    }

    /// Returns the average character width for this window using the current font.
    ///
    /// # Returns
    /// The average width of a character in pixels
    fn get_char_width(&self) -> i32 {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { ffi::wxd_Window_GetCharWidth(handle) }
        } else {
            0
        }
    }

    // --- Window Style Management ---

    /// Sets the window style flags.
    ///
    /// Window styles control fundamental behaviors and appearance of the window.
    /// You can combine multiple styles using the bitwise OR operator (`|`).
    ///
    /// # Arguments
    /// * `style` - The window style flags to set
    ///
    /// # Example
    /// ```
    /// # use wxdragon::prelude::*;
    /// # use wxdragon::WindowStyle;
    /// # fn example(window: &Window) {
    /// // Set window to be visible with a overlapped and resize border
    /// window.set_style(WindowStyle::Visible | WindowStyle::Overlapped | WindowStyle::ThickFrame);
    ///
    /// // Make window a popup window
    /// window.set_style(WindowStyle::Popup | WindowStyle::Visible);
    /// # }
    /// ```
    ///
    /// # Note
    /// Some style changes may not take effect until the window is recreated or refreshed.
    /// Certain style combinations are mutually exclusive (e.g., Child and Popup).
    fn set_style(&self, style: WindowStyle) {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe {
                ffi::wxd_Window_SetWindowStyle(window_ptr, style.bits());
            }
        }
    }

    /// Sets window style flags using raw i64 value.
    ///
    /// This is provided for cases where you need to set flags not covered by the enum.
    /// For normal usage, prefer `set_style()` with the WindowStyle enum.
    ///
    /// # Arguments
    /// * `style` - The raw style flags value
    fn set_style_raw(&self, style: i64) {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe {
                ffi::wxd_Window_SetWindowStyle(window_ptr, style);
            }
        }
    }

    /// Gets the current window style flags as raw value.
    ///
    /// # Returns
    /// The currently set window style flags for this window as a raw i64 value.
    /// Use `WindowStyle` variants to check for specific flags.
    ///
    /// # Example
    /// ```
    /// # use wxdragon::prelude::*;
    /// # use wxdragon::WindowStyle;
    /// # fn example(window: &Window) {
    /// let current_style = window.get_style_raw();
    /// if (current_style & WindowStyle::Visible.bits()) != 0 {
    ///     println!("Window is visible");
    /// }
    /// # }
    /// ```
    fn get_style_raw(&self) -> i64 {
        let window_ptr = self.handle_ptr();
        if !window_ptr.is_null() {
            unsafe { ffi::wxd_Window_GetWindowStyle(window_ptr) }
        } else {
            0
        }
    }

    /// Checks if a specific window style flag is set.
    ///
    /// # Arguments
    /// * `style` - The style flag to check for
    ///
    /// # Returns
    /// `true` if the style flag is set, `false` otherwise
    ///
    /// # Example
    /// ```
    /// # use wxdragon::prelude::*;
    /// # use wxdragon::WindowStyle;
    /// # fn example(window: &Window) {
    /// if window.has_style(WindowStyle::Visible) {
    ///     println!("Window is visible");
    /// }
    ///
    /// if window.has_style(WindowStyle::Overlapped | WindowStyle::SysMenu) {
    ///     println!("Window has both overlapped and system menu");
    /// }
    /// # }
    /// ```
    fn has_style(&self, style: WindowStyle) -> bool {
        let current_style = self.get_style_raw();
        (current_style & style.bits()) == style.bits()
    }

    /// Adds window style flags to the current set.
    ///
    /// This is equivalent to `set_style_raw(get_style_raw() | new_style.bits())`
    /// but more convenient for adding flags without removing existing ones.
    ///
    /// # Arguments
    /// * `style` - The style flags to add
    ///
    /// # Example
    /// ```ignore
    /// // Add visible flag while preserving other styles
    /// window.add_style(WindowStyle::Visible);
    /// ```
    fn add_style(&self, style: WindowStyle) {
        let current_style = self.get_style_raw();
        self.set_style_raw(current_style | style.bits());
    }

    /// Removes window style flags from the current set.
    ///
    /// This removes the specified flags while preserving other flags.
    ///
    /// # Arguments
    /// * `style` - The style flags to remove
    ///
    /// # Example
    /// ```ignore
    /// // Remove maximize box while preserving other styles
    /// window.remove_style(WindowStyle::MaximizeBox);
    /// ```
    fn remove_style(&self, style: WindowStyle) {
        let current_style = self.get_style_raw();
        self.set_style_raw(current_style & !style.bits());
    }

    // Other common methods (SetSize, GetSize, etc.) can be added here
    // if corresponding wxd_Window_* functions are added to the C API.

    /// Gets the native handle of the window (platform-specific).
    ///
    /// # Returns
    /// A raw pointer to the native window, or null if not available
    ///
    /// # Safety
    /// The returned pointer should not be used to modify the window and may
    /// only be valid for the lifetime of this `Window` instance.
    ///
    fn get_handle(&self) -> *mut std::ffi::c_void {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return std::ptr::null_mut();
        }
        unsafe { ffi::wxd_Window_GetHandle(handle) }
    }

    /// Disables compositing for the window (Windows only).
    ///
    /// This can be useful for avoiding flickering or other issues with some controls.
    /// This method is only available on Windows.
    #[cfg(target_os = "windows")]
    fn msw_disable_composited(&self) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            unsafe { wxd_Window_MSWDisableComposited(handle) }
        }
    }

    // --- Tab Order Functions ---

    /// Moves this window to appear after the specified window in the tab order.
    ///
    /// This changes the tab order so that when tabbing through controls,
    /// this window will be visited immediately after `win`.
    ///
    /// # Arguments
    /// * `win` - The window that this window should appear after in tab order
    ///
    /// # Example
    /// ```ignore
    /// // Make button2 come after button1 in tab order
    /// button2.move_after_in_tab_order(&button1);
    /// ```
    fn move_after_in_tab_order(&self, win: &dyn WxWidget) {
        let handle = self.handle_ptr();
        let win_handle = win.handle_ptr();
        if !handle.is_null() && !win_handle.is_null() {
            unsafe { ffi::wxd_Window_MoveAfterInTabOrder(handle, win_handle) };
        }
    }

    /// Moves this window to appear before the specified window in the tab order.
    ///
    /// This changes the tab order so that when tabbing through controls,
    /// this window will be visited immediately before `win`.
    ///
    /// # Arguments
    /// * `win` - The window that this window should appear before in tab order
    ///
    /// # Example
    /// ```ignore
    /// // Make button1 come before button2 in tab order
    /// button1.move_before_in_tab_order(&button2);
    /// ```
    fn move_before_in_tab_order(&self, win: &dyn WxWidget) {
        let handle = self.handle_ptr();
        let win_handle = win.handle_ptr();
        if !handle.is_null() && !win_handle.is_null() {
            unsafe { ffi::wxd_Window_MoveBeforeInTabOrder(handle, win_handle) };
        }
    }

    /// Gets the next sibling window in the parent's child list.
    ///
    /// # Returns
    /// `Some(Window)` if there is a next sibling, `None` if this is the last child
    /// or if the window has no parent.
    fn get_next_sibling(&self) -> Option<Window> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        let sibling_ptr = unsafe { ffi::wxd_Window_GetNextSibling(handle) };
        if sibling_ptr.is_null() {
            None
        } else {
            Some(unsafe { Window::from_ptr(sibling_ptr) })
        }
    }

    /// Gets the previous sibling window in the parent's child list.
    ///
    /// # Returns
    /// `Some(Window)` if there is a previous sibling, `None` if this is the first child
    /// or if the window has no parent.
    fn get_prev_sibling(&self) -> Option<Window> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        let sibling_ptr = unsafe { ffi::wxd_Window_GetPrevSibling(handle) };
        if sibling_ptr.is_null() {
            None
        } else {
            Some(unsafe { Window::from_ptr(sibling_ptr) })
        }
    }

    /// Navigates to the next or previous control.
    ///
    /// This is equivalent to pressing Tab (forward) or Shift+Tab (backward)
    /// to move between controls that can accept focus.
    ///
    /// # Arguments
    /// * `forward` - If `true`, navigate to the next control; if `false`, navigate to the previous control
    ///
    /// # Returns
    /// `true` if navigation was successful, `false` otherwise
    ///
    /// # Example
    /// ```
    /// # use crate::wxdragon::WxWidget;
    /// # fn show_menu(window: &wxdragon::Window) {
    /// // Navigate to the previously focused control
    /// if window.navigate(false) {
    ///     println!("Successfully navigated to previous control");
    /// }
    /// # }
    /// ```
    fn navigate(&self, forward: bool) -> bool {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return false;
        }

        let flags = if forward {
            ffi::WXD_NAVIGATION_NEXT
        } else {
            ffi::WXD_NAVIGATION_PREVIOUS
        } as ::std::os::raw::c_int;
        unsafe { ffi::wxd_Window_Navigate(handle, flags) }
    }

    /// Shows a popup menu at the specified position or at the current mouse position.
    ///
    /// # Parameters
    ///
    /// * `menu` - The menu to display
    /// * `screen_pos` - Optional screen position where to show the menu. If `None`, the menu is shown at the current mouse position.
    ///
    /// # Returns
    ///
    /// `true` if a menu item was selected, `false` otherwise
    ///
    /// # Example
    ///
    /// ```
    /// # use wxdragon::prelude::*;
    /// # fn show_menu(window: &wxdragon::Window) {
    /// let mut menu = Menu::builder()
    ///     .append_item(1001, "Option 1", "")
    ///     .append_item(1002, "Option 2", "")
    ///     .build();
    /// window.popup_menu(&mut menu, None);
    /// # }
    /// ```
    fn popup_menu(&self, menu: &mut crate::Menu, screen_pos: Option<crate::geometry::Point>) -> bool {
        let handle = self.handle_ptr();
        if handle.is_null() || menu.as_mut_ptr().is_null() {
            return false;
        }
        let pos = screen_pos
            .map(|p| self.screen_to_client(p))
            .unwrap_or(Point::DEFAULT_POSITION);
        let pos_ptr = &pos as *const crate::geometry::Point as *const ffi::wxd_Point;

        unsafe { ffi::wxd_Window_PopupMenu(handle, menu.as_mut_ptr(), pos_ptr) }
    }

    /// Synchronously dispatch a wxEVT_MENU with the given command ID to this window.
    /// Returns true if any handler processed the event.
    fn process_menu_command(&self, id: i32) -> bool {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return false;
        }
        unsafe { ffi::wxd_Window_ProcessMenuCommand(handle, id) }
    }

    /// Asynchronously post a wxEVT_MENU with the given command ID to this window.
    /// The event will be queued and delivered later by the main loop.
    fn post_menu_command(&self, id: i32) {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return;
        }
        unsafe { ffi::wxd_Window_PostMenuCommand(handle, id) }
    }

    /// Sets the accessible object for this window.
    ///
    /// The window takes ownership of the accessible object.
    fn set_accessible(&self, accessible: Accessible) {
        let handle = self.handle_ptr();
        if !handle.is_null() {
            let acc_ptr = accessible.as_ptr();
            // Window takes ownership, so we forget the Rust wrapper
            std::mem::forget(accessible);
            unsafe {
                ffi::wxd_Window_SetAccessible(handle, acc_ptr);
            }
        }
    }

    /// Gets the accessible object for this window.
    ///
    /// Note: The returned `Accessible` object is owned by the window.
    /// It should not be dropped by the caller.
    fn get_accessible(&self) -> Option<Accessible> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }
        let acc_ptr = unsafe { ffi::wxd_Window_GetAccessible(handle) };
        if acc_ptr.is_null() {
            None
        } else {
            Some(unsafe { Accessible::from_ptr(acc_ptr, false) })
        }
    }
}

/// Trait for widgets that can be cast from a Window using class name matching
pub trait FromWindowWithClassName: Sized {
    /// Returns the expected wxWidgets class name for this widget type
    fn class_name() -> &'static str;

    /// Safely construct this widget from a raw window pointer
    /// This should only be called after verifying the class name matches
    ///
    /// # Safety
    ///
    /// The caller must ensure that:
    /// - `ptr` is a valid, non-null pointer to a wxWidgets window object
    /// - The window object pointed to by `ptr` is actually of the correct widget type
    ///   (i.e., the class name has been verified to match `Self::class_name()`)
    /// - The window object will remain valid for the lifetime of the returned widget
    /// - No other Rust objects are concurrently accessing the same wxWidgets object
    ///   in a way that could cause memory safety issues
    unsafe fn from_ptr(ptr: *mut ffi::wxd_Window_t) -> Self;
}

impl Window {
    /// Gets the wxWidgets class name for this window using built-in RTTI
    pub fn get_class_name(&self) -> Option<String> {
        let handle = self.handle_ptr();
        if handle.is_null() {
            return None;
        }

        let len = unsafe { ffi::wxd_Window_GetClassName(handle, std::ptr::null_mut(), 0) };
        if len < 0 {
            return None;
        }

        let mut buf = vec![0; len as usize + 1];
        unsafe { ffi::wxd_Window_GetClassName(handle, buf.as_mut_ptr(), buf.len()) };
        Some(unsafe { CStr::from_ptr(buf.as_ptr()).to_string_lossy().to_string() })
    }

    /// Generic method to cast this window to a specific widget type
    /// Uses wxWidgets' built-in RTTI to safely verify the type before casting
    pub fn as_widget<T: FromWindowWithClassName>(&self) -> Option<T> {
        if let Some(class_name) = self.get_class_name() {
            if class_name == T::class_name() {
                Some(unsafe { T::from_ptr(self.handle_ptr()) })
            } else {
                None
            }
        } else {
            None
        }
    }
}

/// Trait for downcasting wxWidgets to specific types.
///
/// This trait is automatically implemented for any type that implements both
/// `WxWidget` and `Any`, providing safe downcasting functionality.
///
/// # Example
/// ```
/// # use wxdragon::WxWidget;
/// # use wxdragon::window::WxWidgetDowncast;
/// # use wxdragon::widgets::TextCtrl;
///
/// # fn handle_widget(widget: &dyn WxWidget) {
///     if let Some(text_ctrl) = widget.downcast_ref::<TextCtrl>() {
///         let value = text_ctrl.get_value();
///         println!("Text control value: {}", value);
///     }
/// # }
/// ```
pub trait WxWidgetDowncast {
    /// Attempts to downcast this widget to a specific type.
    /// Returns `Some(&T)` if the widget is of type `T`, `None` otherwise.
    fn downcast_ref<T: WxWidget + 'static>(&self) -> Option<&T>;

    /// Attempts to downcast this widget to a specific type (mutable).
    /// Returns `Some(&mut T)` if the widget is of type `T`, `None` otherwise.
    fn downcast_mut<T: WxWidget + 'static>(&mut self) -> Option<&mut T>;

    /// Returns the type name of this widget for debugging purposes.
    fn widget_type_name(&self) -> &'static str;
}

/// Blanket implementation: any type that implements both WxWidget and Any
/// automatically gets downcasting functionality.
impl<W> WxWidgetDowncast for W
where
    W: WxWidget + std::any::Any,
{
    fn downcast_ref<T: WxWidget + 'static>(&self) -> Option<&T> {
        (self as &dyn std::any::Any).downcast_ref::<T>()
    }

    fn downcast_mut<T: WxWidget + 'static>(&mut self) -> Option<&mut T> {
        (&mut *self as &mut dyn std::any::Any).downcast_mut::<T>()
    }

    fn widget_type_name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }
}

// Provide downcasting for trait objects `dyn WxWidget` as well, so callers holding
// `&dyn WxWidget` or `&mut dyn WxWidget` (e.g., editor widgets) can downcast safely.
impl WxWidgetDowncast for dyn WxWidget {
    fn downcast_ref<T: WxWidget + 'static>(&self) -> Option<&T> {
        (self as &dyn std::any::Any).downcast_ref::<T>()
    }

    fn downcast_mut<T: WxWidget + 'static>(&mut self) -> Option<&mut T> {
        (self as &mut dyn std::any::Any).downcast_mut::<T>()
    }

    fn widget_type_name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }
}

// Implement the trait for the base Window struct itself.
impl WxWidget for Window {
    fn handle_ptr(&self) -> *mut ffi::wxd_Window_t {
        self.0 // Return the raw pointer directly
    }
    // get_id, show use the default trait implementation.
    // set_sizer and set_sizer_and_fit REMOVED from trait
}

// --- Event Handling Implementation ---

impl WxEvtHandler for Window {
    unsafe fn get_event_handler_ptr(&self) -> *mut ffi::wxd_EvtHandler_t {
        self.0 as *mut ffi::wxd_EvtHandler_t
    }
}

// ---------------------------------------------------------------------------
// Unit tests for WindowHandle behavior
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    // This test exercises the wxWidgets main loop. On macOS the Cargo test
    // harness runs each test in a separate thread, which is *not* the OS main
    // thread. wxWidgets requires initialization and event handling on the main
    // thread; calling `wxdragon::main` from a worker thread causes the callback
    // to execute on the real main thread instead, so the test thread never
    // receives output or exits the loop.  As a result the test hangs and even the
    // initial `println!` inside the closure is never visible.
    //
    // The simplest workaround is to skip this test on macOS.  It still runs on
    // other platforms where the test harness thread may be treated as the
    // main thread, and the behavior being verified is platform‑agnostic.
    #[cfg_attr(target_os = "macos", ignore)]
    #[test]
    fn child_destroy_does_not_invalidate_parent() {
        use super::*;
        use crate::prelude::*;
        use crate::widgets::{Frame, Panel, StaticText};

        SystemOptions::set_option_by_int("msw.no-manifest-check", 1);
        let timer_store: std::rc::Rc<std::cell::RefCell<Option<Timer<Frame>>>> = std::rc::Rc::new(std::cell::RefCell::new(None));
        let timer_store_clone = timer_store.clone();

        let res = crate::main(move |app| {
            let frame = Frame::builder().with_title("test").build();
            // frame.show(true);

            let panel = Panel::builder(&frame).build();
            assert!(panel.is_valid(), "panel should start valid");

            let label = StaticText::builder(&panel).with_label("temp").build();
            // explicitly destroy child
            label.destroy();

            // if the fix is correct, the parent should still be valid
            assert!(panel.is_valid(), "panel was invalidated by child destruction");

            // schedule exit via a one-shot timer after 100ms
            let timer = Timer::new(&frame);
            let app_clone = app;
            timer.on_tick(move |_evt| {
                app_clone.exit_main_loop();
            });
            timer.start(100, true);
            timer_store_clone.borrow_mut().replace(timer);
        });
        if let Err(e) = res {
            log::warn!("Test failed with error: {:?}", e);
        }
    }
}