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
//!
//! Safe wrapper for wxTreebook.
use crate::event::{Event, EventType, WxEvtHandler};
use crate::geometry::{Point, Size};
use crate::id::Id;
use crate::window::{WindowHandle, WxWidget};
use std::ffi::CString;
use wxdragon_sys as ffi;
// --- Treebook Styles ---
widget_style_enum!(
name: TreebookStyle,
doc: "Style flags for Treebook widget.",
variants: {
Default: ffi::WXD_BK_DEFAULT, "Default style.",
Top: ffi::WXD_BK_TOP, "Place tabs at the top.",
Bottom: ffi::WXD_BK_BOTTOM, "Place tabs at the bottom.",
Left: ffi::WXD_BK_LEFT, "Place tabs at the left.",
Right: ffi::WXD_BK_RIGHT, "Place tabs at the right."
},
default_variant: Default
);
/// Events emitted by Treebook
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TreebookEvent {
/// Emitted when the selected page changes
PageChanged,
/// Emitted when the selected page is about to change
PageChanging,
/// Emitted when a tree node is expanded
NodeExpanded,
/// Emitted when a tree node is collapsed
NodeCollapsed,
}
/// Event data for Treebook page changed/changing events
#[derive(Debug)]
pub struct TreebookEventData {
base: Event,
}
impl TreebookEventData {
/// Create a new NotebookEventData with the provided Event
pub fn new(event: Event) -> Self {
Self { base: event }
}
/// Skip this event (allowing the default processing to occur)
pub fn skip(&self, skip: bool) {
self.base.skip(skip);
}
/// Get the ID of the control that generated the event
pub fn get_id(&self) -> i32 {
self.base.get_id()
}
/// Gets the page that has been selected.
/// For a `PageChanged` event, this is the new page.
pub fn get_selection(&self) -> Option<i32> {
if self.base.is_null() {
return None;
}
let val = unsafe { ffi::wxd_NotebookEvent_GetSelection(self.base.0) };
if val == ffi::WXD_NOT_FOUND as i32 { None } else { Some(val) }
}
/// Gets the page that was selected before the change.
/// For a `PageChanged` event, this is the old page.
pub fn get_old_selection(&self) -> Option<i32> {
if self.base.is_null() {
return None;
}
let val = unsafe { ffi::wxd_NotebookEvent_GetOldSelection(self.base.0) };
if val == ffi::WXD_NOT_FOUND as i32 { None } else { Some(val) }
}
}
/// Represents a wxTreebook control.
///
/// Treebook 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.
///
/// # Example
/// ```ignore
/// let treebook = Treebook::builder(&frame).build();
///
/// // Treebook is Copy - no clone needed for closures!
/// treebook.bind_page_changed(move |_| {
/// // Safe: if treebook was destroyed, this is a no-op
/// let selection = treebook.get_selection();
/// });
///
/// // After parent destruction, treebook operations are safe no-ops
/// frame.destroy();
/// assert!(!treebook.is_valid());
/// ```
#[derive(Clone, Copy)]
pub struct Treebook {
/// Safe handle to the underlying wxTreebook - automatically invalidated on destroy
handle: WindowHandle,
}
impl Treebook {
/// Creates a new Treebook builder.
pub fn builder(parent: &dyn WxWidget) -> TreebookBuilder<'_> {
TreebookBuilder::new(parent)
}
// Internal constructor
pub(crate) unsafe fn from_ptr(ptr: *mut ffi::wxd_Treebook_t) -> Self {
Treebook {
handle: WindowHandle::new(ptr as *mut ffi::wxd_Window_t),
}
}
/// Helper to get raw treebook pointer, returns null if widget has been destroyed
#[inline]
fn treebook_ptr(&self) -> *mut ffi::wxd_Treebook_t {
self.handle
.get_ptr()
.map(|p| p as *mut ffi::wxd_Treebook_t)
.unwrap_or(std::ptr::null_mut())
}
/// 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(), "Treebook parent cannot be null");
let ptr = unsafe {
ffi::wxd_Treebook_new(
parent_ptr,
id,
pos.x,
pos.y,
size.width,
size.height,
style as ffi::wxd_Style_t,
)
};
if ptr.is_null() {
panic!("Failed to create wxTreebook");
}
unsafe { Treebook::from_ptr(ptr) }
}
/// Adds a new page to the treebook control.
/// Returns the index of the added page, or -1 on failure.
/// No-op if the treebook has been destroyed.
pub fn add_page<W: WxWidget>(&self, page: &W, text: &str, select: bool, image_id: i32) -> i32 {
let ptr = self.treebook_ptr();
if ptr.is_null() {
return -1;
}
let page_ptr = page.handle_ptr();
let text_c = CString::new(text).unwrap_or_default();
unsafe { ffi::wxd_Treebook_AddPage(ptr, page_ptr, text_c.as_ptr(), select as i32, image_id) }
}
/// Adds a new sub-page to the last top-level page added to the treebook control.
/// Returns the index of the added page, or -1 on failure.
/// No-op if the treebook has been destroyed.
pub fn add_sub_page<W: WxWidget>(&self, page: &W, text: &str, select: bool, image_id: i32) -> i32 {
let ptr = self.treebook_ptr();
if ptr.is_null() {
return -1;
}
let page_ptr = page.handle_ptr();
let text_c = CString::new(text).unwrap_or_default();
unsafe { ffi::wxd_Treebook_AddSubPage(ptr, page_ptr, text_c.as_ptr(), select as i32, image_id) }
}
/// Gets the number of pages in the treebook.
/// Returns 0 if the treebook has been destroyed.
pub fn get_page_count(&self) -> i32 {
let ptr = self.treebook_ptr();
if ptr.is_null() {
return 0;
}
unsafe { ffi::wxd_Treebook_GetPageCount(ptr) }
}
/// Gets the currently selected page, or -1 if none is selected.
/// Returns -1 if the treebook has been destroyed.
pub fn get_selection(&self) -> i32 {
let ptr = self.treebook_ptr();
if ptr.is_null() {
return -1;
}
unsafe { ffi::wxd_Treebook_GetSelection(ptr) }
}
/// Sets the selection to the given page index.
/// Returns the index of the previously selected page.
/// Returns -1 if the treebook has been destroyed.
pub fn set_selection(&self, n: usize) -> i32 {
let ptr = self.treebook_ptr();
if ptr.is_null() {
return -1;
}
unsafe { ffi::wxd_Treebook_SetSelection(ptr, n) }
}
/// Sets the text for the given page.
/// No-op if the treebook has been destroyed.
pub fn set_page_text(&self, n: usize, text: &str) {
let ptr = self.treebook_ptr();
if ptr.is_null() {
return;
}
let text_c = CString::new(text).unwrap_or_default();
unsafe {
ffi::wxd_Treebook_SetPageText(ptr, n, text_c.as_ptr());
}
}
/// Gets the text for the given page.
/// Returns empty string if the treebook has been destroyed.
pub fn get_page_text(&self, n: usize) -> String {
let ptr = self.treebook_ptr();
if ptr.is_null() {
return String::new();
}
unsafe {
// First call to get the size needed
let needed_len_with_null = ffi::wxd_Treebook_GetPageText(ptr, n, std::ptr::null_mut(), 0);
if needed_len_with_null <= 1 {
// 0 or 1 means error or empty string
return String::new();
}
let buffer_size = needed_len_with_null as usize;
let mut buffer: Vec<u8> = Vec::with_capacity(buffer_size);
// Second call to actually get the string
let copied_len_with_null = ffi::wxd_Treebook_GetPageText(ptr, n, buffer.as_mut_ptr() as *mut i8, buffer_size as i32);
if copied_len_with_null <= 0 {
// Check for error on second call
return String::new();
}
// Assuming the C++ side returned needed size including null,
// and successfully copied that amount (or truncated).
// The actual number of bytes excluding null is needed_len_with_null - 1.
let actual_len = (copied_len_with_null - 1) as usize;
buffer.set_len(actual_len.min(buffer_size - 1)); // Set length to actual content size (excluding null)
String::from_utf8_lossy(&buffer).into_owned()
}
}
/// Returns the underlying WindowHandle for this treebook.
pub fn window_handle(&self) -> WindowHandle {
self.handle
}
}
// Manual WxWidget implementation for Treebook (using WindowHandle)
impl WxWidget for Treebook {
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 Treebook {
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 Treebook {}
// Use the widget_builder macro for Treebook
widget_builder!(
name: Treebook,
parent_type: &'a dyn WxWidget,
style_type: TreebookStyle,
fields: {},
build_impl: |slf| {
Treebook::new_impl(
slf.parent.handle_ptr(),
slf.id,
slf.pos,
slf.size,
slf.style.bits()
)
}
);
// Implement Treebook-specific event handlers
crate::implement_widget_local_event_handlers!(
Treebook,
TreebookEvent,
TreebookEventData,
PageChanged => page_changed, EventType::TREEBOOK_PAGE_CHANGED,
PageChanging => page_changing, EventType::TREEBOOK_PAGE_CHANGING,
NodeExpanded => node_expanded, EventType::TREEBOOK_NODE_EXPANDED,
NodeCollapsed => node_collapsed, EventType::TREEBOOK_NODE_COLLAPSED
);
// XRC Support - enables Treebook to be created from XRC-managed pointers
#[cfg(feature = "xrc")]
impl crate::xrc::XrcSupport for Treebook {
unsafe fn from_xrc_ptr(ptr: *mut ffi::wxd_Window_t) -> Self {
Treebook {
handle: WindowHandle::new(ptr),
}
}
}
// Enable widget casting for Treebook
impl crate::window::FromWindowWithClassName for Treebook {
fn class_name() -> &'static str {
"wxTreebook"
}
unsafe fn from_ptr(ptr: *mut ffi::wxd_Window_t) -> Self {
Treebook {
handle: WindowHandle::new(ptr),
}
}
}