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
//! wxListCtrl wrapper
use crate::event::{Event, EventType, WxEvtHandler};
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};
// Window is used by macros and internal compatibility
#[allow(unused_imports)]
use crate::window::Window;
use std::any::Any;
use std::ffi::{CStr, CString};
use std::os::raw::{c_int, c_longlong};
use std::sync::Arc;
use wxdragon_sys as ffi;
// --- ListCtrl Styles ---
widget_style_enum!(
name: ListCtrlStyle,
doc: "Style flags for ListCtrl widget.",
variants: {
Default: 0, "Default list control style.",
SingleSel: ffi::WXD_LC_SINGLE_SEL, "Single selection (default is multiple).",
SortAscending: ffi::WXD_LC_SORT_ASCENDING, "Sort in ascending order.",
SortDescending: ffi::WXD_LC_SORT_DESCENDING, "Sort in descending order.",
Virtual: ffi::WXD_LC_VIRTUAL, "The application provides items text on demand.",
EditLabels: ffi::WXD_LC_EDIT_LABELS, "Labels can be edited for in-place renaming.",
// View styles
Icon: ffi::WXD_LC_ICON, "Large icon view.",
SmallIcon: ffi::WXD_LC_SMALL_ICON, "Small icon view.",
List: ffi::WXD_LC_LIST, "List view showing items on a single line.",
Report: ffi::WXD_LC_REPORT, "Multicolumn report view (detail view).",
// Alignment styles
AlignTop: ffi::WXD_LC_ALIGN_TOP, "Align icons with the top (default).",
AlignLeft: ffi::WXD_LC_ALIGN_LEFT, "Align icons with the left.",
// Behavior styles
AutoArrange: ffi::WXD_LC_AUTOARRANGE, "Icons arrange themselves.",
HRules: ffi::WXD_LC_HRULES, "Horizontal rules in report mode.",
VRules: ffi::WXD_LC_VRULES, "Vertical rules in report mode.",
NoHeader: ffi::WXD_LC_NO_HEADER, "No header in report mode.",
NoSort: ffi::WXD_LC_NO_SORT_HEADER, "No sorting when clicking on headers."
},
default_variant: Default
);
// --- ListColumnFormat Enum (for LIST_FORMAT_... constants) ---
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(i32)]
#[derive(Default)]
pub enum ListColumnFormat {
/// Align column content to the left
#[default]
Left = ffi::WXD_LIST_FORMAT_LEFT as i32,
/// Align column content to the right
Right = ffi::WXD_LIST_FORMAT_RIGHT as i32,
/// Align column content to the center
Centre = ffi::WXD_LIST_FORMAT_CENTRE as i32,
}
impl ListColumnFormat {
/// Returns the raw integer value of the format
pub fn as_i32(self) -> i32 {
self as i32
}
}
// --- ListItemState (for LIST_STATE_... constants) ---
widget_style_enum!(
name: ListItemState,
doc: "Item state flags for ListCtrl items.",
variants: {
None: 0, "No state (used for clearing states).",
Selected: ffi::WXD_LIST_STATE_SELECTED, "Item is selected.",
Focused: ffi::WXD_LIST_STATE_FOCUSED, "Item has focus.",
Disabled: ffi::WXD_LIST_STATE_DISABLED, "Item is disabled.",
DropHilited: ffi::WXD_LIST_STATE_DROPHILITED, "Item is highlighted as a drop target."
},
default_variant: None
);
// --- ListNextItemFlag Enum (for LIST_NEXT_... constants) ---
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(i32)]
#[derive(Default)]
pub enum ListNextItemFlag {
/// All items, no geometric restriction
#[default]
All = ffi::WXD_LIST_NEXT_ALL as i32,
/// Item above current one
Above = ffi::WXD_LIST_NEXT_ABOVE as i32,
/// Item below current one
Below = ffi::WXD_LIST_NEXT_BELOW as i32,
/// Item to the left of current one
Left = ffi::WXD_LIST_NEXT_LEFT as i32,
/// Item to the right of current one
Right = ffi::WXD_LIST_NEXT_RIGHT as i32,
}
impl ListNextItemFlag {
/// Returns the raw integer value of the flag
pub fn as_i32(self) -> i32 {
self as i32
}
}
/// Events emitted by ListCtrl
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListCtrlEvent {
/// Emitted when an item is selected
ItemSelected,
/// Emitted when an item is deselected
ItemDeselected,
/// Emitted when an item is activated (double-clicked or Enter)
ItemActivated,
/// Emitted when an item is focused
ItemFocused,
/// Emitted when a column header is clicked
ColumnClick,
/// Emitted when a column header is right-clicked
ColumnRightClick,
/// Emitted when a column begins to be dragged
ColumnBeginDrag,
/// Emitted when beginning in-place editing of an item's label
BeginLabelEdit,
/// Emitted when ending in-place editing of an item's label
EndLabelEdit,
/// Emitted when beginning to drag an item
BeginDrag,
/// Emitted when beginning to right drag an item
BeginRDrag,
/// Emitted when an item is deleted
DeleteItem,
/// Emitted when all items are deleted
DeleteAllItems,
/// Emitted when the key is pressed with focus on the list
KeyDown,
/// Emitted when an item is inserted
InsertItem,
/// Emitted when an item is right-clicked
ItemRightClick,
/// Emitted when an item is middle-clicked
ItemMiddleClick,
}
/// Event data for ListCtrl events
#[derive(Debug)]
pub struct ListCtrlEventData {
event: Event,
}
impl ListCtrlEventData {
/// Create a new ListCtrlEventData from a generic Event
pub fn new(event: Event) -> Self {
Self { event }
}
/// Get the item index affected by the event
pub fn get_item_index(&self) -> i32 {
if self.event.is_null() {
return -1;
}
unsafe { ffi::wxd_ListEvent_GetItemIndex(self.event.0) }
}
/// Get the column index affected by the event (for column-related events)
pub fn get_column(&self) -> Option<i32> {
if self.event.is_null() {
return None;
}
let col = unsafe { ffi::wxd_ListEvent_GetColumn(self.event.0) };
if col == -1 { None } else { Some(col) }
}
/// Get the item label (for label edit events)
pub fn get_label(&self) -> Option<String> {
if self.event.is_null() {
return None;
}
let len = unsafe { ffi::wxd_ListEvent_GetLabel(self.event.0, std::ptr::null_mut(), 0) };
if len == 0 {
return None;
}
let mut buf = vec![0; len as usize + 1];
unsafe { ffi::wxd_ListEvent_GetLabel(self.event.0, buf.as_mut_ptr(), buf.len()) };
Some(unsafe { CStr::from_ptr(buf.as_ptr()).to_string_lossy().to_string() })
}
/// Check if editing was cancelled (for end edit events)
pub fn is_edit_cancelled(&self) -> Option<bool> {
if self.event.is_null() {
return None;
}
// Boolean functions from C++ return int (0/1), explicitly convert to Rust bool
Some(unsafe { ffi::wxd_ListEvent_IsEditCancelled(self.event.0) })
}
/// Get the point where the event occurred (for click events)
pub fn get_position(&self) -> Option<Point> {
self.event.get_position()
}
/// Get the key code (for key events)
pub fn get_key_code(&self) -> Option<i32> {
self.event.get_key_code()
}
}
// --- ImageList Type Constants ---
/// Constants for image list types
pub mod image_list_type {
/// Normal sized images (typically for Icon view)
pub const NORMAL: i32 = 0;
/// Small sized images (typically for Report/List view)
pub const SMALL: i32 = 1;
/// State images (for checkboxes)
pub const STATE: i32 = 2;
}
/// A control for displaying and manipulating multiple items
///
/// ListCtrl 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.
///
/// The ListCtrl can display items in various formats including:
/// - List view (one column)
/// - Report view (multiple columns with headers)
/// - Icon view (large or small icons)
///
/// # Example
/// ```ignore
/// let list_ctrl = ListCtrl::builder(&frame)
/// .with_style(ListCtrlStyle::Report)
/// .build();
///
/// // ListCtrl is Copy - no clone needed for closures!
/// list_ctrl.on_item_selected(move |event| {
/// // Safe: if list_ctrl was destroyed, this is a no-op
/// let index = event.get_item_index();
/// let text = list_ctrl.get_item_text(index as i64, 0);
/// println!("Selected: {}", text);
/// });
///
/// // After parent destruction, list_ctrl operations are safe no-ops
/// frame.destroy();
/// assert!(!list_ctrl.is_valid());
/// ```
#[derive(Clone, Copy)]
pub struct ListCtrl {
/// Safe handle to the underlying wxListCtrl - automatically invalidated on destroy
handle: WindowHandle,
}
impl ListCtrl {
/// Creates a new ListCtrl builder.
pub fn builder(parent: &dyn WxWidget) -> ListCtrlBuilder<'_> {
ListCtrlBuilder::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(), "ListCtrl requires a parent");
let ptr = unsafe { ffi::wxd_ListCtrl_Create(parent_ptr, id, pos.into(), size.into(), style) };
if ptr.is_null() {
panic!("Failed to create ListCtrl: FFI returned null pointer.");
}
// Create a WindowHandle which automatically registers for destroy events
ListCtrl {
handle: WindowHandle::new(ptr as *mut ffi::wxd_Window_t),
}
}
/// Creates a new ListCtrl from a raw pointer.
/// This is intended for internal use by other widget wrappers.
#[allow(dead_code)]
pub(crate) fn from_ptr(ptr: *mut ffi::wxd_Window_t) -> Self {
Self {
handle: WindowHandle::new(ptr),
}
}
/// Helper to get raw list_ctrl pointer, returns null if widget has been destroyed
#[inline]
fn listctrl_ptr(&self) -> *mut ffi::wxd_ListCtrl_t {
self.handle
.get_ptr()
.map(|p| p as *mut ffi::wxd_ListCtrl_t)
.unwrap_or(std::ptr::null_mut())
}
/// Returns the underlying WindowHandle for this list control.
pub fn window_handle(&self) -> WindowHandle {
self.handle
}
/// Inserts a column at the specified position.
/// Returns -1 if the list control has been destroyed.
pub fn insert_column(&self, col: i64, heading: &str, format: ListColumnFormat, width: i32) -> i32 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return -1;
}
let c_heading = CString::new(heading).unwrap_or_default();
unsafe { ffi::wxd_ListCtrl_InsertColumn(ptr, col as c_longlong, c_heading.as_ptr(), format as c_int, width) }
}
/// Sets the width of the specified column.
/// No-op (returns false) if the list control has been destroyed.
pub fn set_column_width(&self, col: i64, width: i32) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
unsafe { ffi::wxd_ListCtrl_SetColumnWidth(ptr, col as c_longlong, width) }
}
/// Gets the width of the specified column.
/// Returns 0 if the list control has been destroyed.
pub fn get_column_width(&self, col: i64) -> i32 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return 0;
}
unsafe { ffi::wxd_ListCtrl_GetColumnWidth(ptr, col as c_longlong) }
}
/// Gets the number of columns in the list control.
/// Returns 0 if the list control has been destroyed.
pub fn get_column_count(&self) -> i32 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return 0;
}
unsafe { ffi::wxd_ListCtrl_GetColumnCount(ptr) }
}
/// Inserts a simple item (label only) at the specified index.
/// Returns -1 if the list control has been destroyed.
pub fn insert_item(&self, index: i64, label: &str, image_index: Option<i32>) -> i32 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return -1;
}
let c_label = CString::new(label).unwrap_or_default();
let img_idx = image_index.unwrap_or(-1); // Use -1 if no image is specified
unsafe { ffi::wxd_ListCtrl_InsertItemWithImage(ptr, index as c_longlong, c_label.as_ptr(), img_idx) }
}
/// Sets the text of an item (label in column 0).
/// No-op if the list control has been destroyed.
pub fn set_item_text(&self, index: i64, text: &str) {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return;
}
let c_text = CString::new(text).unwrap_or_default();
unsafe { ffi::wxd_ListCtrl_SetItemText(ptr, index as c_longlong, c_text.as_ptr()) }
}
/// Sets the text of an item in the specified column.
/// No-op if the list control has been destroyed.
///
/// # Arguments
/// * `index` - The index of the item.
/// * `col` - The column index (0-based).
/// * `text` - The text to set.
///
/// # Example
/// ```no_run
/// # use wxdragon::prelude::*;
/// # let parent = Frame::builder().build();
/// # let list_ctrl = ListCtrl::builder(&parent)
/// # .with_style(ListCtrlStyle::Report)
/// # .build();
/// list_ctrl.set_item_text_by_column(0, 1, "Column 1 text");
/// ```
pub fn set_item_text_by_column(&self, index: i64, col: i32, text: &str) {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return;
}
if col == 0 {
// Use the standard method for column 0
self.set_item_text(index, text);
return;
}
// Use SetItem to set column text
let c_text = CString::new(text).unwrap_or_default();
let mask = ffi::WXD_LIST_MASK_TEXT as i64;
let state = 0;
let state_mask = 0;
let image = -1;
let data = 0;
let item_fmt = 0;
unsafe {
ffi::wxd_ListCtrl_SetItem(
ptr,
index as c_longlong,
col as c_int,
c_text.as_ptr(),
image,
item_fmt,
state,
state_mask,
data,
mask,
);
}
}
/// Gets the text of an item in the specified column.
/// Returns empty string if the list control has been destroyed.
pub fn get_item_text(&self, index: i64, col: i32) -> String {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return String::new();
}
unsafe {
let needed_len = ffi::wxd_ListCtrl_GetItemText(ptr, index as c_longlong, col, std::ptr::null_mut(), 0);
if needed_len <= 0 {
return String::new();
}
let mut buffer: Vec<u8> = Vec::with_capacity(needed_len as usize);
let actual_len = ffi::wxd_ListCtrl_GetItemText(
ptr,
index as c_longlong,
col,
buffer.as_mut_ptr() as *mut i8,
needed_len as i32,
);
if actual_len <= 0 {
return String::new();
}
buffer.set_len(actual_len as usize);
String::from_utf8_lossy(&buffer).into_owned()
}
}
/// Gets the number of items in the list control.
/// Returns 0 if the list control has been destroyed.
pub fn get_item_count(&self) -> i32 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return 0;
}
unsafe { ffi::wxd_ListCtrl_GetItemCount(ptr) }
}
/// Sets the state of an item using the ListItemState enum.
/// No-op (returns false) if the list control has been destroyed.
///
/// # Arguments
/// * `item` - The index of the item.
/// * `state` - The state flags to set or clear.
/// * `state_mask` - The state flags to modify (only bits set in mask will be changed).
///
/// # Example
/// ```no_run
/// # use wxdragon::prelude::*;
/// # let parent = Frame::builder().build();
/// # let list_ctrl = ListCtrl::builder(&parent)
/// # .with_style(ListCtrlStyle::Report)
/// # .build();
/// // To select an item:
/// list_ctrl.set_item_state(0, ListItemState::Selected, ListItemState::Selected);
/// // To deselect an item:
/// list_ctrl.set_item_state(0, ListItemState::default(), ListItemState::Selected);
/// ```
pub fn set_item_state(&self, item: i64, state: ListItemState, state_mask: ListItemState) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
unsafe {
ffi::wxd_ListCtrl_SetItemState(
ptr,
item as c_longlong,
state.bits() as c_longlong,
state_mask.bits() as c_longlong,
)
}
}
/// Gets the state of an item using the ListItemState enum.
/// Returns false if the list control has been destroyed.
///
/// # Arguments
/// * `item` - The index of the item.
/// * `state_mask` - The specific state flag to check.
///
/// # Returns
/// Returns true if the state specified by state_mask is set, false otherwise.
///
/// # Example
/// ```no_run
/// # use wxdragon::prelude::*;
/// # let parent = Frame::builder().build();
/// # let list_ctrl = ListCtrl::builder(&parent)
/// # .with_style(ListCtrlStyle::Report)
/// # .build();
/// // Check if an item is selected:
/// let is_selected = list_ctrl.get_item_state(0, ListItemState::Selected);
/// ```
pub fn get_item_state(&self, item: i64, state_mask: ListItemState) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
let state = unsafe { ffi::wxd_ListCtrl_GetItemState(ptr, item as c_longlong, state_mask.bits() as c_longlong) };
state != 0
}
/// Gets the next item based on geometry and state.
/// Returns -1 if the list control has been destroyed.
pub fn get_next_item(&self, item: i64, geometry: ListNextItemFlag, state: ListItemState) -> i32 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return -1;
}
unsafe { ffi::wxd_ListCtrl_GetNextItem(ptr, item as c_longlong, geometry as c_int, state.bits() as c_int) }
}
/// Gets the first selected item in the list control.
/// Returns -1 if the list control has been destroyed.
pub fn get_first_selected_item(&self) -> i32 {
self.get_next_item(-1, ListNextItemFlag::All, ListItemState::Selected)
}
/// Sets the image for a specific item.
/// No-op (returns false) if the list control has been destroyed.
///
/// # Arguments
/// * `item_index` - The 0-based index of the item.
/// * `image_index` - The index of the image in the image list.
///
/// # Returns
/// `true` if successful, `false` otherwise.
pub fn set_item_image(&self, item_index: i64, image_index: i32) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
unsafe { ffi::wxd_ListCtrl_SetItemImageIndex(ptr, item_index as c_longlong, image_index) }
}
/// Deletes the specified item.
/// No-op (returns false) if the list control has been destroyed.
pub fn delete_item(&self, item: i64) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
unsafe { ffi::wxd_ListCtrl_DeleteItem(ptr, item as c_longlong) }
}
/// Deletes all items from the list control.
/// No-op (returns false) if the list control has been destroyed.
pub fn delete_all_items(&self) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
unsafe { ffi::wxd_ListCtrl_DeleteAllItems(ptr) }
}
/// Deletes all items and columns from the list control.
/// No-op (returns false) if the list control has been destroyed.
pub fn clear_all(&self) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
unsafe { ffi::wxd_ListCtrl_ClearAll(ptr) }
}
/// Gets the number of selected items.
/// Returns 0 if the list control has been destroyed.
pub fn get_selected_item_count(&self) -> i32 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return 0;
}
unsafe { ffi::wxd_ListCtrl_GetSelectedItemCount(ptr) }
}
/// Ensures that the specified item is visible.
/// No-op (returns false) if the list control has been destroyed.
pub fn ensure_visible(&self, item: i64) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
unsafe { ffi::wxd_ListCtrl_EnsureVisible(ptr, item as c_longlong) }
}
/// Determines which item, if any, is at the specified point.
/// Returns a tuple (item_index, flags, subitem_index).
/// Returns (-1, 0, 0) if the list control has been destroyed.
pub fn hit_test(&self, point: Point) -> (i32, i32, i32) {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return (-1, 0, 0);
}
let mut flags: i32 = 0;
let mut subitem: c_longlong = 0;
let item =
unsafe { ffi::wxd_ListCtrl_HitTest(ptr, point.into(), &mut flags as *mut i32, &mut subitem as *mut c_longlong) };
(item, flags, subitem as i32)
}
/// Starts editing the label of the specified item.
/// Panics if the list control has been destroyed or editing fails.
///
/// # Returns
/// Returns the TextCtrl that will be used to edit the label.
/// The caller does not own this TextCtrl; it will be deleted automatically
/// when editing is finished.
pub fn edit_label(&self, item: i64) -> crate::widgets::textctrl::TextCtrl {
let listctrl_ptr = self.listctrl_ptr();
if listctrl_ptr.is_null() {
panic!("Cannot edit label: ListCtrl has been destroyed");
}
let ptr = unsafe { ffi::wxd_ListCtrl_EditLabel(listctrl_ptr, item as c_longlong) };
if ptr.is_null() {
panic!("Failed to start editing item label: FFI returned null pointer.");
}
unsafe { crate::widgets::textctrl::TextCtrl::from_ptr(ptr) }
}
// --- Item Appearance Methods ---
/// Sets the background color of an item.
/// No-op if the list control has been destroyed.
pub fn set_item_background_colour(&self, item: i64, colour: &crate::color::Colour) {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return;
}
unsafe { ffi::wxd_ListCtrl_SetItemBackgroundColour(ptr, item as c_longlong, (*colour).into()) }
}
/// Sets the text color of an item.
/// No-op if the list control has been destroyed.
pub fn set_item_text_colour(&self, item: i64, colour: &crate::color::Colour) {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return;
}
unsafe { ffi::wxd_ListCtrl_SetItemTextColour(ptr, item as c_longlong, (*colour).into()) }
}
/// Gets the background color of an item.
/// Returns white if the list control has been destroyed.
pub fn get_item_background_colour(&self, item: i64) -> crate::color::Colour {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return crate::color::Colour::new(255, 255, 255, 255);
}
unsafe {
let c_colour = ffi::wxd_ListCtrl_GetItemBackgroundColour(ptr, item as c_longlong);
crate::color::Colour::from(c_colour)
}
}
/// Gets the text color of an item.
/// Returns black if the list control has been destroyed.
pub fn get_item_text_colour(&self, item: i64) -> crate::color::Colour {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return crate::color::Colour::new(0, 0, 0, 255);
}
unsafe {
let c_colour = ffi::wxd_ListCtrl_GetItemTextColour(ptr, item as c_longlong);
crate::color::Colour::from(c_colour)
}
}
// --- Column Management Methods ---
/// Sets the custom order of columns.
/// No-op (returns false) if the list control has been destroyed.
///
/// By default, the columns in a list control appear in order of their indices (0, 1, 2, ...).
/// This method allows you to set a custom visual order for the columns.
pub fn set_columns_order(&self, orders: &[i32]) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
unsafe { ffi::wxd_ListCtrl_SetColumnsOrder(ptr, orders.len() as c_int, orders.as_ptr() as *mut c_int) }
}
/// Gets the custom order of all columns.
/// Returns empty vector if the list control has been destroyed.
///
/// Returns a vector of column indices in their current display order.
pub fn get_columns_order(&self) -> Vec<i32> {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return Vec::new();
}
unsafe {
let mut count: c_int = 0;
let result_ptr = ffi::wxd_ListCtrl_GetColumnsOrder(ptr, &mut count as *mut c_int);
if result_ptr.is_null() || count <= 0 {
return Vec::new();
}
let mut result = Vec::with_capacity(count as usize);
for i in 0..count {
result.push(*result_ptr.offset(i as isize));
}
// Free the memory allocated by the C function
ffi::wxd_free_int_array(result_ptr);
result
}
}
/// Gets the position in which the given column is currently displayed.
/// Returns -1 if the list control has been destroyed or an error occurred.
///
/// Returns the position where the column is currently shown, or -1 if an error occurred.
pub fn get_column_order(&self, col: i32) -> i32 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return -1;
}
unsafe { ffi::wxd_ListCtrl_GetColumnOrder(ptr, col) }
}
/// Gets the column index at the given display position.
/// Returns -1 if the list control has been destroyed or an error occurred.
///
/// Returns the index of the column which is shown at the specified position, or -1 if an error occurred.
pub fn get_column_index_from_order(&self, pos: i32) -> i32 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return -1;
}
unsafe { ffi::wxd_ListCtrl_GetColumnIndexFromOrder(ptr, pos) }
}
// --- Virtual List Support Methods ---
/// Sets the number of items in a virtual list control.
/// No-op if the list control has been destroyed.
///
/// Must be used with a list control created with the `ListCtrlStyle::Virtual` style.
pub fn set_item_count(&self, count: i64) {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return;
}
unsafe { ffi::wxd_ListCtrl_SetItemCount(ptr, count as c_longlong) }
}
/// Refreshes a single item in a virtual list control.
/// No-op if the list control has been destroyed.
pub fn refresh_item(&self, item: i64) {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return;
}
unsafe { ffi::wxd_ListCtrl_RefreshItem(ptr, item as c_longlong) }
}
/// Refreshes a range of items in a virtual list control.
/// No-op if the list control has been destroyed.
pub fn refresh_items(&self, item_from: i64, item_to: i64) {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return;
}
unsafe { ffi::wxd_ListCtrl_RefreshItems(ptr, item_from as c_longlong, item_to as c_longlong) }
}
// --- ImageList Methods ---
/// Sets the image list for the control.
/// The ListCtrl takes ownership of the ImageList.
/// No-op if the list control has been destroyed.
///
/// # Arguments
/// * `image_list` - The ImageList to set.
/// * `list_type` - Which image list to set (e.g., `image_list_type::NORMAL`, `image_list_type::SMALL`).
pub fn set_image_list(&self, image_list: ImageList, list_type: i32) {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return;
}
unsafe {
ffi::wxd_ListCtrl_SetImageList(
ptr,
image_list.as_ptr(), // Pass the raw pointer
list_type,
);
}
// wxWidgets takes ownership of the image list
std::mem::forget(image_list);
}
/// Gets the image list associated with the control.
/// The ListCtrl owns the ImageList, so the caller should not delete it.
/// Returns None if the list control has been destroyed.
///
/// # Arguments
/// * `list_type` - Which image list to get (e.g., `image_list_type::NORMAL`, `image_list_type::SMALL`).
///
/// # Returns
/// An Option containing the ImageList if it exists, otherwise None.
pub fn get_image_list(&self, list_type: i32) -> Option<ImageList> {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return None;
}
let img_ptr = unsafe { ffi::wxd_ListCtrl_GetImageList(ptr, list_type) };
if img_ptr.is_null() {
None
} else {
// The ImageList is owned by wxWidgets, so create an unowned wrapper
Some(unsafe { ImageList::from_ptr_unowned(img_ptr) })
}
}
}
// Implement the HasItemData trait for ListCtrl
impl HasItemData for ListCtrl {
fn set_custom_data<T: Any + Send + Sync + 'static>(&self, item_id: impl Into<u64>, data: T) -> u64 {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return 0;
}
let item_index = item_id.into() as i64;
// First check if there's already data associated with this item
let existing_data_id = unsafe { ffi::wxd_ListCtrl_GetItemData(ptr, item_index as c_longlong) 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 and get a unique ID
let data_id = store_item_data(data);
// Store the ID as an integer in the list item using the native set_item_data
let result = unsafe { ffi::wxd_ListCtrl_SetItemData(ptr, item_index as c_longlong, data_id as c_longlong) };
// If setting failed, remove the data from the registry and return 0
if !result {
let _ = remove_item_data(data_id);
return 0;
}
data_id
}
fn get_custom_data(&self, item_id: impl Into<u64>) -> Option<Arc<dyn Any + Send + Sync>> {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return None;
}
let item_index = item_id.into() as i64;
// Get the data ID using the native get_item_data
let data_id = unsafe { ffi::wxd_ListCtrl_GetItemData(ptr, item_index as c_longlong) 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.listctrl_ptr();
if ptr.is_null() {
return false;
}
let item_index = item_id.into() as i64;
// Get the data ID using the native get_item_data
let data_id = unsafe { ffi::wxd_ListCtrl_GetItemData(ptr, item_index as c_longlong) as u64 };
// If the ID is non-zero and exists in the registry, there is custom data
data_id != 0 && get_item_data(data_id).is_some()
}
fn clear_custom_data(&self, item_id: impl Into<u64>) -> bool {
let ptr = self.listctrl_ptr();
if ptr.is_null() {
return false;
}
let item_index = item_id.into() as i64;
// Get the data ID using the native get_item_data
let data_id = unsafe { ffi::wxd_ListCtrl_GetItemData(ptr, item_index as c_longlong) as u64 };
// Only attempt to remove data if there's actually data to remove
if data_id != 0 {
// Remove the data from the registry
let _ = remove_item_data(data_id);
}
// Clear the data in the list item by setting it to 0
unsafe { ffi::wxd_ListCtrl_SetItemData(ptr, item_index as c_longlong, 0) }
}
fn cleanup_all_custom_data(&self) {
// Get the total number of items in the list control
let item_count = self.get_item_count();
// Iterate through all items and clear their custom data
for i in 0..item_count {
self.clear_custom_data(i as u64);
}
}
}
// Manual WxWidget implementation for ListCtrl (using WindowHandle)
impl WxWidget for ListCtrl {
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 ListCtrl {
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 scrolling functionality for ListCtrl
impl crate::scrollable::WxScrollable for ListCtrl {}
// Use the widget_builder macro for ListCtrl
widget_builder!(
name: ListCtrl,
parent_type: &'a dyn WxWidget,
style_type: ListCtrlStyle,
fields: {},
build_impl: |slf| {
let list_ctrl = ListCtrl::new_impl(
slf.parent.handle_ptr(),
slf.id,
slf.pos,
slf.size,
slf.style.bits()
);
// Set up cleanup for custom data
list_ctrl.setup_cleanup();
list_ctrl
}
);
// Register for destroy event to clean up custom data
impl ListCtrl {
/// Sets up the ListCtrl 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 list_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
list_ctrl_clone.cleanup_all_custom_data();
});
}
/// Manually clean up all custom data associated with this ListCtrl.
/// This can be called explicitly when needed.
pub fn cleanup_custom_data(&self) {
self.cleanup_all_custom_data();
}
}
// Implement event handlers for ListCtrl
crate::implement_widget_local_event_handlers!(
ListCtrl,
ListCtrlEvent,
ListCtrlEventData,
ItemSelected => item_selected, EventType::LIST_ITEM_SELECTED,
ItemDeselected => item_deselected, EventType::LIST_ITEM_DESELECTED,
ItemActivated => item_activated, EventType::LIST_ITEM_ACTIVATED,
ItemFocused => item_focused, EventType::LIST_ITEM_FOCUSED,
ColumnClick => column_click, EventType::LIST_COL_CLICK,
ColumnRightClick => column_right_click, EventType::LIST_COL_RIGHT_CLICK,
ColumnBeginDrag => column_begin_drag, EventType::LIST_COL_BEGIN_DRAG,
BeginLabelEdit => begin_label_edit, EventType::LIST_BEGIN_LABEL_EDIT,
EndLabelEdit => end_label_edit, EventType::LIST_END_LABEL_EDIT,
BeginDrag => begin_drag, EventType::LIST_BEGIN_DRAG,
BeginRDrag => begin_right_drag, EventType::LIST_BEGIN_RDRAG,
DeleteItem => delete_item_event, EventType::LIST_DELETE_ITEM,
DeleteAllItems => delete_all_items_event, EventType::LIST_DELETE_ALL_ITEMS,
KeyDown => key_down, EventType::LIST_KEY_DOWN,
InsertItem => insert_item_event, EventType::LIST_INSERT_ITEM,
ItemRightClick => item_right_click, EventType::LIST_ITEM_RIGHT_CLICK,
ItemMiddleClick => item_middle_click, EventType::LIST_ITEM_MIDDLE_CLICK
);
// XRC Support - enables ListCtrl to be created from XRC-managed pointers
#[cfg(feature = "xrc")]
impl crate::xrc::XrcSupport for ListCtrl {
unsafe fn from_xrc_ptr(ptr: *mut ffi::wxd_Window_t) -> Self {
ListCtrl {
handle: WindowHandle::new(ptr),
}
}
}
// Widget casting support for ListCtrl
impl crate::window::FromWindowWithClassName for ListCtrl {
fn class_name() -> &'static str {
"wxListCtrl"
}
unsafe fn from_ptr(ptr: *mut ffi::wxd_Window_t) -> Self {
ListCtrl {
handle: WindowHandle::new(ptr),
}
}
}