libui 0.4.0

A native, cross-platform and lightweight UI toolkit.
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
use super::Control;
use callback_helpers::{from_void_ptr, to_heap_ptr};
use libui_ffi::{
    self, uiControl, uiSortIndicator, uiTable, uiTableModel, uiTableModelHandler, uiTableParams,
    uiTableSelectionMode, uiTableValue, uiTableValueType,
};
use std::cell::RefCell;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::{c_int, c_uint, c_void};
use std::rc::Rc;

/// An enum of possible `Table` cell/column types.
#[derive(Copy, Clone, Debug)]
pub enum TableValueType {
    String,
    Image,
    Int,
    Color,
}

// libui intends its enums to be u32 but is unable to express that
// in C with the `enum` statement. Bindgen then has to guess.
// On some platforms it emits u32, on some i32, triggering
// compile errors. Since there is no option for this in bindgen,
// we have to work around this here. Related bindgen questions:
// https://github.com/rust-lang/rust-bindgen/issues/1361
// https://github.com/rust-lang/rust-bindgen/issues/1907
impl TableValueType {
    fn from_ui(t: uiTableValueType) -> TableValueType {
        const X_STRING: c_uint = libui_ffi::uiTableValueTypeString as c_uint;
        const X_IMAGE: c_uint = libui_ffi::uiTableValueTypeImage as c_uint;
        const X_INT: c_uint = libui_ffi::uiTableValueTypeInt as c_uint;
        const X_COLOR: c_uint = libui_ffi::uiTableValueTypeColor as c_uint;
        match t {
            X_STRING => TableValueType::String,
            X_IMAGE => TableValueType::Image,
            X_INT => TableValueType::Int,
            X_COLOR => TableValueType::Color,
            _ => panic!("Unsupported table value type"),
        }
    }

    fn into_ui(self) -> uiTableValueType {
        use self::TableValueType::*;
        return match self {
            String => libui_ffi::uiTableValueTypeString,
            Image => libui_ffi::uiTableValueTypeImage,
            Int => libui_ffi::uiTableValueTypeInt,
            Color => libui_ffi::uiTableValueTypeColor,
        } as uiTableValueType;
    }
}

/// An enum representing the value of a `Table` cell.
pub enum TableValue {
    Int(i32),
    String(String),
    Color { r: f64, g: f64, b: f64, a: f64 },
}

pub trait TableDataSource {
    fn num_columns(&mut self) -> i32;
    fn num_rows(&mut self) -> i32;
    fn column_type(&mut self, column: i32) -> TableValueType;

    fn cell(&mut self, column: i32, row: i32) -> TableValue;
    fn set_cell(&mut self, column: i32, row: i32, value: TableValue);
}

extern "C" fn c_num_columns(
    ui_handler: *mut uiTableModelHandler,
    _ui_model: *mut uiTableModel,
) -> c_int {
    unsafe {
        // This cast is safe because RustTableModelHandler has a compatible layout.
        // Unfortunately we can't do the same with `ui_model` because we don't store
        // the object itself but just a pointer we didn't create.
        // TODO: deal with the model somehow.
        (*(ui_handler as *mut RustTableModelHandler))
            .trait_object
            .borrow_mut()
            .num_columns()
    }
}

extern "C" fn c_num_rows(
    ui_handler: *mut uiTableModelHandler,
    _ui_model: *mut uiTableModel,
) -> c_int {
    unsafe {
        (*(ui_handler as *mut RustTableModelHandler))
            .trait_object
            .borrow_mut()
            .num_rows()
    }
}

extern "C" fn c_column_type(
    ui_handler: *mut uiTableModelHandler,
    _ui_model: *mut uiTableModel,
    column: c_int,
) -> uiTableValueType {
    let t = unsafe {
        (*(ui_handler as *mut RustTableModelHandler))
            .trait_object
            .borrow_mut()
            .column_type(column)
    };

    t.into_ui()
}

extern "C" fn c_cell_value(
    ui_handler: *mut uiTableModelHandler,
    _ui_model: *mut uiTableModel,
    row: c_int,
    column: c_int,
) -> *mut uiTableValue {
    let value = unsafe {
        (*(ui_handler as *mut RustTableModelHandler))
            .trait_object
            .borrow_mut()
            .cell(column, row)
    };

    match value {
        TableValue::Int(v) => unsafe { libui_ffi::uiNewTableValueInt(v) },
        TableValue::String(s) => unsafe {
            let c_string = CString::new(s.as_bytes().to_vec()).unwrap();
            libui_ffi::uiNewTableValueString(c_string.as_ptr())
        },
        TableValue::Color { r, g, b, a } => unsafe { libui_ffi::uiNewTableValueColor(r, g, b, a) },
    }
}

extern "C" fn c_set_cell_value(
    ui_handler: *mut uiTableModelHandler,
    _ui_model: *mut uiTableModel,
    row: c_int,
    column: c_int,
    value: *const uiTableValue,
) {
    unsafe {
        // Button columns call SetCellValue() with a value of `NULL` in case of
        // a click. We don't want to have a special enum or Option<TableValue> just for
        // this one instance, so we provide an integer instead. The function is only ever
        // called for clicks anyway, making a check on the users side unnecessary.
        if value == std::ptr::null() {
            (*(ui_handler as *mut RustTableModelHandler))
                .trait_object
                .borrow_mut()
                .set_cell(column, row, TableValue::Int(0));
            return;
        }

        let vt = libui_ffi::uiTableValueGetType(value);
        let rt = TableValueType::from_ui(vt);

        let rust_value = match rt {
            TableValueType::Int => {
                let i = libui_ffi::uiTableValueInt(value);
                TableValue::Int(i)
            }
            TableValueType::String => {
                let s = libui_ffi::uiTableValueString(value);
                TableValue::String(CStr::from_ptr(s).to_string_lossy().into_owned())
            }
            TableValueType::Color => {
                let (mut r, mut g, mut b, mut a) = (0.0, 0.0, 0.0, 0.0);
                libui_ffi::uiTableValueColor(value, &mut r, &mut g, &mut b, &mut a);
                TableValue::Color { r, g, b, a }
            }
            _ => panic!("Unsupported table value type"),
        };

        (*(ui_handler as *mut RustTableModelHandler))
            .trait_object
            .borrow_mut()
            .set_cell(column, row, rust_value);
    }
}

#[repr(C)]
struct RustTableModelHandler {
    ui_table_model_handler: uiTableModelHandler,
    trait_object: Rc<RefCell<dyn TableDataSource>>,
}

impl RustTableModelHandler {
    fn new(trait_object: Rc<RefCell<dyn TableDataSource>>) -> Self {
        RustTableModelHandler {
            ui_table_model_handler: libui_ffi::uiTableModelHandler {
                NumColumns: Some(c_num_columns),
                ColumnType: Some(c_column_type),
                NumRows: Some(c_num_rows),
                CellValue: Some(c_cell_value),
                SetCellValue: Some(c_set_cell_value),
            },
            trait_object,
        }
    }
}

/// The view model for a `Table` control.
pub struct TableModel {
    ui_table_model: *mut libui_ffi::uiTableModel,
    _model_handler: Box<RustTableModelHandler>,
}

impl TableModel {
    pub fn new(data_source: Rc<RefCell<dyn TableDataSource>>) -> TableModel {
        unsafe {
            let mut handler = Box::new(RustTableModelHandler::new(data_source));
            let ptr = handler.as_mut() as *mut RustTableModelHandler;
            TableModel {
                ui_table_model: libui_ffi::uiNewTableModel(
                    ptr as *mut libui_ffi::uiTableModelHandler,
                ),
                _model_handler: handler, // We store the object to bind its lifetime to ours.
            }
        }
    }

    /// Informs all associated `Table` views that a new row has been added.
    ///
    /// You must insert the row data in your model before calling this function.
    /// `TableDataSource::num_rows()` must represent the new row count before you call this function.
    pub fn notify_row_inserted(&self, new_row: i32) {
        unsafe {
            libui_ffi::uiTableModelRowInserted(self.ui_table_model, new_row);
        }
    }

    /// Informs all associated `Table` views that a row has been changed.
    ///
    /// You do NOT need to call this method from `TableDataSource::set_cell()`, but NEED
    /// to call this if your data changes at any other point.
    pub fn notify_row_changed(&self, row: i32) {
        unsafe {
            libui_ffi::uiTableModelRowChanged(self.ui_table_model, row);
        }
    }

    /// Informs all associated `Table` views that a row has been deleted.
    ///
    /// You must delete the row from your model before you call this function.
    /// `TableDataSource::num_rows()` must represent the new row count before you call this function.
    pub fn notify_row_deleted(&self, old_row: i32) {
        unsafe {
            libui_ffi::uiTableModelRowDeleted(self.ui_table_model, old_row);
        }
    }
}

impl Drop for TableModel {
    fn drop(&mut self) {
        unsafe {
            libui_ffi::uiFreeTableModel(self.ui_table_model);
        }
    }
}

/// The parameters to construct a `Table` with.
pub struct TableParameters {
    model: Rc<RefCell<TableModel>>,
    row_background_color_column: i32,
}

impl TableParameters {
    pub fn new(model: Rc<RefCell<TableModel>>) -> TableParameters {
        TableParameters {
            model: model,
            row_background_color_column: -1,
        }
    }
}

/// Describes a visual sorting indicator for `Table` columns.
#[derive(Copy, Clone, Debug)]
pub enum SortIndicator {
    None,
    Ascending,
    Descending,
}

impl SortIndicator {
    fn from_ui(t: uiSortIndicator) -> SortIndicator {
        // bindgen workaround: enum type
        const X_NONE: c_uint = libui_ffi::uiSortIndicatorNone as c_uint;
        const X_ASC: c_uint = libui_ffi::uiSortIndicatorAscending as c_uint;
        const X_DESC: c_uint = libui_ffi::uiSortIndicatorDescending as c_uint;
        match t {
            X_NONE => SortIndicator::None,
            X_ASC => SortIndicator::Ascending,
            X_DESC => SortIndicator::Descending,
            _ => panic!("Unsupported sort indicator"),
        }
    }

    fn into_ui(self) -> uiSortIndicator {
        use self::SortIndicator::*;
        return match self {
            None => libui_ffi::uiSortIndicatorNone,
            Ascending => libui_ffi::uiSortIndicatorAscending,
            Descending => libui_ffi::uiSortIndicatorDescending,
        } as uiSortIndicator;
    }
}

/// Describes how many `Table` rows can be selected.
#[derive(Copy, Clone, Debug)]
pub enum SelectionMode {
    None,
    ZeroOrOne,
    One,
    ZeroOrMany,
}

impl SelectionMode {
    fn from_ui(t: uiTableSelectionMode) -> SelectionMode {
        // bindgen workaround: enum type
        const X_NONE: c_uint = libui_ffi::uiTableSelectionModeNone as c_uint;
        const X_MAX_ONE: c_uint = libui_ffi::uiTableSelectionModeZeroOrOne as c_uint;
        const X_ONE: c_uint = libui_ffi::uiTableSelectionModeOne as c_uint;
        const X_MIN_ONE: c_uint = libui_ffi::uiTableSelectionModeZeroOrMany as c_uint;
        match t {
            X_NONE => SelectionMode::None,
            X_MAX_ONE => SelectionMode::ZeroOrOne,
            X_ONE => SelectionMode::One,
            X_MIN_ONE => SelectionMode::ZeroOrMany,
            _ => panic!("Unsupported selection mode"),
        }
    }

    fn into_ui(self) -> uiTableSelectionMode {
        use self::SelectionMode::*;
        return match self {
            None => libui_ffi::uiTableSelectionModeNone,
            ZeroOrOne => libui_ffi::uiTableSelectionModeZeroOrOne,
            One => libui_ffi::uiTableSelectionModeOne,
            ZeroOrMany => libui_ffi::uiTableSelectionModeZeroOrMany,
        } as uiTableSelectionMode;
    }
}

/// A structure holding additional information on text columns.
#[derive(Copy, Clone, Debug)]
pub struct TextColumnParameters {
    pub text_color_column: i32,
}

impl Default for TextColumnParameters {
    fn default() -> Self {
        Self {
            text_color_column: -1,
        }
    }
}

define_control! {
    /// A tabular control that can be used to display and edit data.
    /// The table itself does not store any data but is a "View" on
    /// a [`TableModel`] / [`TableDataSource`] which update the table
    /// and provide the data. It follows the the concept of separation of
    /// concerns, similar to common patterns like model-view-controller or
    /// model-view-adapter.
    ///
    /// Users must implement the [`TableDataSource`] trait to serve as their data storage
    /// or data storage adapter. It provides the actual data while also handling data edits.
    ///
    /// Then a [`TableModel`] object can be created from it. `TableModel` acts as a delegate
    /// for the underlying data store. Its purpose is to provide the data for views and inform
    /// about any updates.
    ///
    /// With the model, a new table can be created via [`Table::new()`]. Use the `append_XXX()`
    /// methods of the table object to select which data is to be displayed and how.
    rust_type: Table,
    sys_type: uiTable
}

impl Table {
    pub const COLUMN_READONLY: i32 = -1;
    pub const COLUMN_EDITABLE: i32 = -2;

    /// Instantiates a new `Table` using the supplied model.
    pub fn new(params: TableParameters) -> Table {
        unsafe {
            let mut ui_params = uiTableParams {
                Model: params.model.borrow().ui_table_model,
                RowBackgroundColorModelColumn: params.row_background_color_column,
            };
            // TODO: keep the model alive via the shared ptr. This requires storing it tho.
            // Because i am lazy, i leak the model for now.
            mem::forget(params.model);
            Table {
                // The parameter struct is not stored. we can safely provide
                // a raw pointer and let the struct go out of scope. Only the
                // uiTableModel inside must be kept alive.
                uiTable: libui_ffi::uiNewTable(&mut ui_params as *mut uiTableParams),
            }
        }
    }

    /// Appends a text column to the table.
    ///
    /// * `title`               - The columns header.
    /// * `text_model_column`   - Index to the model column with the text data ([`TableValue::String`]).
    /// * `state_model_column`  - Index to the model column with the state data ([`TableValue::Int`]). An entry with value != `0`
    ///                           means the text shall be editable. Alternatively use [`Table::COLUMN_EDITABLE`] or [`Table::COLUMN_READONLY`]
    ///                           for this parameter to make all rows either state.
    pub fn append_text_column(
        &mut self,

        title: &str,
        text_model_column: i32,
        state_model_column: i32,
    ) {
        unsafe {
            let c_title = CString::new(title.as_bytes().to_vec()).unwrap();
            libui_ffi::uiTableAppendTextColumn(
                self.uiTable,
                c_title.as_ptr(),
                text_model_column,
                state_model_column,
                std::ptr::null_mut(), // TODO: support text params
            );
        }
    }

    /// Appends a text column to the table, allowing for colored text using the [`TextColumnParameters`] argument.
    ///
    /// * `title`               - The columns header.
    /// * `text_model_column`   - Index to the model column with the text data ([`TableValue::String`]),
    /// * `state_model_column`  - Index to the model column with the state data ([`TableValue::Int`]). An entry with value != `0`
    ///                           means the text shall be editable. Alternatively use [`Table::COLUMN_EDITABLE`] or [`Table::COLUMN_READONLY`]
    ///                           for this parameter to make all rows either state.
    /// * `params`              - [`TextColumnParameters::text_color_column`] must point to a [`TableValue::Color`] column in
    ///                           the table model, or be `-1` for using the default text color.
    pub fn append_text_column_with_params(
        &mut self,
        title: &str,
        text_model_column: i32,
        state_model_column: i32,
        params: TextColumnParameters,
    ) {
        unsafe {
            let c_title = CString::new(title.as_bytes().to_vec()).unwrap();
            let mut c_params = libui_ffi::uiTableTextColumnOptionalParams {
                ColorModelColumn: params.text_color_column,
            };
            libui_ffi::uiTableAppendTextColumn(
                self.uiTable,
                c_title.as_ptr(),
                text_model_column,
                state_model_column,
                &mut c_params as *mut libui_ffi::uiTableTextColumnOptionalParams,
            );
        }
    }

    // TODO: uiTableAppendImageColumn
    // TODO: uiTableAppendImageTextColumn

    /// Appends a column to the table containing a checkbox.
    ///
    /// * `title`               - The columns header.
    /// * `check_model_column`  - Index to the model column with the checkbox data.
    ///                           Must be of [`TableValue::Int`], where a value of `0` is an unchecked box.
    ///                           A value not equal to `0` results in a checked box.
    /// * `state_model_column`  - Index to the model column with the state data ([`TableValue::Int`]). An entry with value != `0`
    ///                           means the checkbox shall be editable. Alternatively use [`Table::COLUMN_EDITABLE`] or [`Table::COLUMN_READONLY`]
    ///                           for this parameter to make all rows either state.
    pub fn append_checkbox_column(
        &mut self,
        title: &str,
        check_model_column: i32,
        state_model_column: i32,
    ) {
        unsafe {
            let c_title = CString::new(title.as_bytes().to_vec()).unwrap();
            libui_ffi::uiTableAppendCheckboxColumn(
                self.uiTable,
                c_title.as_ptr(),
                check_model_column,
                state_model_column,
            );
        }
    }

    /// Appends a column to the table containing a checkbox and text.
    ///
    /// * `title`                   - The columns header.
    /// * `check_model_column`      - Index to the model column with the checkbox data.
    ///                               Must be of [`TableValue::Int`], where a value of `0` is an unchecked box.
    ///                               A value not equal to `0` results in a checked box.
    /// * `state_model_column`      - Index to the model column with the state data ([`TableValue::Int`]). An entry with value != `0`
    ///                               means the checkbox shall be editable. Alternatively use [`Table::COLUMN_EDITABLE`] or [`Table::COLUMN_READONLY`]
    ///                               for this parameter to make all rows either state.
    /// * `text_model_column`       - Index to the model column with the text data. Must be [`TableValue::String`].
    /// * `text_state_model_colum`  - Defines whether or not the text is editable, analogous to `state_model_column`.
    pub fn append_checkbox_text_column(
        &mut self,
        title: &str,
        check_model_column: i32,
        state_model_column: i32,
        text_model_column: i32,
        text_state_model_colum: i32,
    ) {
        unsafe {
            let c_title = CString::new(title.as_bytes().to_vec()).unwrap();
            libui_ffi::uiTableAppendCheckboxTextColumn(
                self.uiTable,
                c_title.as_ptr(),
                check_model_column,
                state_model_column,
                text_model_column,
                text_state_model_colum,
                std::ptr::null_mut(),
            );
        }
    }

    /// Appends a column to the table containing a progress bar.
    ///
    /// * `title`           - The columns header.
    /// * `model_column`    - Index to the model column with the progessbar data.
    ///                       Values must be of [`TableValue::Int`], between -1 and 100 representing the current progress.
    pub fn append_progressbar_column(&mut self, title: &str, model_column: i32) {
        unsafe {
            let c_title = CString::new(title.as_bytes().to_vec()).unwrap();
            libui_ffi::uiTableAppendProgressBarColumn(self.uiTable, c_title.as_ptr(), model_column);
        }
    }

    /// Appends a column to the table containing a button.
    ///
    /// * `title`               - The columns header.
    /// * `btn_model_column`    - Index to the model column with the button text ([`TableValue::String`]).
    ///                           Clicks are signaled to the [`TableDataSource`] by calling [`TableDataSource::set_cell()`]
    ///                           with a `TableValue::Int()`. Because no other reason for the call exists, checking the type is not strictly necessary.
    /// * `state_model_column`  - Index to the model column with the state data ([`TableValue::Int`]). An entry with value != `0`
    ///                           means the button shall be clickable. Alternatively use [`Table::COLUMN_EDITABLE`] or [`Table::COLUMN_READONLY`]
    ///                           for this parameter to make all rows either state.
    pub fn append_button_column(
        &mut self,
        title: &str,
        btn_model_column: i32,
        state_model_column: i32,
    ) {
        unsafe {
            let c_title = CString::new(title.as_bytes().to_vec()).unwrap();
            libui_ffi::uiTableAppendButtonColumn(
                self.uiTable,
                c_title.as_ptr(),
                btn_model_column,
                state_model_column,
            );
        }
    }

    /// Returns whether or not the table header is visible.
    pub fn header_visible(&self) -> bool {
        unsafe { libui_ffi::uiTableHeaderVisible(self.uiTable) != 0 }
    }

    /// Sets whether or not the table header is visible.
    pub fn set_header_visible(&mut self, visible: bool) {
        unsafe {
            libui_ffi::uiTableHeaderSetVisible(self.uiTable, visible as i32);
        }
    }

    /// Returns the column's sort indicator displayed in the table header.
    pub fn sort_indicator(&self, column: i32) -> SortIndicator {
        let v = unsafe { libui_ffi::uiTableHeaderSortIndicator(self.uiTable, column) };
        SortIndicator::from_ui(v)
    }

    /// Sets the column's sort indicator displayed in the table header.
    ///
    /// Use this to display appropriate arrows in the table header to indicate a sort direction.
    /// Setting the indicator is purely visual and does not perform any sorting.
    pub fn set_sort_indicator(&mut self, column: i32, indicator: SortIndicator) {
        unsafe {
            libui_ffi::uiTableHeaderSetSortIndicator(self.uiTable, column, indicator.into_ui());
        }
    }

    /// Returns the table column width in pixels.
    pub fn column_width(&self, column: i32) -> i32 {
        unsafe { libui_ffi::uiTableColumnWidth(self.uiTable, column) }
    }

    /// Sets the table column width in pixels.
    ///
    /// Setting the width to `-1` will restore automatic column sizing, matching
    /// either the width of the content or column header (which ever one is bigger).
    /// Note: Mac OS only resizes to the column header, not the content.
    pub fn set_column_width(&mut self, column: i32, width: i32) {
        unsafe {
            libui_ffi::uiTableColumnSetWidth(self.uiTable, column, width);
        }
    }

    /// Returns the table selection mode.
    pub fn selection_mode(&self) -> SelectionMode {
        let v = unsafe { libui_ffi::uiTableGetSelectionMode(self.uiTable) };
        SelectionMode::from_ui(v)
    }

    /// Sets the table selection mode.
    ///
    /// Note: All rows will be deselected if the existing selection is illegal in the new selection mode.
    pub fn set_selection_mode(&mut self, mode: SelectionMode) {
        unsafe {
            libui_ffi::uiTableSetSelectionMode(self.uiTable, mode.into_ui());
        }
    }

    /// Returns the current table selection.
    ///
    /// If nothing is selected, the vector will be empty.
    /// Warning: This function leaks memory currently.
    pub fn selection(&self) -> Vec<i32> {
        let mut selection: Vec<i32> = vec![];
        unsafe {
            let s = libui_ffi::uiTableGetSelection(self.uiTable);
            let p = (*s).Rows;
            for i in 0..(*s).NumRows {
                let v = *(p.offset(i as isize));
                selection.push(v);
            }
            // Linker error under Windows...
            // libui_ffi::uiFreeTableSelection(s);
        }
        selection
    }

    /// Sets the current table selection clearing any previous selection.
    ///
    /// Selecting more rows than the selection mode allows for results in nothing happening.
    pub fn set_selection(&mut self, selection: &Vec<i32>) {
        unsafe {
            // Our vector is only read, despite what struct and func signature say
            let mut s = libui_ffi::uiTableSelection {
                NumRows: selection.len() as i32,
                Rows: selection.as_ptr() as *mut i32,
            };
            libui_ffi::uiTableSetSelection(
                self.uiTable,
                &mut s as *mut libui_ffi::uiTableSelection,
            );
        }
    }

    /// Registers a callback for when the table selection changed.
    ///
    /// Note: The callback is not triggered when calling `set_selection()` or when
    /// the selection is cleared due to `set_selection_mode()`.
    pub fn on_selection_changed<'ctx, F>(&mut self, callback: F)
    where
        F: FnMut(&mut Table) + 'static,
    {
        extern "C" fn c_callback<G>(table: *mut uiTable, data: *mut c_void)
        where
            G: FnMut(&mut Table),
        {
            let mut table = Table { uiTable: table };
            unsafe {
                from_void_ptr::<G>(data)(&mut table);
            }
        }
        unsafe {
            libui_ffi::uiTableOnSelectionChanged(
                self.uiTable,
                Some(c_callback::<F>),
                to_heap_ptr(callback),
            );
        }
    }

    extern "C" fn generic_table_callback<G>(
        table: *mut uiTable,
        row_or_column: i32,
        data: *mut c_void,
    ) where
        G: FnMut(&mut Table, i32),
    {
        let mut table = Table { uiTable: table };
        unsafe {
            from_void_ptr::<G>(data)(&mut table, row_or_column);
        }
    }

    /// Registers a callback for when the user single clicks a table row.
    ///
    /// Note: Only one callback can be registered at a time.
    pub fn on_row_clicked<'ctx, F>(&mut self, callback: F)
    where
        F: FnMut(&mut Table, i32) + 'static,
    {
        unsafe {
            libui_ffi::uiTableOnRowClicked(
                self.uiTable,
                Some(Self::generic_table_callback::<F>),
                to_heap_ptr(callback),
            );
        }
    }

    /// Registers a callback for when the user double clicks a table row.
    ///
    /// Note: Only one callback can be registered at a time.
    /// Bug: The double click callback is always preceded by one `on_row_clicked()` callback.
    /// For unix systems linking against `GTK < 3.14` the preceding `on_row_clicked()` callback
    /// will be triggered twice.
    pub fn on_row_double_clicked<'ctx, F>(&mut self, callback: F)
    where
        F: FnMut(&mut Table, i32) + 'static,
    {
        unsafe {
            libui_ffi::uiTableOnRowDoubleClicked(
                self.uiTable,
                Some(Self::generic_table_callback::<F>),
                to_heap_ptr(callback),
            );
        }
    }

    /// Registers a callback for when a table column header is clicked.
    ///
    /// Note: Only one callback can be registered at a time.
    pub fn on_header_clicked<'ctx, F>(&mut self, callback: F)
    where
        F: FnMut(&mut Table, i32) + 'static,
    {
        unsafe {
            libui_ffi::uiTableHeaderOnClicked(
                self.uiTable,
                Some(Self::generic_table_callback::<F>),
                to_heap_ptr(callback),
            );
        }
    }
}