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
use crate::enums::{Align, CallbackTrigger, Color, Damage, Event, Font, FrameType, Key, LabelType};
use crate::image::Image;
use crate::prelude::*;
use crate::utils::FlString;
use fltk_sys::text::*;
use std::{
    ffi::{CStr, CString},
    mem,
    os::raw,
    sync::atomic::{AtomicUsize, Ordering},
};

/// Defines the text cursor styles supported by fltk
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Cursor {
    /// Normal
    Normal,
    /// Caret
    Caret,
    /// Dim
    Dim,
    /// Block
    Block,
    /// Heavy
    Heavy,
    /// Simple
    Simple,
}

/// 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,
    refcount: AtomicUsize,
}

impl TextBuffer {
    /// Initialized a default text buffer
    pub fn default() -> TextBuffer {
        unsafe {
            let text_buffer = Fl_Text_Buffer_new();
            assert!(!text_buffer.is_null());
            TextBuffer {
                inner: text_buffer,
                refcount: AtomicUsize::new(2),
            }
        }
    }

    /// Deletes the `TextBuffer`
    /// # Safety
    /// The buffer shouldn't be deleted while the Display widget still needs it
    pub unsafe fn delete(mut buf: Self) {
        Fl_Text_Buffer_delete(buf.inner);
        buf.inner = std::ptr::null_mut::<Fl_Text_Buffer>();
    }

    /// Deletes the `TextBuffer`
    /// # Safety
    /// The buffer shouldn't be deleted while the Display widget still needs it
    pub unsafe fn delete_buffer(mut buf: TextBuffer) {
        Fl_Text_Buffer_delete(buf.inner);
        buf.inner = std::ptr::null_mut::<Fl_Text_Buffer>();
    }

    /// Initialized a text buffer from a pointer
    /// # Safety
    /// The pointer must be valid
    pub unsafe fn from_ptr(ptr: *mut Fl_Text_Buffer) -> Self {
        assert!(!ptr.is_null());
        TextBuffer {
            inner: ptr,
            refcount: AtomicUsize::new(2),
        }
    }

    /// Returns the inner pointer from a text buffer
    /// # Safety
    /// Can return multiple mutable pointers to the same buffer
    pub unsafe fn as_ptr(&self) -> *mut Fl_Text_Buffer {
        self.inner
    }

    /// Sets the text of the buffer
    pub fn set_text(&mut self, txt: &str) {
        assert!(!self.inner.is_null());
        unsafe {
            let txt = CString::safe_new(txt);
            Fl_Text_Buffer_set_text(self.inner, txt.as_ptr())
        }
    }

    /// Returns the text of the buffer
    pub fn text(&self) -> String {
        assert!(!self.inner.is_null());
        unsafe {
            let text = Fl_Text_Buffer_text(self.inner);
            assert!(!text.is_null());
            CStr::from_ptr(text as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }

    /**
        Appends to the buffer.
        To append and scroll to the end of the buffer:
        ```rust,no_run
        use fltk::{prelude::*, *};
        let txt = "Some long text!";
        let buf = text::TextBuffer::default();
        let mut disp = text::TextDisplay::default();
        disp.set_buffer(Some(buf));
        disp.buffer().unwrap().append(txt);
        disp.set_insert_position(disp.buffer().unwrap().length());
        disp.scroll(
            disp.count_lines(0, disp.buffer().unwrap().length(), true),
            0,
        );
        ```
    */
    pub fn append(&mut self, text: &str) {
        assert!(!self.inner.is_null());
        let text = CString::safe_new(text);
        unsafe { Fl_Text_Buffer_append(self.inner, text.as_ptr()) }
    }

    /// Get the length of the buffer
    pub fn length(&self) -> i32 {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_length(self.inner) as i32 }
    }

    /// Removes from the buffer
    pub fn remove(&mut self, start: i32, end: i32) {
        assert!(!self.inner.is_null());
        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: i32, end: i32) -> Option<String> {
        assert!(!self.inner.is_null());
        unsafe {
            let x = Fl_Text_Buffer_text_range(self.inner, start as i32, end as i32);
            if x.is_null() {
                None
            } else {
                Some(
                    CStr::from_ptr(x as *mut raw::c_char)
                        .to_string_lossy()
                        .to_string(),
                )
            }
        }
    }

    /// Inserts text into a position
    pub fn insert(&mut self, pos: i32, text: &str) {
        assert!(!self.inner.is_null());
        let text = CString::safe_new(text);
        unsafe { Fl_Text_Buffer_insert(self.inner, pos as i32, text.as_ptr()) }
    }

    /// Replaces text from position `start` to `end`
    pub fn replace(&mut self, start: i32, end: i32, text: &str) {
        assert!(!self.inner.is_null());
        let text = CString::safe_new(text);
        unsafe { Fl_Text_Buffer_replace(self.inner, start as i32, end as i32, text.as_ptr()) }
    }

    /// Copies text from a source buffer into the current buffer
    pub fn copy_from(&mut self, source_buf: &TextBuffer, start: i32, end: i32, to: i32) {
        assert!(!self.inner.is_null());
        unsafe {
            Fl_Text_Buffer_copy(
                self.inner,
                source_buf.as_ptr(),
                start as i32,
                end as i32,
                to as i32,
            )
        }
    }

    /// Copies whole text from a source buffer into a new buffer
    pub fn copy(&self) -> TextBuffer {
        assert!(!self.inner.is_null());
        let mut temp = TextBuffer::default();
        temp.copy_from(self, 0, 0, self.length());
        temp
    }

    /// Performs an undo operation on the buffer
    /// # Errors
    /// Errors on failure to undo
    pub fn undo(&mut self) -> Result<(), FltkError> {
        assert!(!self.inner.is_null());
        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) {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_canUndo(self.inner, flag as raw::c_char) }
    }

    /// Loads a file into the buffer
    /// # Errors
    /// Errors on failure to load file
    pub fn load_file<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), FltkError> {
        assert!(!self.inner.is_null());
        if !path.as_ref().exists() {
            return Err(FltkError::Internal(FltkErrorKind::ResourceNotFound));
        }
        let path = path
            .as_ref()
            .to_str()
            .ok_or_else(|| FltkError::Unknown(String::from("Failed to convert path to string")))?;
        let path = CString::new(path)?;
        unsafe {
            match Fl_Text_Buffer_load_file(self.inner, path.as_ptr()) {
                0 => Ok(()),
                _ => Err(FltkError::Internal(FltkErrorKind::ResourceNotFound)),
            }
        }
    }

    /// Saves a buffer into a file
    /// # Errors
    /// Errors on failure to save file
    pub fn save_file<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), FltkError> {
        assert!(!self.inner.is_null());
        let path = path
            .as_ref()
            .to_str()
            .ok_or_else(|| FltkError::Unknown(String::from("Failed to convert path to string")))?;
        let path = CString::new(path)?;
        unsafe {
            match Fl_Text_Buffer_save_file(self.inner, path.as_ptr()) {
                0 => Ok(()),
                _ => Err(FltkError::Internal(FltkErrorKind::ResourceNotFound)),
            }
        }
    }

    /// Returns the tab distance for the buffer
    pub fn tab_distance(&self) -> i32 {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_tab_distance(self.inner) as i32 }
    }

    /// Sets the tab distance
    pub fn set_tab_distance(&mut self, tab_dist: i32) {
        assert!(!self.inner.is_null());
        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: i32, end: i32) {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_select(self.inner, start as i32, end as i32) }
    }

    /// Returns whether text is selected
    pub fn selected(&self) -> bool {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_selected(self.inner) != 0 }
    }

    /// Unselects text
    pub fn unselect(&mut self) {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_unselect(self.inner) }
    }

    /// Returns the selection position
    pub fn selection_position(&mut self) -> Option<(i32, i32)> {
        assert!(!self.inner.is_null());
        unsafe {
            let mut start = 0;
            let mut end = 0;
            let ret = Fl_Text_Buffer_selection_position(self.inner, &mut start as _, &mut end as _);
            if ret == 0 {
                None
            } else {
                let x = (start as i32, end as i32);
                Some(x)
            }
        }
    }

    /// Returns the selection text
    pub fn selection_text(&mut self) -> String {
        assert!(!self.inner.is_null());
        unsafe {
            let x = Fl_Text_Buffer_selection_text(self.inner);
            assert!(!x.is_null());
            CStr::from_ptr(x as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }

    /// Removes the selection
    pub fn remove_selection(&mut self) {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_remove_selection(self.inner) }
    }

    /// Replaces selection
    pub fn replace_selection(&mut self, text: &str) {
        assert!(!self.inner.is_null());
        let text = CString::safe_new(text);
        unsafe { Fl_Text_Buffer_replace_selection(self.inner, text.as_ptr()) }
    }

    /// Highlights selection
    pub fn highlight(&mut self, start: i32, end: i32) {
        assert!(!self.inner.is_null());
        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 {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_is_highlighted(self.inner) != 0 }
    }

    /// Unhighlights text
    pub fn unhighlight(&mut self) {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_unhighlight(self.inner) }
    }

    /// Returns the highlight position
    pub fn highlight_position(&mut self) -> Option<(i32, i32)> {
        assert!(!self.inner.is_null());
        unsafe {
            let mut start = 0;
            let mut end = 0;
            let ret = Fl_Text_Buffer_highlight_position(self.inner, &mut start as _, &mut end as _);
            if ret == 0 {
                None
            } else {
                let x = (start as i32, end as i32);
                Some(x)
            }
        }
    }

    /// Returns the highlighted text
    pub fn highlight_text(&mut self) -> String {
        assert!(!self.inner.is_null());
        unsafe {
            let x = Fl_Text_Buffer_highlight_text(self.inner);
            assert!(!x.is_null());
            CStr::from_ptr(x as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }

    /// Returns the line at pos
    pub fn line_text(&self, pos: i32) -> String {
        assert!(!self.inner.is_null());
        unsafe {
            let x = Fl_Text_Buffer_line_text(self.inner, pos as i32);
            assert!(!x.is_null());
            CStr::from_ptr(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: i32) -> i32 {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_line_start(self.inner, pos as i32) as i32 }
    }

    /// Returns the index of the first character of a word at pos
    pub fn word_start(&self, pos: i32) -> i32 {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_word_start(self.inner, pos as i32) as i32 }
    }

    /// Returns the index of the last character of a word at pos
    pub fn word_end(&self, pos: i32) -> i32 {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_word_end(self.inner, pos as i32) as i32 }
    }

    /// Counts the lines from start to end
    pub fn count_lines(&self, start: i32, end: i32) -> i32 {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_count_lines(self.inner, start as i32, end as i32) as i32 }
    }

    /// Calls the modify callbacks
    pub fn call_modify_callbacks(&mut self) {
        assert!(!self.inner.is_null());
        unsafe { Fl_Text_Buffer_call_modify_callbacks(self.inner) }
    }

    /// Adds a modify callback.
    /// callback args:
    /// pos: i32, inserted items: i32, deleted items: i32, restyled items: i32, `deleted_text`
    pub fn add_modify_callback<F: FnMut(i32, i32, i32, i32, &str) + 'static>(&mut self, cb: F) {
        assert!(!self.inner.is_null());
        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 temp = if deleted_text.is_null() {
                    String::from("")
                } else {
                    CStr::from_ptr(deleted_text).to_string_lossy().to_string()
                };
                let a: *mut Box<dyn FnMut(i32, i32, i32, i32, &str)> =
                    data as *mut Box<dyn for<'r> FnMut(i32, i32, i32, i32, &'r str)>;
                let f: &mut (dyn FnMut(i32, i32, i32, i32, &str)) = &mut **a;
                let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    f(
                        pos as i32,
                        inserted as i32,
                        deleted as i32,
                        restyled as i32,
                        &temp,
                    )
                }));
            }
            let a: *mut Box<dyn FnMut(i32, i32, i32, i32, &str)> =
                Box::into_raw(Box::new(Box::new(cb)));
            let data: *mut raw::c_void = a as *mut std::ffi::c_void;
            let callback: Fl_Text_Modify_Cb = Some(shim);
            Fl_Text_Buffer_add_modify_callback(self.inner, callback, data);
        }
    }

    /// Removes a modify callback.
    /// callback args:
    /// pos: i32, inserted items: i32, deleted items: i32, restyled items: i32, `deleted_text`
    pub fn remove_modify_callback<F: FnMut(i32, i32, i32, i32, &str) + 'static>(&mut self, cb: F) {
        assert!(!self.inner.is_null());
        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 temp = if deleted_text.is_null() {
                    String::from("")
                } else {
                    CStr::from_ptr(deleted_text).to_string_lossy().to_string()
                };
                let a: *mut Box<dyn FnMut(i32, i32, i32, i32, &str)> =
                    data as *mut Box<dyn for<'r> FnMut(i32, i32, i32, i32, &'r str)>;
                let f: &mut (dyn FnMut(i32, i32, i32, i32, &str)) = &mut **a;
                let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    f(
                        pos as i32,
                        inserted as i32,
                        deleted as i32,
                        restyled as i32,
                        &temp,
                    )
                }));
            }
            let a: *mut Box<dyn FnMut(i32, i32, i32, i32, &str)> =
                Box::into_raw(Box::new(Box::new(cb)));
            let data: *mut raw::c_void = a as *mut std::ffi::c_void;
            let callback: Fl_Text_Modify_Cb = Some(shim);
            Fl_Text_Buffer_remove_modify_callback(self.inner, callback, data);
        }
    }

    /// Forward search for a string
    pub fn search_forward(
        &self,
        start_pos: i32,
        search_string: &str,
        match_case: bool,
    ) -> Option<i32> {
        unsafe {
            let search_string = CString::safe_new(search_string);
            let mut found_pos = 0;
            let ret = Fl_Text_Buffer_search_forward(
                self.inner,
                start_pos,
                search_string.as_ptr() as _,
                &mut found_pos as _,
                match_case as _,
            );
            if ret == 0 {
                None
            } else {
                Some(found_pos)
            }
        }
    }

    /// Backward search for a string
    pub fn search_backward(
        &self,
        start_pos: i32,
        search_string: &str,
        match_case: bool,
    ) -> Option<i32> {
        unsafe {
            let search_string = CString::safe_new(search_string);
            let mut found_pos = 0;
            let ret = Fl_Text_Buffer_search_backward(
                self.inner,
                start_pos,
                search_string.as_ptr() as _,
                &mut found_pos as _,
                match_case as _,
            );
            if ret == 0 {
                None
            } else {
                Some(found_pos)
            }
        }
    }

    /// Forward search for a char
    pub fn find_char_forward(&self, start_pos: i32, search_char: char) -> Option<i32> {
        unsafe {
            let mut found_pos = 0;
            let ret = Fl_Text_Buffer_findchar_forward(
                self.inner,
                start_pos,
                search_char as _,
                &mut found_pos as _,
            );
            if ret == 0 {
                None
            } else {
                Some(found_pos)
            }
        }
    }

    /// Backward search for a char
    pub fn find_char_backward(&self, start_pos: i32, search_char: char) -> Option<i32> {
        unsafe {
            let mut found_pos = 0;
            let ret = Fl_Text_Buffer_findchar_backward(
                self.inner,
                start_pos,
                search_char as _,
                &mut found_pos as _,
            );
            if ret == 0 {
                None
            } else {
                Some(found_pos)
            }
        }
    }
}

unsafe impl Sync for TextBuffer {}

unsafe impl Send for TextBuffer {}

impl PartialEq for TextBuffer {
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl Eq for TextBuffer {}

impl Clone for TextBuffer {
    fn clone(&self) -> TextBuffer {
        assert!(!self.inner.is_null());
        let x = self.refcount.fetch_add(1, Ordering::Relaxed);
        TextBuffer {
            inner: self.inner,
            refcount: AtomicUsize::new(x),
        }
    }
}

impl Drop for TextBuffer {
    fn drop(&mut self) {
        assert!(!self.inner.is_null());
        self.refcount.fetch_sub(1, Ordering::Relaxed);
        if *self.refcount.get_mut() < 1 {
            unsafe {
                Fl_Text_Buffer_delete(self.inner);
            }
            self.inner = std::ptr::null_mut();
        }
    }
}

/// Defines wrap modes
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum WrapMode {
    /// No wrapping
    None,
    /// Wrap text at certain column
    AtColumn,
    /// Wrap text at certain pixel
    AtPixel,
    /// Wrap text at certain bounds
    AtBounds,
}

/// Defines drag types
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum DragType {
    /// No dragging
    None = -2,
    /// Drag Start "drag n drop" event
    StartDnd = -1,
    /// Drag single character
    Char = 0,
    /// Drag single word
    Word = 1,
    /// Drag single line
    Line = 2,
}

/// Creates a non-editable text display widget
#[derive(WidgetBase, WidgetExt, DisplayExt, Debug)]
pub struct TextDisplay {
    inner: *mut Fl_Text_Display,
    tracker: *mut fltk_sys::fl::Fl_Widget_Tracker,
    is_derived: bool,
}

/// Creates an editable text display widget
#[derive(WidgetBase, WidgetExt, DisplayExt, Debug)]
pub struct TextEditor {
    inner: *mut Fl_Text_Editor,
    tracker: *mut fltk_sys::fl::Fl_Widget_Tracker,
    is_derived: bool,
}

/// Creates an editable text display widget to handle terminal-like behavior, such as
/// logging events or debug information.
/// `SimpleTerminal` already has an internal buffer.
/// It is NOT is a full terminal emulator; it does NOT
/// handle stdio redirection, pipes, pseudo ttys, termio character cooking,
/// keyboard input processing, screen addressing, random cursor positioning,
/// curses compatibility, or VT100/xterm emulation.
#[derive(WidgetBase, WidgetExt, DisplayExt, Debug)]
pub struct SimpleTerminal {
    inner: *mut Fl_Simple_Terminal,
    tracker: *mut fltk_sys::fl::Fl_Widget_Tracker,
    is_derived: bool,
}

/// Defines the styles used in the `set_highlight_data`, which is used with style buffers
#[derive(Debug, Clone, Copy)]
pub struct StyleTableEntry {
    /// Font color
    pub color: Color,
    /// Font type
    pub font: Font,
    /// Font size
    pub size: i32,
}

impl TextEditor {
    /// Set to insert mode
    pub fn set_insert_mode(&mut self, b: bool) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Text_Editor_set_insert_mode(self.inner, b as i32) }
    }

    /// Returns whether insert mode is set
    pub fn insert_mode(&self) -> bool {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Text_Editor_insert_mode(self.inner) != 0 }
    }

    /// Set tab navigation
    pub fn set_tab_nav(&mut self, val: bool) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Text_Editor_set_tab_nav(self.inner, val as i32) }
    }

    /// Returns whether tab navigation is set
    pub fn tab_nav(&self) -> bool {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Text_Editor_tab_nav(self.inner) != 0 }
    }

    /// Copies the text within the `TextEditor` widget
    pub fn copy(&self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_copy(self.inner);
        }
    }

    /// Cuts the text within the `TextEditor` widget
    pub fn cut(&self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_cut(self.inner);
        }
    }

    /// Pastes text from the clipboard into the `TextEditor` widget
    pub fn paste(&self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_paste(self.inner);
        }
    }

    /// Undo changes in the `TextEditor` widget
    pub fn undo(&self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_undo(self.inner);
        }
    }

    /// Inserts the text associated with key 'c'
    pub fn kf_default(&mut self, c: Key) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_default(c.bits() as i32, self.inner);
        }
    }

    /// Ignores the key 'c' in editor
    pub fn kf_ignore(&mut self, c: Key) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_ignore(c.bits() as i32, self.inner);
        }
    }

    /// Does a backspace
    pub fn kf_backspace(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_backspace(self.inner);
        }
    }

    /// Inserts a new line
    pub fn kf_enter(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_enter(self.inner);
        }
    }

    /// Moves the cursor in the direction indicated by the key
    pub fn kf_move(&mut self, c: Key) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_move(c.bits() as i32, self.inner);
        }
    }

    /// Extends the current selection in the direction of key 'c'
    pub fn kf_shift_move(&mut self, c: Key) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_shift_move(c.bits() as i32, self.inner);
        }
    }

    /// Moves the current text cursor in the direction indicated by control key 'c'
    pub fn kf_ctrl_move(&mut self, c: Key) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_ctrl_move(c.bits() as i32, self.inner);
        }
    }

    /// Extends the current selection in the direction indicated by control key 'c'
    pub fn kf_c_s_move(&mut self, c: Key) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_c_s_move(c.bits() as i32, self.inner);
        }
    }

    /// Moves the current text cursor in the direction indicated by meta key 'c'
    pub fn kf_meta_move(&mut self, c: Key) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_meta_move(c.bits() as i32, self.inner);
        }
    }

    /// Extends the current selection in the direction indicated by meta key 'c'
    pub fn kf_m_s_move(&mut self, c: Key) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_m_s_move(c.bits() as i32, self.inner);
        }
    }

    /// Moves the text cursor to the beginning of the current line
    pub fn kf_home(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_home(self.inner);
        }
    }

    /// Moves the text cursor to the end of the current line
    pub fn kf_end(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_end(self.inner);
        }
    }

    /// Moves the text cursor one character to the left
    pub fn kf_left(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_left(self.inner);
        }
    }

    /// Moves the text cursor one line up
    pub fn kf_up(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_up(self.inner);
        }
    }

    /// Moves the text cursor one character to the right
    pub fn kf_right(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_right(self.inner);
        }
    }

    /// Moves the text cursor one line down
    pub fn kf_down(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_down(self.inner);
        }
    }

    /// Moves the text cursor up one page
    pub fn kf_page_up(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_page_up(self.inner);
        }
    }

    /// Moves the text cursor down one page
    pub fn kf_page_down(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_page_down(self.inner);
        }
    }

    /// Toggles the insert mode for the editor
    pub fn kf_insert(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_insert(self.inner);
        }
    }

    /// Does a delete of selected text or the current character in the current buffer
    pub fn kf_delete(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_delete(self.inner);
        }
    }

    /// Selects all text in the associated buffer
    pub fn kf_select_all(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            Fl_Text_Editor_kf_select_all(self.inner);
        }
    }
}

impl SimpleTerminal {
    /// Sets whether the terminal automatically stays at the bottom
    pub fn set_stay_at_bottom(&mut self, arg1: bool) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Simple_Terminal_set_stay_at_bottom(self.inner, arg1 as i32) }
    }

    /// Returns whether the terminal automatically stays at the bottom
    pub fn stay_at_bottom(&self) -> bool {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Simple_Terminal_stay_at_bottom(self.inner) != 0 }
    }

    /// Sets the max lines allowed in history
    pub fn set_history_lines(&mut self, arg1: i32) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Simple_Terminal_set_history_lines(self.inner, arg1 as i32) }
    }

    /// Gets the max lines allowed in history
    pub fn history_lines(&self) -> i32 {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Simple_Terminal_history_lines(self.inner) as i32 }
    }

    /// Enables ANSI sequences within the text to control text colors
    pub fn set_ansi(&mut self, val: bool) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Simple_Terminal_set_ansi(self.inner, val as i32) }
    }

    /// Returns whether ANSI sequences are enabled
    pub fn ansi(&self) -> bool {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Simple_Terminal_ansi(self.inner) != 0 }
    }

    /// Appends text to the terminal buffer
    pub fn append(&mut self, s: &str) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        let s = CString::safe_new(s);
        unsafe { Fl_Simple_Terminal_append(self.inner, s.into_raw()) }
    }

    /// Sets the text of the terminal buffer
    pub fn set_text(&mut self, s: &str) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        let s = CString::safe_new(s);
        unsafe { Fl_Simple_Terminal_set_text(self.inner, s.into_raw()) }
    }

    /// Gets the text of the terminal buffer
    pub fn text(&self) -> String {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe {
            let ptr = Fl_Simple_Terminal_text(self.inner);
            assert!(!ptr.is_null());
            CStr::from_ptr(ptr as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }

    /// Clears the terminal
    pub fn clear(&mut self) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Simple_Terminal_clear(self.inner) }
    }

    /// Removes `count` lines from `start`
    pub fn remove_lines(&mut self, start: i32, count: i32) {
        assert!(!self.was_deleted());
        assert!(self.buffer().is_some());
        unsafe { Fl_Simple_Terminal_remove_lines(self.inner, start as i32, count as i32) }
    }
}