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
use crate::image::Image;
pub use crate::prelude::*;
use fltk_sys::text::*;
use std::{
    ffi::{CStr, CString},
    mem,
    os::raw,
};

/// Wraps a text buffer, Cloning a text buffer invalidates the underlying pointer, thus the no derive(Clone)
#[derive(Debug)]
pub struct TextBuffer {
    _inner: *mut Fl_Text_Buffer,
}

impl TextBuffer {
    /// Initialized a default text buffer
    pub fn default() -> Self {
        unsafe {
            let text_buffer = Fl_Text_Buffer_new();
            assert!(!text_buffer.is_null(), "Failed to instantiate text buffer!");
            TextBuffer {
                _inner: text_buffer,
            }
        }
    }
    /// Deletes the TextBuffer
    pub unsafe fn delete(&mut self) {
        Fl_Text_Buffer_delete(self._inner)
    }
    /// Initialized a text buffer from a pointer
    pub unsafe fn from_ptr(ptr: *mut Fl_Text_Buffer) -> Self {
        TextBuffer { _inner: ptr }
    }

    /// Returns the inner pointer from a text buffer
    pub fn as_ptr(&self) -> *mut Fl_Text_Buffer {
        self._inner
    }

    /// Sets the text of the buffer
    pub fn set_text(&mut self, txt: &str) {
        unsafe {
            let txt = CString::new(txt).unwrap();
            Fl_Text_Buffer_set_text(self._inner, txt.into_raw() as *const raw::c_char)
        }
    }

    /// Returns the text of the buffer
    pub fn text(&self) -> String {
        unsafe {
            let text = Fl_Text_Buffer_text(self._inner);
            assert!(!text.is_null(), "Failed to retrieve text from buffer!");
            CString::from_raw(text as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }

    /// Appends to the buffer
    pub fn append(&mut self, text: &str) {
        let text = CString::new(text).unwrap();
        unsafe { Fl_Text_Buffer_append(self._inner, text.into_raw() as *const raw::c_char) }
    }

    /// Get the length of the buffer
    pub fn length(&self) -> u32 {
        unsafe { Fl_Text_Buffer_length(self._inner) as u32 }
    }

    /// Removes from the buffer
    pub fn remove(&mut self, start: u32, end: u32) {
        debug_assert!(
            start <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        debug_assert!(
            end <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe {
            Fl_Text_Buffer_remove(self._inner, start as i32, end as i32);
        }
    }

    /// Returns the text within the range
    pub fn text_range(&self, start: u32, end: u32) -> Option<String> {
        debug_assert!(
            start <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        debug_assert!(
            end <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe {
            let x = Fl_Text_Buffer_text_range(self._inner, start as i32, end as i32);
            if x.is_null() {
                None
            } else {
                Some(
                    CString::from_raw(x as *mut raw::c_char)
                        .to_string_lossy()
                        .to_string(),
                )
            }
        }
    }

    /// Inserts text into a position
    pub fn insert(&mut self, pos: u32, text: &str) {
        debug_assert!(
            pos <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        let text = CString::new(text).unwrap();
        unsafe {
            Fl_Text_Buffer_insert(
                self._inner,
                pos as i32,
                text.into_raw() as *const raw::c_char,
            )
        }
    }

    /// Replaces text from position ```start``` to ```end```
    pub fn replace(&mut self, start: u32, end: u32, text: &str) {
        debug_assert!(
            start <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        debug_assert!(
            end <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        let text = CString::new(text).unwrap();
        unsafe {
            Fl_Text_Buffer_replace(
                self._inner,
                start as i32,
                end as i32,
                text.into_raw() as *const raw::c_char,
            )
        }
    }

    /// Copies text from a source buffer into the current buffer
    pub fn copy(&mut self, source_buf: &TextBuffer, start: u32, end: u32, to: u32) {
        debug_assert!(
            start <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        debug_assert!(
            end <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        debug_assert!(
            to <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe {
            Fl_Text_Buffer_copy(
                self._inner,
                source_buf.as_ptr(),
                start as i32,
                end as i32,
                to as i32,
            )
        }
    }

    /// Performs an undo operation on the buffer
    pub fn undo(&mut self) -> Result<(), FltkError> {
        unsafe {
            match Fl_Text_Buffer_undo(self._inner, std::ptr::null_mut()) {
                0 => Err(FltkError::Unknown(String::from("Failed to undo"))),
                _ => Ok(()),
            }
        }
    }

    /// Sets whether the buffer can undo
    pub fn can_undo(&mut self, flag: bool) {
        unsafe { Fl_Text_Buffer_canUndo(self._inner, flag as i8) }
    }

    /// Loads a file into the buffer
    pub fn load_file(&mut self, path: &std::path::Path) -> Result<(), FltkError> {
        if !path.exists() {
            return Err(FltkError::Internal(FltkErrorKind::ResourceNotFound));
        }
        let path = path.to_str().unwrap();
        let path = CString::new(path)?;
        unsafe {
            match Fl_Text_Buffer_loadfile(self._inner, path.into_raw() as *const raw::c_char, 0) {
                0 => Err(FltkError::Internal(FltkErrorKind::ResourceNotFound)),
                _ => Ok(()),
            }
        }
    }

    /// Returns the tab distance for the buffer
    pub fn tab_distance(&self) -> u32 {
        unsafe { Fl_Text_Buffer_tab_distance(self._inner) as u32 }
    }

    /// Sets the tab distance
    pub fn set_tab_distance(&mut self, tab_dist: u32) {
        debug_assert!(
            tab_dist <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe { Fl_Text_Buffer_set_tab_distance(self._inner, tab_dist as i32) }
    }

    /// Selects the text from start to end
    pub fn select(&mut self, start: u32, end: u32) {
        debug_assert!(
            start <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        debug_assert!(
            end <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe { Fl_Text_Buffer_select(self._inner, start as i32, end as i32) }
    }

    /// Returns whether text is selected
    pub fn selected(&self) -> bool {
        unsafe {
            match Fl_Text_Buffer_selected(self._inner) {
                0 => false,
                _ => true,
            }
        }
    }

    /// Unselects text
    pub fn unselect(&mut self) {
        unsafe { Fl_Text_Buffer_unselect(self._inner) }
    }

    /// Returns the selection position
    pub fn selection_position(&mut self) -> Option<(u32, u32)> {
        unsafe {
            let start: *mut raw::c_int = std::ptr::null_mut();
            let end: *mut raw::c_int = std::ptr::null_mut();
            let ret = Fl_Text_Buffer_selection_position(self._inner, start, end);
            if ret != 0 {
                let x = (*start as u32, *end as u32);
                Some(x)
            } else {
                None
            }
        }
    }

    /// Returns the selection text
    pub fn selection_text(&mut self) -> String {
        unsafe {
            let x = Fl_Text_Buffer_selection_text(self._inner);
            assert!(!x.is_null(), "Null pointer exception!");
            CString::from_raw(x as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }

    /// Removes the selection
    pub fn remove_selection(&mut self) {
        unsafe { Fl_Text_Buffer_remove_selection(self._inner) }
    }

    /// Replaces selection
    pub fn replace_selection(&mut self, text: &str) {
        let text = CString::new(text).unwrap();
        unsafe {
            Fl_Text_Buffer_replace_selection(self._inner, text.into_raw() as *const raw::c_char)
        }
    }

    /// Highlights selection
    pub fn highlight(&mut self, start: u32, end: u32) {
        debug_assert!(
            start <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        debug_assert!(
            end <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe { Fl_Text_Buffer_highlight(self._inner, start as i32, end as i32) }
    }

    /// Returns whether text is highlighted
    pub fn is_highlighted(&mut self) -> bool {
        unsafe {
            match Fl_Text_Buffer_is_highlighted(self._inner) {
                0 => false,
                _ => true,
            }
        }
    }

    /// Unhighlights text
    pub fn unhighlight(&mut self) {
        unsafe { Fl_Text_Buffer_unhighlight(self._inner) }
    }

    /// Returns the highlight position
    pub fn highlight_position(&mut self) -> Option<(u32, u32)> {
        unsafe {
            let start: *mut raw::c_int = std::ptr::null_mut();
            let end: *mut raw::c_int = std::ptr::null_mut();
            let ret = Fl_Text_Buffer_highlight_position(self._inner, start, end);
            if ret != 0 {
                let x = (*start as u32, *end as u32);
                Some(x)
            } else {
                None
            }
        }
    }

    /// Returns the highlighted text
    pub fn highlight_text(&mut self) -> String {
        unsafe {
            let x = Fl_Text_Buffer_highlight_text(self._inner);
            assert!(!x.is_null(), "Null pointer exception!");
            CString::from_raw(x as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }

    /// Returns the line at pos
    pub fn line_text(&self, pos: u32) -> String {
        debug_assert!(
            pos <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe {
            let x = Fl_Text_Buffer_line_text(self._inner, pos as i32);
            assert!(!x.is_null(), "Null pointer exception!");
            CString::from_raw(x as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }

    /// Returns the index of the line's start position at pos
    pub fn line_start(&self, pos: u32) -> u32 {
        debug_assert!(
            pos <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe { Fl_Text_Buffer_line_start(self._inner, pos as i32) as u32 }
    }

    /// Returns the index of the first character of a word at pos
    pub fn word_start(&self, pos: u32) -> u32 {
        debug_assert!(
            pos <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe { Fl_Text_Buffer_word_start(self._inner, pos as i32) as u32 }
    }

    /// Returns the index of the last character of a word at pos
    pub fn word_end(&self, pos: u32) -> u32 {
        debug_assert!(
            pos <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe { Fl_Text_Buffer_word_end(self._inner, pos as i32) as u32 }
    }

    /// Counts the lines from start to end
    pub fn count_lines(&self, start: u32, end: u32) -> u32 {
        debug_assert!(
            start <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        debug_assert!(
            end <= std::i32::MAX as u32,
            "u32 entries must be < std::i32::MAX for compatibility!"
        );
        unsafe { Fl_Text_Buffer_count_lines(self._inner, start as i32, end as i32) as u32 }
    }

    /// Calls the modify callbacks
    pub fn call_modify_callbacks(&mut self) {
        unsafe { Fl_Text_Buffer_call_modify_callbacks(self._inner) }
    }

    /// Adds a modify callback
    pub fn add_modify_callback(
        &mut self,
        cb: Box<dyn FnMut(u32, u32, u32, u32, &str)>,
    ) {
        unsafe {
            unsafe extern "C" fn shim(
                pos: raw::c_int,
                inserted: raw::c_int,
                deleted: raw::c_int,
                restyled: raw::c_int,
                deleted_text: *const raw::c_char,
                data: *mut raw::c_void,
            ) {
                let mut temp = String::from("");
                if !deleted_text.is_null() {
                    temp = CStr::from_ptr(deleted_text).to_string_lossy().to_string();
                }
                let a: *mut Box<dyn FnMut(u32, u32, u32, u32, &str)> = mem::transmute(data);
                let f: &mut (dyn FnMut(u32, u32, u32, u32, &str)) = &mut **a;
                f(
                    pos as u32,
                    inserted as u32,
                    deleted as u32,
                    restyled as u32,
                    &temp,
                )
            }
            let a: *mut Box<dyn FnMut(u32, u32, u32, u32, &str)> = Box::into_raw(Box::new(cb));
            let data: *mut raw::c_void = mem::transmute(a);
            let callback: Fl_Text_Modify_Cb = Some(shim);
            Fl_Text_Buffer_add_modify_callback(self._inner, callback, data);
        }
    }

    /// Removes a modify callback
    pub fn remove_modify_callback(
        &mut self,
        cb: Box<dyn FnMut(u32, u32, u32, u32, &str)>,
    ) {
        unsafe {
            unsafe extern "C" fn shim(
                pos: raw::c_int,
                inserted: raw::c_int,
                deleted: raw::c_int,
                restyled: raw::c_int,
                deleted_text: *const raw::c_char,
                data: *mut raw::c_void,
            ) {
                let mut temp = String::from("");
                if !deleted_text.is_null() {
                    temp = CStr::from_ptr(deleted_text).to_string_lossy().to_string();
                }
                let a: *mut Box<dyn FnMut(u32, u32, u32, u32, &str)> = mem::transmute(data);
                let f: &mut (dyn FnMut(u32, u32, u32, u32, &str)) = &mut **a;
                f(
                    pos as u32,
                    inserted as u32,
                    deleted as u32,
                    restyled as u32,
                    &temp,
                )
            }
            let a: *mut Box<dyn FnMut(u32, u32, u32, u32, &str)> = Box::into_raw(Box::new(cb));
            let data: *mut raw::c_void = mem::transmute(a);
            let callback: Fl_Text_Modify_Cb = Some(shim);
            Fl_Text_Buffer_remove_modify_callback(self._inner, callback, data);
        }
    }
}

unsafe impl Sync for TextBuffer {}
unsafe impl Send for TextBuffer {}

impl Clone for TextBuffer {
    fn clone(&self) -> TextBuffer {
        let mut temp = TextBuffer::default();
        temp.copy(self, 0, 0, self.length());
        temp
    }
}

// impl Drop for TextBuffer {
//     fn drop(&mut self) {
//         unsafe { Fl_Text_Buffer_delete(self._inner) }
//     }
// }

/// Creates a non-editable text display widget
#[derive(WidgetExt, DisplayExt, Debug)]
pub struct TextDisplay {
    _inner: *mut Fl_Text_Display,
}

/// Creates an editable text display widget
#[derive(WidgetExt, DisplayExt, Debug)]
pub struct TextEditor {
    _inner: *mut Fl_Text_Editor,
}

/// Creates an editable text display widget
#[derive(WidgetExt, DisplayExt, Debug)]
pub struct SimpleTerminal {
    _inner: *mut Fl_Simple_Terminal,
}

#[derive(Debug, Clone, Copy)]
pub struct StyleTableEntry {
    pub color: Color,
    pub font: Font,
    pub size: u32,
}

impl TextEditor {
    /// Create an new TextEditor widget
    pub fn new(x: i32, y: i32, w: i32, h: i32, buf: &mut TextBuffer) -> TextEditor {
        let temp = CString::new("").unwrap();
        unsafe {
            let text_editor = Fl_Text_Editor_new(x, y, w, h, temp.into_raw() as *const raw::c_char);
            assert!(!text_editor.is_null(), "Failed to instantiate text editor!");
            let mut x = TextEditor {
                _inner: text_editor,
            };
            x.set_buffer(buf);
            x
        }
    }
    /// Creates a default and zero initialized TextEditor
    pub fn default(buf: &mut TextBuffer) -> TextEditor {
        let temp = CString::new("").unwrap();
        unsafe {
            let text_editor = Fl_Text_Editor_new(0, 0, 0, 0, temp.into_raw() as *const raw::c_char);
            assert!(!text_editor.is_null(), "Failed to instantiate text editor!");
            let mut x = TextEditor {
                _inner: text_editor,
            };
            x.set_buffer(buf);
            x
        }
    }
    /// Copies the text within the TextEditor widget
    pub fn copy(&self) {
        unsafe {
            kf_copy(self._inner);
        }
    }
    /// Cuts the text within the TextEditor widget
    pub fn cut(&self) {
        unsafe {
            kf_cut(self._inner);
        }
    }
    /// Pastes text from the clipboard into the TextEditor widget
    pub fn paste(&self) {
        unsafe {
            kf_paste(self._inner);
        }
    }
    /// Undo changes in the TextEditor widget
    pub fn undo(&self) {
        unsafe {
            kf_undo(self._inner);
        }
    }
}

impl TextDisplay {
    /// Create an new TextDisplay widget
    pub fn new(x: i32, y: i32, w: i32, h: i32, buf: &mut TextBuffer) -> TextDisplay {
        let temp = CString::new("").unwrap();
        unsafe {
            let text_display =
                Fl_Text_Display_new(x, y, w, h, temp.into_raw() as *const raw::c_char);
            assert!(
                !text_display.is_null(),
                "Failed to instantiate text display!"
            );
            let mut x = TextDisplay {
                _inner: text_display,
            };
            x.set_buffer(buf);
            x
        }
    }
    /// Creates a default and zero initialized TextDisplay
    pub fn default(buf: &mut TextBuffer) -> TextDisplay {
        let temp = CString::new("").unwrap();
        unsafe {
            let text_display =
                Fl_Text_Display_new(0, 0, 0, 0, temp.into_raw() as *const raw::c_char);
            assert!(
                !text_display.is_null(),
                "Failed to instantiate text display!"
            );
            let mut x = TextDisplay {
                _inner: text_display,
            };
            x.set_buffer(buf);
            x
        }
    }
}

impl SimpleTerminal {
    /// Create an new SimpleTerminal widget
    pub fn new(x: i32, y: i32, w: i32, h: i32, buf: &mut TextBuffer) -> SimpleTerminal {
        let temp = CString::new("").unwrap();
        unsafe {
            let simple_terminal =
                Fl_Simple_Terminal_new(x, y, w, h, temp.into_raw() as *const raw::c_char);
            assert!(
                !simple_terminal.is_null(),
                "Failed to instantiate simple terminal!"
            );
            let mut x = SimpleTerminal {
                _inner: simple_terminal,
            };
            x.set_buffer(buf);
            x
        }
    }
    /// Creates a default and zero initialized SimpleTerminal
    pub fn default(buf: &mut TextBuffer) -> SimpleTerminal {
        let temp = CString::new("").unwrap();
        unsafe {
            let simple_terminal =
                Fl_Simple_Terminal_new(0, 0, 0, 0, temp.into_raw() as *const raw::c_char);
            assert!(
                !simple_terminal.is_null(),
                "Failed to instantiate simple terminal!"
            );
            let mut x = SimpleTerminal {
                _inner: simple_terminal,
            };
            x.set_buffer(buf);
            x
        }
    }
}

#[cfg(test)]
mod editor {
    #[test]
    fn buffer() {}
}