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
//! wxTreeCtrl wrapper
//!
//! The `TreeCtrl` widget provides a tree control for displaying hierarchical data.
//! This module uses the `HasItemData` trait for associating custom data with tree items.
//!
//! # Examples
//!
//! ```rust,no_run
//! use wxdragon::prelude::*;
//! use wxdragon::widgets::treectrl::{TreeCtrl, TreeCtrlStyle};
//! use wxdragon::HasItemData;
//!
//! // Create custom data to associate with tree items
//! #[derive(Clone)]
//! struct PersonData {
//!     name: String,
//!     age: u32,
//!     role: String,
//! }
//!
//! fn create_tree_with_data(parent: &dyn WxWidget) -> TreeCtrl {
//!     // Create a tree control
//!     let tree = TreeCtrl::builder(parent)
//!         .with_style(TreeCtrlStyle::HasButtons | TreeCtrlStyle::LinesAtRoot)
//!         .build();
//!
//!     // Add root with associated data
//!     let ceo = PersonData {
//!         name: "John Smith".to_string(),
//!         age: 52,
//!         role: "CEO".to_string(),
//!     };
//!     let root = tree.add_root_with_data("Company", ceo, None, None).unwrap();
//!
//!     // Add child with different data type
//!     tree.append_item_with_data(&root, "Budget", 1000000, None, None).unwrap();
//!
//!     // Add another child with string data
//!     tree.append_item_with_data(
//!         &root,
//!         "Mission",
//!         "To create amazing products".to_string(),
//!         None,
//!         None,
//!     ).unwrap();
//!
//!     // Later, when handling selection events:
//!     // if let Some(item_id) = tree.get_selection() {
//!     //     if let Some(data) = tree.get_custom_data(&item_id) {
//!     //         if let Some(person) = data.downcast_ref::<PersonData>() {
//!     //             println!("Selected person: {}", person.name);
//!     //         } else if let Some(budget) = data.downcast_ref::<i32>() {
//!     //             println!("Selected budget: ${}", budget);
//!     //         } else if let Some(text) = data.downcast_ref::<String>() {
//!     //             println!("Selected text: {}", text);
//!     //         }
//!     //     }
//!     // }
//!
//!     tree
//! }
//! ```

use std::any::Any;
use std::ffi::CString;
use std::ptr;
use std::sync::Arc;

use crate::event::{TreeEvents, WxEvtHandler};
// Base for some events
use crate::geometry::{Point, Size};
use crate::id::Id;
use crate::widgets::imagelist::ImageList;
use crate::widgets::item_data::{HasItemData, get_item_data, remove_item_data, store_item_data};
use crate::window::{WindowHandle, WxWidget};
use wxdragon_sys as ffi;

// --- TreeCtrl Styles ---
widget_style_enum!(
    name: TreeCtrlStyle,
    doc: "Style flags for TreeCtrl widget.",
    variants: {
        Default: ffi::WXD_TR_DEFAULT_STYLE, "Default style. Combines `HasButtons` and `LinesAtRoot`.",
        HasButtons: ffi::WXD_TR_HAS_BUTTONS, "Use buttons to show expand/collapse state.",
        LinesAtRoot: ffi::WXD_TR_LINES_AT_ROOT, "Use lines to show hierarchy at the root level.",
        NoLines: ffi::WXD_TR_NO_LINES, "Don't show any lines.",
        Single: ffi::WXD_TR_SINGLE, "Only allow a single item to be selected.",
        HideRoot: ffi::WXD_TR_HIDE_ROOT, "Hide the root item, making its children appear as top-level items.",
        EditLabels: ffi::WXD_TR_EDIT_LABELS, "Allow editing of item labels."
        // Add other TR_ styles as needed, e.g., TR_FULL_ROW_HIGHLIGHT, TR_MULTIPLE, etc.
        // TR_NO_BUTTONS = ffi::WXD_TR_NO_BUTTONS, (if available)
        // TR_ROW_LINES = ffi::WXD_TR_ROW_LINES, (if available)
        // TR_TWIST_BUTTONS = ffi::WXD_TR_TWIST_BUTTONS, (if available)
    },
    default_variant: Default
);

// --- TreeItemIcon Enum ---
/// Specifies which icon of a tree item is being referred to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)] // Matches wxd_TreeItemIconType_t which is an enum, typically int/u32
pub enum TreeItemIcon {
    Normal = ffi::wxd_TreeItemIconType_t_WXD_TreeItemIcon_Normal,
    Selected = ffi::wxd_TreeItemIconType_t_WXD_TreeItemIcon_Selected,
    Expanded = ffi::wxd_TreeItemIconType_t_WXD_TreeItemIcon_Expanded,
    SelectedExpanded = ffi::wxd_TreeItemIconType_t_WXD_TreeItemIcon_SelectedExpanded,
}

impl From<TreeItemIcon> for ffi::wxd_TreeItemIconType_t {
    fn from(icon: TreeItemIcon) -> Self {
        icon as ffi::wxd_TreeItemIconType_t
    }
}

bitflags::bitflags! {
    /// Flags returned by TreeCtrl::hit_test() indicating what part of an item was hit.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct TreeHitTestFlags: u32 {
        const ABOVE = 0x0001;
        const BELOW = 0x0002;
        const NOWHERE = 0x0004;
        const ON_ITEM_BUTTON = 0x0008;
        const ON_ITEM_ICON = 0x0010;
        const ON_ITEM_INDENT = 0x0020;
        const ON_ITEM_LABEL = 0x0040;
        const ON_ITEM_RIGHT = 0x0080;
        const ON_ITEM_STATE_ICON = 0x0100;
        const TO_LEFT = 0x0200;
        const TO_RIGHT = 0x0400;
        const ON_ITEM_UPPER_PART = 0x0800;
        const ON_ITEM_LOWER_PART = 0x1000;
        const ON_ITEM = Self::ON_ITEM_ICON.bits() | Self::ON_ITEM_LABEL.bits();
    }
}

// Represents the opaque wxTreeItemId used by wxWidgets.
// This struct owns the pointer returned by the C++ FFI functions
// and is responsible for freeing it via wxd_TreeItemId_Free.
#[derive(Debug)]
pub struct TreeItemId {
    ptr: *mut ffi::wxd_TreeItemId_t,
}

impl TreeItemId {
    // Creates a new TreeItemId from a raw pointer.
    // Assumes ownership of the pointer.
    pub(crate) unsafe fn from_ptr(ptr: *mut ffi::wxd_TreeItemId_t) -> Option<Self> {
        if ptr.is_null() {
            None
        } else {
            // Add validation to ensure the C++ side returned a valid pointer
            let ptr_value = ptr as usize;

            // Basic sanity check on the pointer before accepting it
            if ptr_value.is_multiple_of(std::mem::align_of::<*mut std::ffi::c_void>())  // Properly aligned
                && ptr_value > 0x1000  // Not in null/low memory range
                && ptr_value < (usize::MAX / 2)
            // Not in kernel space
            {
                // Additional check: try to verify the TreeItemId is valid
                if unsafe { ffi::wxd_TreeItemId_IsOk(ptr) } {
                    Some(TreeItemId { ptr })
                } else {
                    log::warn!("Warning: C++ returned invalid TreeItemId pointer {ptr:p}, rejecting");
                    // Free the invalid pointer since we were supposed to take ownership
                    unsafe { ffi::wxd_TreeItemId_Free(ptr) };
                    None
                }
            } else {
                log::warn!("Warning: C++ returned corrupted TreeItemId pointer {ptr:p}, rejecting");
                None
            }
        }
    }

    // Checks if the underlying wxTreeItemId is valid.
    pub fn is_ok(&self) -> bool {
        unsafe { ffi::wxd_TreeItemId_IsOk(self.ptr) }
    }

    // Returns the raw pointer - use with caution.
    pub(crate) fn as_ptr(&self) -> *mut ffi::wxd_TreeItemId_t {
        self.ptr
    }
}

impl Clone for TreeItemId {
    fn clone(&self) -> Self {
        let clone_ptr = unsafe { ffi::wxd_TreeItemId_Clone(self.ptr) };
        TreeItemId { ptr: clone_ptr }
    }
}

// Implement conversion to u64 for TreeItemId
impl From<&TreeItemId> for u64 {
    fn from(tree_item: &TreeItemId) -> Self {
        // We use the address of the TreeItemId itself as our value
        tree_item as *const _ as usize as u64
    }
}

impl Drop for TreeItemId {
    fn drop(&mut self) {
        // Only free if the pointer is not null.
        if !self.ptr.is_null() {
            unsafe {
                // In release mode, we're seeing crashes when calling C++ functions on TreeItemId pointers.
                // Let's be more defensive and add bounds checking.

                // Check if the pointer looks reasonable (not obviously corrupted)
                let ptr_value = self.ptr as usize;

                // Basic sanity check: pointer should be aligned and in a reasonable memory range
                // On macOS ARM64, user space addresses are typically in a specific range
                if ptr_value.is_multiple_of(std::mem::align_of::<*mut std::ffi::c_void>())  // Properly aligned
                    && ptr_value > 0x1000  // Not in null/low memory range
                    && ptr_value < (usize::MAX / 2)
                // Not in kernel space
                {
                    // Additional validation: check if the TreeItemId is valid before freeing
                    if ffi::wxd_TreeItemId_IsOk(self.ptr) {
                        // Tell the C++ side to free the WXD_TreeItemId_t struct.
                        ffi::wxd_TreeItemId_Free(self.ptr);
                    } else {
                        // TreeItemId is not valid, but still try to free the memory
                        // This might be a TreeItemId that was already invalidated
                        ffi::wxd_TreeItemId_Free(self.ptr);
                    }
                } else {
                    // Pointer looks corrupted, don't try to free it to avoid crashes
                    log::warn!(
                        "Warning: Dropping TreeItemId with corrupted pointer {:p}, not freeing to avoid crash",
                        self.ptr
                    );
                }
            }
            self.ptr = ptr::null_mut();
        }
    }
}

/// TreeIterationCookie is used to keep track of the state while iterating through children
pub struct TreeIterationCookie {
    cookie_ptr: *mut std::ffi::c_void,
}

impl TreeIterationCookie {
    /// Creates a new cookie
    fn new(cookie_ptr: *mut std::ffi::c_void) -> Self {
        Self { cookie_ptr }
    }

    /// Gets the raw pointer to the cookie
    fn as_ptr_mut(&mut self) -> *mut *mut std::ffi::c_void {
        &mut self.cookie_ptr as *mut *mut std::ffi::c_void
    }
}

impl Drop for TreeIterationCookie {
    fn drop(&mut self) {
        // NOTE: The cookie is automatically freed by the C++ side when iteration
        // completes (GetNextChild returns null), so we don't need to free it here.
        // Attempting to free it manually was causing memory safety issues because
        // the cookie is allocated with C++ 'new' but we were trying to free it
        // with Rust's Box allocator.

        // Just set to null for safety, but don't free
        self.cookie_ptr = ptr::null_mut();
    }
}

/// Represents the wxTreeCtrl widget.
///
/// TreeCtrl uses `WindowHandle` internally for safe memory management.
/// When the underlying window is destroyed (by calling `destroy()` or when
/// its parent is destroyed), the handle becomes invalid and all operations
/// become safe no-ops.
#[derive(Clone, Copy)]
pub struct TreeCtrl {
    handle: WindowHandle,
}

/// TreeCtrl implementation with tree traversal capabilities.
/// The following FFI functions are available for tree traversal:
/// - `wxd_TreeCtrl_GetRootItem`: Get the root item
/// - `wxd_TreeCtrl_GetFirstChild`: Get the first child of an item
/// - `wxd_TreeCtrl_GetNextChild`: Get the next child of an item using the same cookie
/// - `wxd_TreeCtrl_GetNextSibling`: Get the next sibling of an item
/// - `wxd_TreeCtrl_GetChildrenCount`: Get the number of children of an item
impl TreeCtrl {
    /// Creates a new TreeCtrl builder.
    pub fn builder(parent: &dyn WxWidget) -> TreeCtrlBuilder<'_> {
        TreeCtrlBuilder::new(parent)
    }

    /// Internal implementation used by the builder.
    fn new_impl(parent_ptr: *mut ffi::wxd_Window_t, id: Id, pos: Point, size: Size, style: i64) -> Self {
        assert!(!parent_ptr.is_null(), "TreeCtrl parent cannot be null");

        let ctrl_ptr = unsafe { ffi::wxd_TreeCtrl_Create(parent_ptr, id, pos.into(), size.into(), style as ffi::wxd_Style_t) };

        if ctrl_ptr.is_null() {
            panic!("Failed to create wxTreeCtrl");
        }

        let tree_ctrl = TreeCtrl {
            handle: WindowHandle::new(ctrl_ptr as *mut ffi::wxd_Window_t),
        };

        // Set up cleanup for custom data
        tree_ctrl.setup_cleanup();

        tree_ctrl
    }

    /// Helper to get raw TreeCtrl pointer, returns null if widget has been destroyed
    #[inline]
    fn treectrl_ptr(&self) -> *mut ffi::wxd_TreeCtrl_t {
        self.handle
            .get_ptr()
            .map(|p| p as *mut ffi::wxd_TreeCtrl_t)
            .unwrap_or(std::ptr::null_mut())
    }

    /// Adds the root item to the tree control.
    ///
    /// # Arguments
    /// * `text` - The text label for the root item.
    /// * `image` - Optional index of the image for the item (normal state).
    /// * `selected_image` - Optional index of the image for the item when selected.
    ///
    /// Returns the new item ID, or None if creation failed.
    pub fn add_root(&self, text: &str, image: Option<i32>, selected_image: Option<i32>) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let c_text = CString::new(text).unwrap_or_default();
        let img = image.unwrap_or(-1);
        let sel_img = selected_image.unwrap_or(-1);
        let item_ptr = unsafe { ffi::wxd_TreeCtrl_AddRoot(ptr, c_text.as_ptr(), img, sel_img, ptr::null_mut()) };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Adds the root item to the tree control with associated data.
    ///
    /// # Arguments
    /// * `text` - The text label for the root item.
    /// * `data` - Custom data to associate with the item.
    /// * `image` - Optional index of the image for the item (normal state).
    /// * `selected_image` - Optional index of the image for the item when selected.
    ///
    /// Returns the new item ID, or None if creation failed.
    pub fn add_root_with_data<T: Any + Send + Sync + 'static>(
        &self,
        text: &str,
        data: T,
        image: Option<i32>,
        selected_image: Option<i32>,
    ) -> Option<TreeItemId> {
        let root_item = self.add_root(text, image, selected_image)?;
        self.set_custom_data_direct(&root_item, data);
        Some(root_item)
    }

    /// Appends an item to the given parent item.
    ///
    /// # Arguments
    /// * `parent` - The parent item.
    /// * `text` - The text label for the new item.
    /// * `image` - Optional index of the image for the item (normal state).
    /// * `selected_image` - Optional index of the image for the item when selected.
    ///
    /// Returns the new item ID, or None if creation failed.
    pub fn append_item(
        &self,
        parent: &TreeItemId,
        text: &str,
        image: Option<i32>,
        selected_image: Option<i32>,
    ) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let t = CString::new(text).unwrap_or_default();
        let img = image.unwrap_or(-1);
        let sel_img = selected_image.unwrap_or(-1);
        let item_ptr = unsafe { ffi::wxd_TreeCtrl_AppendItem(ptr, parent.as_ptr(), t.as_ptr(), img, sel_img, ptr::null_mut()) };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Appends an item to the given parent item with associated data.
    ///
    /// # Arguments
    /// * `parent` - The parent item.
    /// * `text` - The text label for the new item.
    /// * `data` - Custom data to associate with the item.
    /// * `image` - Optional index of the image for the item (normal state).
    /// * `selected_image` - Optional index of the image for the item when selected.
    ///
    /// Returns the new item ID, or None if creation failed.
    pub fn append_item_with_data<T: Any + Send + Sync + 'static>(
        &self,
        parent: &TreeItemId,
        text: &str,
        data: T,
        image: Option<i32>,
        selected_image: Option<i32>,
    ) -> Option<TreeItemId> {
        let item = self.append_item(parent, text, image, selected_image)?;
        self.set_custom_data_direct(&item, data);
        Some(item)
    }

    /// Deletes the specified item and all its children.
    /// Note: The passed TreeItemId becomes invalid after this call.
    pub fn delete(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        // Clean up any attached data before deleting the item
        let _ = self.clear_custom_data(item);

        unsafe { ffi::wxd_TreeCtrl_Delete(ptr, item.as_ptr()) };
    }

    /// Gets the currently selected item.
    /// Returns None if no item is selected or on error.
    pub fn get_selection(&self) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let item_ptr = unsafe { ffi::wxd_TreeCtrl_GetSelection(ptr) };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Selects the given item.
    pub fn select_item(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe {
            ffi::wxd_TreeCtrl_SelectItem(ptr, item.as_ptr());
        }
    }

    /// Expands the given item to show its children.
    pub fn expand(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_Expand(ptr, item.as_ptr()) };
    }

    /// Sets up the TreeCtrl to clean up all custom data when it's destroyed.
    /// This is automatically called during construction.
    fn setup_cleanup(&self) {
        use crate::event::EventType;

        // Create a clone for the closure
        let tree_ctrl_clone = *self;

        // Bind to the DESTROY event for proper cleanup when the window is destroyed
        self.bind_internal(EventType::DESTROY, move |_event| {
            // Clean up all custom data when the control is destroyed
            tree_ctrl_clone.cleanup_all_custom_data();
        });
    }

    /// Manually clean up all custom data associated with this TreeCtrl.
    /// This can be called explicitly when needed, but is automatically
    /// called when the TreeCtrl is destroyed.
    pub fn cleanup_custom_data(&self) {
        self.cleanup_all_custom_data();
    }

    /// Gets the root item of the tree
    pub fn get_root_item(&self) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let item_ptr = unsafe { ffi::wxd_TreeCtrl_GetRootItem(ptr) };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Gets the first child of the specified item.
    /// Returns None if the item has no children.
    ///
    /// This also returns a cookie that must be used for subsequent calls to get_next_child.
    pub fn get_first_child(&self, item: &TreeItemId) -> Option<(TreeItemId, TreeIterationCookie)> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let mut cookie_ptr = ptr::null_mut();
        let child_ptr =
            unsafe { ffi::wxd_TreeCtrl_GetFirstChild(ptr, item.as_ptr(), &mut cookie_ptr as *mut *mut std::ffi::c_void) };

        let child = unsafe { TreeItemId::from_ptr(child_ptr) }?;
        let cookie = TreeIterationCookie::new(cookie_ptr);

        Some((child, cookie))
    }

    /// Gets the next child of an item using a cookie from a previous call to get_first_child
    /// or get_next_child.
    ///
    /// Returns None when there are no more children.
    pub fn get_next_child(&self, item: &TreeItemId, cookie: &mut TreeIterationCookie) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let child_ptr = unsafe { ffi::wxd_TreeCtrl_GetNextChild(ptr, item.as_ptr(), cookie.as_ptr_mut()) };

        unsafe { TreeItemId::from_ptr(child_ptr) }
    }

    /// Gets the next sibling of the specified item.
    /// Returns None if the item has no next sibling.
    pub fn get_next_sibling(&self, item: &TreeItemId) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let sibling_ptr = unsafe { ffi::wxd_TreeCtrl_GetNextSibling(ptr, item.as_ptr()) };

        unsafe { TreeItemId::from_ptr(sibling_ptr) }
    }

    /// Gets the number of children of the specified item.
    ///
    /// # Parameters
    ///
    /// * `item` - The item to check
    /// * `recursively` - If true, count all descendants, not just immediate children
    ///
    /// # Returns
    ///
    /// The number of children (or descendants if recursively is true)
    pub fn get_children_count(&self, item: &TreeItemId, recursively: bool) -> usize {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return 0;
        }
        unsafe { ffi::wxd_TreeCtrl_GetChildrenCount(ptr, item.as_ptr(), recursively) as usize }
    }

    // --- ImageList and Item Image Methods ---

    /// Sets the image list for the tree control.
    /// The tree control takes ownership of the image list.
    pub fn set_image_list(&self, image_list: ImageList) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe {
            ffi::wxd_TreeCtrl_SetImageList(ptr, image_list.as_ptr());
        }
        // wxTreeCtrl takes ownership of the ImageList
        std::mem::forget(image_list);
    }

    /// Gets the image list associated with the tree control.
    /// The tree control owns the image list, so the caller should not delete it.
    pub fn get_image_list(&self) -> Option<ImageList> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let img_ptr = unsafe { ffi::wxd_TreeCtrl_GetImageList(ptr) };
        if img_ptr.is_null() {
            None
        } else {
            Some(unsafe { ImageList::from_ptr_unowned(img_ptr) })
        }
    }

    /// Sets the image for the given item.
    pub fn set_item_image(&self, item: &TreeItemId, image_index: i32, icon_type: TreeItemIcon) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_SetItemImage(ptr, item.as_ptr(), image_index, icon_type.into()) };
    }

    /// Gets the image for the given item.
    /// Returns -1 if no image is associated with the item for the given type.
    pub fn get_item_image(&self, item: &TreeItemId, icon_type: TreeItemIcon) -> i32 {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return -1;
        }
        unsafe { ffi::wxd_TreeCtrl_GetItemImage(ptr, item.as_ptr(), icon_type.into()) }
    }

    /// Gets the text label of the given item.
    /// Returns None if the item is invalid or the tree control has been destroyed.
    pub fn get_item_text(&self, item: &TreeItemId) -> Option<String> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }

        // First call to get the required buffer size
        let required_size = unsafe { ffi::wxd_TreeCtrl_GetItemText(ptr, item.as_ptr(), std::ptr::null_mut(), 0) };

        if required_size < 0 {
            return None;
        }

        // Allocate buffer with space for null terminator
        let buffer_size = (required_size as usize) + 1;
        let mut buffer: Vec<u8> = vec![0; buffer_size];

        // Second call to get the actual text
        let result = unsafe { ffi::wxd_TreeCtrl_GetItemText(ptr, item.as_ptr(), buffer.as_mut_ptr() as *mut i8, buffer_size) };

        if result < 0 {
            return None;
        }

        // Convert to String, removing trailing null if present
        let text_len = result as usize;
        buffer.truncate(text_len);
        String::from_utf8(buffer).ok()
    }

    /// Scrolls and/or expands items to ensure that the given item is visible.
    pub fn ensure_visible(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_EnsureVisible(ptr, item.as_ptr()) }
    }

    /// Sets the currently focused item (the item that has keyboard focus).
    pub fn set_focused_item(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_SetFocusedItem(ptr, item.as_ptr()) }
    }

    /// Expands all items in the tree.
    pub fn expand_all(&self) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_ExpandAll(ptr) }
    }

    /// Sets the text label of the given item.
    pub fn set_item_text(&self, item: &TreeItemId, text: &str) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        let c_text = CString::new(text).unwrap_or_default();
        unsafe { ffi::wxd_TreeCtrl_SetItemText(ptr, item.as_ptr(), c_text.as_ptr()) }
    }

    /// Gets the currently focused item.
    pub fn get_focused_item(&self) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let item_ptr = unsafe { ffi::wxd_TreeCtrl_GetFocusedItem(ptr) };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Collapses the given item.
    pub fn collapse(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_Collapse(ptr, item.as_ptr()) }
    }

    /// Collapses all items in the tree.
    pub fn collapse_all(&self) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_CollapseAll(ptr) }
    }

    /// Collapses the given item and all its children.
    pub fn collapse_all_children(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_CollapseAllChildren(ptr, item.as_ptr()) }
    }

    /// Collapses the item and removes all children.
    pub fn collapse_and_reset(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_CollapseAndReset(ptr, item.as_ptr()) }
    }

    /// Toggles the expand/collapse state of the given item.
    pub fn toggle(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_Toggle(ptr, item.as_ptr()) }
    }

    /// Checks if the given item is expanded.
    pub fn is_expanded(&self, item: &TreeItemId) -> bool {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return false;
        }
        unsafe { ffi::wxd_TreeCtrl_IsExpanded(ptr, item.as_ptr()) }
    }

    /// Checks if the given item is selected.
    pub fn is_selected(&self, item: &TreeItemId) -> bool {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return false;
        }
        unsafe { ffi::wxd_TreeCtrl_IsSelected(ptr, item.as_ptr()) }
    }

    /// Unselects all items.
    pub fn unselect_all(&self) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_UnselectAll(ptr) }
    }

    /// Unselects the given item.
    pub fn unselect_item(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_UnselectItem(ptr, item.as_ptr()) }
    }

    /// Selects all items (only works with TR_MULTIPLE style).
    pub fn select_all(&self) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_SelectAll(ptr) }
    }

    /// Gets all selected items (for multi-selection trees).
    pub fn get_selections(&self) -> Vec<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return Vec::new();
        }
        // First get the count
        let count = unsafe { ffi::wxd_TreeCtrl_GetSelections(ptr, std::ptr::null_mut(), 0) };
        if count == 0 {
            return Vec::new();
        }
        // Allocate and get the items
        let mut items: Vec<*mut ffi::wxd_TreeItemId_t> = vec![std::ptr::null_mut(); count];
        unsafe { ffi::wxd_TreeCtrl_GetSelections(ptr, items.as_mut_ptr(), count) };
        items.into_iter().filter_map(|p| unsafe { TreeItemId::from_ptr(p) }).collect()
    }

    /// Gets the parent of the given item.
    pub fn get_item_parent(&self, item: &TreeItemId) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let item_ptr = unsafe { ffi::wxd_TreeCtrl_GetItemParent(ptr, item.as_ptr()) };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Gets the previous sibling of the given item.
    pub fn get_prev_sibling(&self, item: &TreeItemId) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let item_ptr = unsafe { ffi::wxd_TreeCtrl_GetPrevSibling(ptr, item.as_ptr()) };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Gets the last child of the given item.
    pub fn get_last_child(&self, item: &TreeItemId) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let item_ptr = unsafe { ffi::wxd_TreeCtrl_GetLastChild(ptr, item.as_ptr()) };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Checks if the given item is visible.
    pub fn is_visible(&self, item: &TreeItemId) -> bool {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return false;
        }
        unsafe { ffi::wxd_TreeCtrl_IsVisible(ptr, item.as_ptr()) }
    }

    /// Checks if the given item has children.
    pub fn item_has_children(&self, item: &TreeItemId) -> bool {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return false;
        }
        unsafe { ffi::wxd_TreeCtrl_ItemHasChildren(ptr, item.as_ptr()) }
    }

    /// Checks if the given item is bold.
    pub fn is_bold(&self, item: &TreeItemId) -> bool {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return false;
        }
        unsafe { ffi::wxd_TreeCtrl_IsBold(ptr, item.as_ptr()) }
    }

    /// Sets the item to bold or normal.
    pub fn set_item_bold(&self, item: &TreeItemId, bold: bool) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_SetItemBold(ptr, item.as_ptr(), bold) }
    }

    /// Sets the text colour of the given item.
    pub fn set_item_text_colour(&self, item: &TreeItemId, colour: crate::color::Colour) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_SetItemTextColour(ptr, item.as_ptr(), colour.into()) }
    }

    /// Gets the text colour of the given item.
    pub fn get_item_text_colour(&self, item: &TreeItemId) -> crate::color::Colour {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return crate::color::Colour::new(0, 0, 0, 255);
        }
        let c = unsafe { ffi::wxd_TreeCtrl_GetItemTextColour(ptr, item.as_ptr()) };
        crate::color::Colour::new(c.r, c.g, c.b, c.a)
    }

    /// Sets the background colour of the given item.
    pub fn set_item_background_colour(&self, item: &TreeItemId, colour: crate::color::Colour) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_SetItemBackgroundColour(ptr, item.as_ptr(), colour.into()) }
    }

    /// Gets the background colour of the given item.
    pub fn get_item_background_colour(&self, item: &TreeItemId) -> crate::color::Colour {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return crate::color::Colour::new(255, 255, 255, 255);
        }
        let c = unsafe { ffi::wxd_TreeCtrl_GetItemBackgroundColour(ptr, item.as_ptr()) };
        crate::color::Colour::new(c.r, c.g, c.b, c.a)
    }

    /// Inserts an item after the given previous item.
    pub fn insert_item(
        &self,
        parent: &TreeItemId,
        previous: &TreeItemId,
        text: &str,
        image: Option<i32>,
        selected_image: Option<i32>,
    ) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let c_text = CString::new(text).unwrap_or_default();
        let img = image.unwrap_or(-1);
        let sel_img = selected_image.unwrap_or(-1);
        let item_ptr = unsafe {
            ffi::wxd_TreeCtrl_InsertItem(
                ptr,
                parent.as_ptr(),
                previous.as_ptr(),
                c_text.as_ptr(),
                img,
                sel_img,
                ptr::null_mut(),
            )
        };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Inserts an item at the given position (0-based index).
    pub fn insert_item_before(
        &self,
        parent: &TreeItemId,
        pos: usize,
        text: &str,
        image: Option<i32>,
        selected_image: Option<i32>,
    ) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let c_text = CString::new(text).unwrap_or_default();
        let img = image.unwrap_or(-1);
        let sel_img = selected_image.unwrap_or(-1);
        let item_ptr = unsafe {
            ffi::wxd_TreeCtrl_InsertItemBefore(ptr, parent.as_ptr(), pos, c_text.as_ptr(), img, sel_img, ptr::null_mut())
        };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Prepends an item as the first child.
    pub fn prepend_item(
        &self,
        parent: &TreeItemId,
        text: &str,
        image: Option<i32>,
        selected_image: Option<i32>,
    ) -> Option<TreeItemId> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let c_text = CString::new(text).unwrap_or_default();
        let img = image.unwrap_or(-1);
        let sel_img = selected_image.unwrap_or(-1);
        let item_ptr =
            unsafe { ffi::wxd_TreeCtrl_PrependItem(ptr, parent.as_ptr(), c_text.as_ptr(), img, sel_img, ptr::null_mut()) };
        unsafe { TreeItemId::from_ptr(item_ptr) }
    }

    /// Deletes all items in the tree.
    pub fn delete_all_items(&self) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_DeleteAllItems(ptr) }
    }

    /// Deletes all children of the given item.
    pub fn delete_children(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_DeleteChildren(ptr, item.as_ptr()) }
    }

    /// Gets the total number of items in the tree.
    pub fn get_count(&self) -> usize {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return 0;
        }
        unsafe { ffi::wxd_TreeCtrl_GetCount(ptr) }
    }

    /// Scrolls to the given item (without expanding).
    pub fn scroll_to(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_ScrollTo(ptr, item.as_ptr()) }
    }

    /// Sorts the children of the given item alphabetically.
    pub fn sort_children(&self, item: &TreeItemId) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_SortChildren(ptr, item.as_ptr()) }
    }

    /// Sets whether the item has a button (+/-) to expand/collapse.
    pub fn set_item_has_children(&self, item: &TreeItemId, has: bool) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return;
        }
        unsafe { ffi::wxd_TreeCtrl_SetItemHasChildren(ptr, item.as_ptr(), has) }
    }

    /// Hit test - returns the item at the given point along with flags.
    pub fn hit_test(&self, point: Point) -> (Option<TreeItemId>, TreeHitTestFlags) {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return (None, TreeHitTestFlags::NOWHERE);
        }
        let mut flags: i32 = 0;
        let item_ptr = unsafe { ffi::wxd_TreeCtrl_HitTest(ptr, point.into(), &mut flags) };
        let item = unsafe { TreeItemId::from_ptr(item_ptr) };
        (item, TreeHitTestFlags::from_bits_truncate(flags as u32))
    }

    /// Gets the bounding rectangle of an item.
    pub fn get_bounding_rect(&self, item: &TreeItemId, text_only: bool) -> Option<crate::geometry::Rect> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }
        let mut rect = ffi::wxd_Rect {
            x: 0,
            y: 0,
            width: 0,
            height: 0,
        };
        let success = unsafe { ffi::wxd_TreeCtrl_GetBoundingRect(ptr, item.as_ptr(), &mut rect, text_only) };
        if success {
            Some(crate::geometry::Rect::new(rect.x, rect.y, rect.width, rect.height))
        } else {
            None
        }
    }
}

// Implement HasItemData trait for TreeCtrl
impl HasItemData for TreeCtrl {
    fn set_custom_data<T: Any + Send + Sync + 'static>(&self, item_id: impl Into<u64>, data: T) -> u64 {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return 0;
        }

        // Convert from the generic item_id
        let item_id = item_id.into();

        // For TreeCtrl, we need the actual TreeItemId, not just a u64 representation
        // Get the concrete TreeItemId if that's what was passed
        if let Some(tree_item) = self.get_concrete_tree_item_id(item_id) {
            // First check if there's already data associated with this item
            let existing_data_id = unsafe { ffi::wxd_TreeCtrl_GetItemData(ptr, tree_item.as_ptr()) as u64 };

            // If we have existing data, remove it from the registry
            if existing_data_id != 0 {
                let _ = remove_item_data(existing_data_id);
            }

            // Store the new data in the registry
            let data_id = store_item_data(data);

            // Store the data_id in wxWidgets via the C++ FFI
            unsafe {
                ffi::wxd_TreeCtrl_SetItemData(ptr, tree_item.as_ptr(), data_id as i64);
            }

            return data_id;
        }

        // If we couldn't get a valid TreeItemId, return 0 (failure)
        0
    }

    fn get_custom_data(&self, item_id: impl Into<u64>) -> Option<Arc<dyn Any + Send + Sync>> {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return None;
        }

        // Convert from the generic item_id
        let item_id = item_id.into();

        // Get the concrete TreeItemId if that's what was passed
        let tree_item = self.get_concrete_tree_item_id(item_id)?;

        // Get the data ID from wxWidgets
        let data_id = unsafe { ffi::wxd_TreeCtrl_GetItemData(ptr, tree_item.as_ptr()) as u64 };

        if data_id == 0 {
            return None;
        }

        // Look up the data in the registry
        get_item_data(data_id)
    }

    fn has_custom_data(&self, item_id: impl Into<u64>) -> bool {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return false;
        }

        // Convert from the generic item_id
        let item_id = item_id.into();

        // Get the concrete TreeItemId if that's what was passed
        if let Some(tree_item) = self.get_concrete_tree_item_id(item_id) {
            // Check if this item has data via wxWidgets
            let data_id = unsafe { ffi::wxd_TreeCtrl_GetItemData(ptr, tree_item.as_ptr()) as u64 };

            return data_id != 0 && get_item_data(data_id).is_some();
        }

        false
    }

    fn clear_custom_data(&self, item_id: impl Into<u64>) -> bool {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return false;
        }

        // Convert from the generic item_id
        let item_id = item_id.into();

        // Get the concrete TreeItemId if that's what was passed
        if let Some(tree_item) = self.get_concrete_tree_item_id(item_id) {
            // Get the data ID from wxWidgets
            let data_id = unsafe { ffi::wxd_TreeCtrl_GetItemData(ptr, tree_item.as_ptr()) as u64 };

            if data_id != 0 {
                // Remove the data from the registry
                let _ = remove_item_data(data_id);

                // Clear the association in wxWidgets
                unsafe {
                    ffi::wxd_TreeCtrl_SetItemData(ptr, tree_item.as_ptr(), 0);
                }

                return true;
            }
        }

        false
    }

    fn cleanup_all_custom_data(&self) {
        // Get the root item
        let root = match self.get_root_item() {
            Some(root) => root,
            None => {
                return;
            }
        };

        // Recursively clean up the root and all its children
        self.clean_item_and_children(&root);
    }
}

// Helper methods for TreeCtrl
impl TreeCtrl {
    // This is a special method to handle the case of getting a TreeItemId from something
    // that implements Into<u64>. It handles different ways the item might be passed.
    fn get_concrete_tree_item_id(&self, _id: u64) -> Option<TreeItemId> {
        // Handle the case where we're given a reference to an existing TreeItemId
        // The id value will be the memory address of the TreeItemId reference
        if _id > u32::MAX as u64 {
            // Try to interpret it as a reference to an existing TreeItemId
            let ptr = _id as usize as *const TreeItemId;

            // Add extensive safety checks
            if !ptr.is_null() {
                // Check if the pointer looks reasonable (aligned and in valid memory range)
                let ptr_value = ptr as usize;
                if ptr_value.is_multiple_of(std::mem::align_of::<TreeItemId>())  // Properly aligned
                    && ptr_value > 0x1000  // Not in null/low memory range
                    && ptr_value < (usize::MAX / 2)
                // Not in kernel space (macOS ARM64)
                {
                    unsafe {
                        // Try to dereference the pointer carefully
                        let possible_tree_item = &*ptr;

                        // Validate that the TreeItemId's internal pointer looks reasonable
                        let internal_ptr = possible_tree_item.ptr as usize;
                        if !possible_tree_item.ptr.is_null()
                            && internal_ptr.is_multiple_of(std::mem::align_of::<*mut std::ffi::c_void>())
                            && internal_ptr > 0x1000
                            && internal_ptr < (usize::MAX / 2)
                        {
                            // Final validation: check if the TreeItemId is actually valid
                            if ffi::wxd_TreeItemId_IsOk(possible_tree_item.ptr) {
                                // Clone it to avoid lifetime issues
                                let clone_ptr = ffi::wxd_TreeItemId_Clone(possible_tree_item.ptr);
                                if !clone_ptr.is_null() {
                                    return Some(TreeItemId { ptr: clone_ptr });
                                }
                            }
                        }
                    }
                }
            }
        }

        // For smaller values, handle special cases
        match _id {
            // Special case for getting root item
            1 => self.get_root_item(),
            // Special case for getting selection
            2 => self.get_selection(),
            _ => None,
        }
    }

    /// Recursively clean up the item and all its children
    fn clean_item_and_children(&self, item: &TreeItemId) {
        // Check if this item has any children
        if self.get_children_count(item, false) == 0 {
            // No children, we're done with this branch
            return;
        }

        // Get the first child
        if let Some((first_child, mut cookie)) = self.get_first_child(item) {
            // Clean up the first child and its descendants
            self.clean_item_and_children(&first_child);

            // Process all remaining children
            while let Some(next_child) = self.get_next_child(item, &mut cookie) {
                self.clean_item_and_children(&next_child);
            }
        }
    }

    /// Direct method to set custom data on a TreeItemId without going through u64 conversion.
    /// This is safer than the trait method when you have a direct TreeItemId reference.
    pub fn set_custom_data_direct<T: Any + Send + Sync + 'static>(&self, item_id: &TreeItemId, data: T) -> u64 {
        let ptr = self.treectrl_ptr();
        if ptr.is_null() {
            return 0;
        }

        // First check if there's already data associated with this item
        let existing_data_id = unsafe { ffi::wxd_TreeCtrl_GetItemData(ptr, item_id.as_ptr()) as u64 };

        // If we have existing data, remove it from the registry
        if existing_data_id != 0 {
            let _ = remove_item_data(existing_data_id);
        }

        // Store the new data in the registry
        let data_id = store_item_data(data);

        // Store the data_id in wxWidgets via the C++ FFI
        unsafe {
            ffi::wxd_TreeCtrl_SetItemData(ptr, item_id.as_ptr(), data_id as i64);
        }

        data_id
    }
}

// Manual WxWidget implementation for TreeCtrl (using WindowHandle)
impl WxWidget for TreeCtrl {
    fn handle_ptr(&self) -> *mut ffi::wxd_Window_t {
        self.handle.get_ptr().unwrap_or(std::ptr::null_mut())
    }

    fn is_valid(&self) -> bool {
        self.handle.is_valid()
    }
}

// Implement WxEvtHandler for event binding
impl WxEvtHandler for TreeCtrl {
    unsafe fn get_event_handler_ptr(&self) -> *mut ffi::wxd_EvtHandler_t {
        self.handle.get_ptr().unwrap_or(std::ptr::null_mut()) as *mut ffi::wxd_EvtHandler_t
    }
}

// Implement common event traits that all Window-based widgets support
impl crate::event::WindowEvents for TreeCtrl {}

// Implement scrolling functionality for TreeCtrl
impl crate::scrollable::WxScrollable for TreeCtrl {}

// Use the widget_builder macro for TreeCtrl
widget_builder!(
    name: TreeCtrl,
    parent_type: &'a dyn WxWidget,
    style_type: TreeCtrlStyle,
    fields: {},
    build_impl: |slf| {
        TreeCtrl::new_impl(
            slf.parent.handle_ptr(),
            slf.id,
            slf.pos,
            slf.size,
            slf.style.bits()
        )
    }
);

// At the bottom of the file, add the TreeEvents trait implementation
impl TreeEvents for TreeCtrl {}

// XRC Support - enables TreeCtrl to be created from XRC-managed pointers
#[cfg(feature = "xrc")]
impl crate::xrc::XrcSupport for TreeCtrl {
    unsafe fn from_xrc_ptr(ptr: *mut ffi::wxd_Window_t) -> Self {
        TreeCtrl {
            handle: WindowHandle::new(ptr),
        }
    }
}

// Enable widget casting for TreeCtrl
impl crate::window::FromWindowWithClassName for TreeCtrl {
    fn class_name() -> &'static str {
        "wxTreeCtrl"
    }

    unsafe fn from_ptr(ptr: *mut ffi::wxd_Window_t) -> Self {
        TreeCtrl {
            handle: WindowHandle::new(ptr),
        }
    }
}