1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
use crate::enums::{Event, Font, FrameType, Key, Mode, Shortcut};
use crate::prelude::*;
use crate::utils::FlString;
use crate::window::Window;
use fltk_sys::fl;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::{
    any, cmp,
    ffi::{CStr, CString},
    marker, mem,
    os::raw,
    panic, path, ptr,
    sync::{
        atomic::{AtomicBool, Ordering},
        Mutex,
    },
    thread, time,
};

/// Alias Widget ptr
pub type WidgetPtr = *mut fltk_sys::widget::Fl_Widget;

/// Alias Window ptr
pub type WindowPtr = *mut fltk_sys::window::Fl_Window;

lazy_static! {
    /// The currently chosen font
    static ref CURRENT_FONT: Mutex<i32> = Mutex::new(0);

    /// The currently chosen frame type
    static ref CURRENT_FRAME: Mutex<i32> = Mutex::new(2);

    /// Currently loaded fonts
    static ref LOADED_FONT: Option<&'static str> = None;

    /// Basically a check for global locking
    static ref IS_INIT: AtomicBool = AtomicBool::new(false);

    /// The fonts associated with the application
    pub(crate) static ref FONTS: Mutex<Vec<String>> = Mutex::new(Vec::new());
}

/// Runs the event loop
/// # Errors
/// Returns `FailedToRun`, this is fatal to the app
pub fn run() -> Result<(), FltkError> {
    unsafe {
        if !IS_INIT.load(Ordering::Relaxed) {
            init_all();
        }
        match fl::Fl_run() {
            0 => Ok(()),
            _ => Err(FltkError::Internal(FltkErrorKind::FailedToRun)),
        }
    }
}

/// Locks the main UI thread
/// # Errors
/// Returns `FailedToLock` if locking is unsopported. This is fatal to the app
pub fn lock() -> Result<(), FltkError> {
    unsafe {
        match fl::Fl_lock() {
            0 => Ok(()),
            _ => Err(FltkError::Internal(FltkErrorKind::FailedToLock)),
        }
    }
}

/// Set the app scheme
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Scheme {
    /// Base fltk scheming
    Base,
    /// inspired by the Aqua user interface on Mac OS X
    Plastic,
    /// inspired by the GTK+ theme
    Gtk,
    /// inspired by the Clearlooks Glossy scheme
    Gleam,
}

/// sets the scheme of the application
pub fn set_scheme(scheme: Scheme) {
    let name_str = match scheme {
        Scheme::Base => "base",
        Scheme::Gtk => "gtk+",
        Scheme::Gleam => "gleam",
        Scheme::Plastic => "plastic",
    };
    let name_str = CString::safe_new(name_str);
    unsafe { fl::Fl_set_scheme(name_str.as_ptr()) }
}

/// Gets the scheme of the application
pub fn scheme() -> Scheme {
    unsafe {
        use Scheme::{Base, Gleam, Gtk, Plastic};
        match fl::Fl_scheme() {
            0 => Base,
            1 => Gtk,
            2 => Gleam,
            3 => Plastic,
            _ => unreachable!(),
        }
    }
}

/// Alias Scheme to `AppScheme`
pub type AppScheme = Scheme;

/// Unlocks the main UI thread
pub fn unlock() {
    unsafe {
        fl::Fl_unlock();
    }
}

/// Registers a function that will be called by the main thread during the next message handling cycle
pub fn awake_callback<F: FnMut() + 'static>(cb: F) {
    unsafe {
        unsafe extern "C" fn shim(data: *mut raw::c_void) {
            let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
            let f: &mut (dyn FnMut()) = &mut **a;
            let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
        }
        let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
        let data: *mut raw::c_void = a as *mut raw::c_void;
        let callback: fl::Fl_Awake_Handler = Some(shim);
        fl::Fl_awake_callback(callback, data);
    }
}

/// Trigger event loop handling in the main thread
pub fn awake() {
    unsafe { fl::Fl_awake() }
}

/// Basic Application struct, used to instatiate, set the scheme and run the event loop
#[derive(Debug, Copy, Clone)]
pub struct App {}

impl App {
    /// Instantiates an App type
    pub fn default() -> App {
        init_all();
        App {}
    }

    /// Sets the scheme of the application
    pub fn set_scheme(&mut self, scheme: Scheme) {
        set_scheme(scheme);
    }

    /// Sets the scheme of the application
    pub fn with_scheme(self, scheme: Scheme) -> App {
        set_scheme(scheme);
        self
    }

    /// Gets the scheme of the application

    pub fn scheme(self) -> Scheme {
        scheme()
    }

    /// Runs the event loop
    /// # Errors
    /// Can error on failure to run the application
    pub fn run(self) -> Result<(), FltkError> {
        run()
    }

    /// Wait for incoming messages.
    /// Calls to redraw within wait require an explicit sleep
    pub fn wait(self) -> bool {
        wait()
    }

    /// Loads system fonts

    pub fn load_system_fonts(self) -> Self {
        *FONTS.lock().unwrap() = get_font_names();
        self
    }

    /**
        Loads a font from a path.
        On success, returns a String with the ttf Font Family name. The font's index is always 16.
        As such only one font can be loaded at a time.
        The font name can be used with `Font::by_name`, and index with `Font::by_index`.
        # Examples
        ```rust,no_run
        use fltk::{prelude::*, *};
        let app = app::App::default();
        let font = app.load_font("font.ttf").unwrap();
        let mut frame = frame::Frame::new(0, 0, 400, 100, "Hello");
        frame.set_label_font(enums::Font::by_name(&font));
        ```
        # Errors
        Returns `ResourceNotFound` if the Font file was not found
    */
    pub fn load_font<P: AsRef<path::Path>>(self, path: P) -> Result<String, FltkError> {
        Self::load_font_(path.as_ref())
    }

    fn load_font_(path: &path::Path) -> Result<String, FltkError> {
        if !path.exists() {
            return Err::<String, FltkError>(FltkError::Internal(FltkErrorKind::ResourceNotFound));
        }
        if let Some(p) = path.to_str() {
            let name = load_font(p)?;
            Ok(name)
        } else {
            Err(FltkError::Internal(FltkErrorKind::ResourceNotFound))
        }
    }

    /// Set the visual of the application
    /// # Errors
    /// Returns `FailedOperation` if FLTK failed to set the visual mode
    pub fn set_visual(self, mode: Mode) -> Result<(), FltkError> {
        set_visual(mode)
    }

    /// Redraws the app
    pub fn redraw(self) {
        redraw()
    }

    /// Quit the application
    pub fn quit(self) {
        quit()
    }
}

/// Set the application's scrollbar size
pub fn set_scrollbar_size(sz: i32) {
    unsafe { fl::Fl_set_scrollbar_size(sz as i32) }
}

/// Get the app's scrollbar size
pub fn scrollbar_size() -> i32 {
    unsafe { fl::Fl_scrollbar_size() as i32 }
}

/// Get the grabbed window
pub fn grab() -> Option<impl WindowExt> {
    unsafe {
        let ptr = fl::Fl_grab();
        if ptr.is_null() {
            None
        } else {
            Some(crate::window::Window::from_widget_ptr(ptr as *mut _))
        }
    }
}

/// Set the current grab
pub fn set_grab<W: WindowExt>(win: Option<W>) {
    unsafe {
        win.map_or_else(
            || fl::Fl_set_grab(ptr::null_mut()),
            |w| fl::Fl_set_grab(w.as_widget_ptr() as *mut _),
        )
    }
}

/// Returns the latest captured event
pub fn event() -> Event {
    unsafe {
        mem::transmute(fl::Fl_event())
    }
}

/// Returns the presed key
pub fn event_key() -> Key {
    unsafe {
        mem::transmute(fl::Fl_event_key())
    }
}

/// Returns the original key
pub fn event_original_key() -> Key {
    unsafe {
        mem::transmute(fl::Fl_event_original_key())
    }
}

/// Returns whether the  key is pressed or held down during the last event
pub fn event_key_down(key: Key) -> bool {
    unsafe { fl::Fl_event_key_down(mem::transmute(key)) != 0 }
}

/// Returns a textual representation of the latest event
pub fn event_text() -> String {
    unsafe {
        let text = fl::Fl_event_text();
        if text.is_null() {
            String::from("")
        } else {
            CStr::from_ptr(text as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }
}

/// Returns the captured button event.
/// 1 for left key, 2 for middle, 3 for right
pub fn event_button() -> i32 {
    unsafe { fl::Fl_event_button() }
}

/// Defines Mouse buttons
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq)]
#[non_exhaustive]
pub enum MouseButton {
    /// Left mouse button
    Left = 1,
    /// Middle mouse button
    Middle = 2,
    /// Right mouse button
    Right = 3,
}

/// Returns the captured button event
pub fn event_mouse_button() -> MouseButton {
    unsafe { mem::transmute(fl::Fl_event_button()) }
}

/// Returns the number of clicks
pub fn event_clicks() -> bool {
    unsafe { fl::Fl_event_clicks() != 0 }
}

/// Gets the x coordinate of the mouse in the window
pub fn event_x() -> i32 {
    unsafe { fl::Fl_event_x() }
}

/// Gets the y coordinate of the mouse in the window
pub fn event_y() -> i32 {
    unsafe { fl::Fl_event_y() }
}

/// Gets the x coordinate of the mouse in the screen
pub fn event_x_root() -> i32 {
    unsafe { fl::Fl_event_x_root() }
}

/// Gets the y coordinate of the mouse in the screen
pub fn event_y_root() -> i32 {
    unsafe { fl::Fl_event_y_root() }
}

/// Event direction with Mousewheel event
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MouseWheel {
    /// No movement
    None,
    /// Right movement
    Right,
    /// Left movement
    Left,
    /// Up movement
    Up,
    /// Down movement
    Down,
}

/// Returns the current horizontal mouse scrolling associated with the Mousewheel event.
/// Returns `MouseWheel::None`, `Right` or `Left`
pub fn event_dx() -> MouseWheel {
    match 0.cmp(unsafe { &fl::Fl_event_dx() }) {
        cmp::Ordering::Greater => MouseWheel::Right,
        cmp::Ordering::Equal => MouseWheel::None,
        cmp::Ordering::Less => MouseWheel::Left,
    }
}

/// Returns the current horizontal mouse scrolling associated with the Mousewheel event.
/// Returns `MouseWheel::None`, `Up` or `Down`.
/// Doesn't indicate scrolling direction which depends on system preferences
pub fn event_dy() -> MouseWheel {
    match 0.cmp(unsafe { &fl::Fl_event_dy() }) {
        cmp::Ordering::Greater => MouseWheel::Down,
        cmp::Ordering::Equal => MouseWheel::None,
        cmp::Ordering::Less => MouseWheel::Up,
    }
}

/// Gets the mouse coordinates relative to the screen
pub fn get_mouse() -> (i32, i32) {
    unsafe {
        let mut x: i32 = 0;
        let mut y: i32 = 0;
        fl::Fl_get_mouse(&mut x, &mut y);
        (x, y)
    }
}

/// Returns the x and y coordinates of the captured event
pub fn event_coords() -> (i32, i32) {
    unsafe { (fl::Fl_event_x(), fl::Fl_event_y()) }
}

/// Determines whether an event was a click
pub fn event_is_click() -> bool {
    unsafe { fl::Fl_event_is_click() != 0 }
}

/// Returns the duration of an event
pub fn event_length() -> i32 {
    unsafe { fl::Fl_event_length() as i32 }
}

/// Returns the state of the event
pub fn event_state() -> Shortcut {
    unsafe { mem::transmute(fl::Fl_event_state()) }
}

/// Returns a pair of the width and height of the screen
pub fn screen_size() -> (f64, f64) {
    unsafe { ((fl::Fl_screen_w() as f64), (fl::Fl_screen_h() as f64)) }
}

/// Returns a pair of the x & y coords of the screen
pub fn screen_coords() -> (i32, i32) {
    unsafe { (fl::Fl_screen_x(), fl::Fl_screen_y()) }
}

/// Types of Clipboard contents
#[derive(Debug, Clone, Copy)]
pub enum ClipboardContent {
    /// Textual content
    Text,
    /// Image content
    Image,
}

/// Check the contents of the clipboard
pub fn clipboard_contains(content: ClipboardContent) -> bool {
    use ClipboardContent::*;
    let txt = match content {
        Text => "text/plain",
        Image => "image",
    };
    let txt = CString::new(txt).unwrap();
    unsafe { fl::Fl_clipboard_contains(txt.as_ptr()) != 0 }
}

/// Pastes content from the clipboard
pub fn paste<T>(widget: &T)
where
    T: WidgetExt,
{
    assert!(!widget.was_deleted());
    if clipboard_contains(ClipboardContent::Text) {
        paste_text(widget)
    } else if clipboard_contains(ClipboardContent::Image) {
        paste_image(widget)
    } else {
        // Do nothing!
    }
}

/// Pastes textual content from the clipboard
pub fn paste_text<T>(widget: &T)
where
    T: WidgetExt,
{
    assert!(!widget.was_deleted());
    unsafe {
        fl::Fl_paste_text(widget.as_widget_ptr() as *mut fltk_sys::fl::Fl_Widget, 1);
    }
}

/// Pastes image content from the clipboard
pub fn paste_image<T>(widget: &T)
where
    T: WidgetExt,
{
    assert!(!widget.was_deleted());
    unsafe {
        fl::Fl_paste_image(widget.as_widget_ptr() as *mut fltk_sys::fl::Fl_Widget, 1);
    }
}

/// Sets the callback of a widget
pub fn set_callback<F, W>(widget: &mut W, cb: F)
where
    F: FnMut(&mut dyn WidgetExt),
    W: WidgetExt,
{
    assert!(!widget.was_deleted());
    unsafe {
        unsafe extern "C" fn shim(wid: *mut fltk_sys::widget::Fl_Widget, data: *mut raw::c_void) {
            let a: *mut Box<dyn FnMut(&mut dyn WidgetExt)> =
                data as *mut Box<dyn FnMut(&mut dyn WidgetExt)>;
            let f: &mut (dyn FnMut(&mut dyn WidgetExt)) = &mut **a;
            let mut wid = crate::widget::Widget::from_widget_ptr(wid);
            let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f(&mut wid)));
        }
        let _old_data = widget.user_data();
        let a: *mut Box<dyn FnMut(&mut dyn WidgetExt)> = Box::into_raw(Box::new(Box::new(cb)));
        let data: *mut raw::c_void = a as *mut raw::c_void;
        let callback: fltk_sys::widget::Fl_Callback = Some(shim);
        fltk_sys::widget::Fl_Widget_set_callback(widget.as_widget_ptr(), callback, data);
    }
}

#[allow(clippy::missing_safety_doc)]
/**
    Set a widget callback using a C style API
    ```rust,no_run
    use fltk::{prelude::*, *};
    use std::os::raw::*;
    // data can be anything, even a different widget
    fn cb(w: app::WidgetPtr, data: *mut c_void) {
        // To access the button
        let mut btn = unsafe { button::Button::from_widget_ptr(w) }; // Gets a Widget
        btn.set_label("Works!");
        // To access the frame
        let mut frm = unsafe { widget::Widget::from_widget_ptr(data as app::WidgetPtr) };
        frm.set_label("Works!");
    }
    let mut but = button::Button::default();
    let mut frame = frame::Frame::default();
    unsafe {
        // If no data needs to be passed, you can pass 0 as *mut _
        app::set_raw_callback(&mut but, frame.as_widget_ptr() as *mut _, Some(cb));
        // Using a closure also works
        app::set_raw_callback(&mut but, frame.as_widget_ptr() as *mut _, Some(|_ , _| { println!("Also works!")}));
    }
    ```
    # Safety
    The function involves dereferencing externally provided raw pointers
*/
pub unsafe fn set_raw_callback<W>(
    widget: &mut W,
    data: *mut raw::c_void,
    cb: Option<fn(WidgetPtr, *mut raw::c_void)>,
) where
    W: WidgetExt,
{
    assert!(!widget.was_deleted());
    let cb: Option<unsafe extern "C" fn(WidgetPtr, *mut raw::c_void)> = mem::transmute(cb);
    fltk_sys::widget::Fl_Widget_set_callback(widget.as_widget_ptr(), cb, data);
}

/// Return whether visible focus is shown
pub fn visible_focus() -> bool {
    unsafe { fl::Fl_visible_focus() != 0 }
}

/// Show focus around widgets
pub fn set_visible_focus(flag: bool) {
    unsafe { fl::Fl_set_visible_focus(flag as i32) }
}

/// Set the app's default frame type
pub fn set_frame_type(new_frame: FrameType) {
    unsafe {
        let new_frame = new_frame as i32;
        let mut curr = CURRENT_FRAME.lock().unwrap();
        fl::Fl_set_box_type(*curr, new_frame);
        *curr = new_frame;
    }
}

/// Get the app's frame type
pub fn frame_type() -> FrameType {
    let curr = CURRENT_FRAME.lock().unwrap();
    FrameType::by_index(*curr as _)
}

/// Swap the default frame type with a new frame type
pub fn swap_frame_type(new_frame: FrameType) {
    unsafe {
        let new_frame = new_frame as i32;
        let mut curr = CURRENT_FRAME.lock().unwrap();
        fl::Fl_set_box_type(56, *curr);
        fl::Fl_set_box_type(*curr, new_frame);
        fl::Fl_set_box_type(new_frame, 56);
        *curr = new_frame;
    }
}

/// Set the app's font
pub fn set_font(new_font: Font) {
    unsafe {
        let new_font = new_font.bits() as i32;
        let mut f = CURRENT_FONT.lock().unwrap();
        fl::Fl_set_font(15, *f);
        fl::Fl_set_font(0, new_font);
        fl::Fl_set_font(new_font, *f);
        *f = new_font;
    }
}

/// Set the app's font size
pub fn set_font_size(sz: u8) {
    unsafe { fl::Fl_set_font_size(sz as i32) }
}

/// Get the font's name
pub fn get_font(font: Font) -> String {
    unsafe {
        CStr::from_ptr(fl::Fl_get_font(font.bits() as i32))
            .to_string_lossy()
            .to_string()
    }
}

/// Initializes loaded fonts of a certain pattern `name`
pub fn set_fonts(name: &str) -> u8 {
    let name = CString::safe_new(name);
    unsafe { fl::Fl_set_fonts(name.as_ptr() as *mut raw::c_char) as u8 }
}

/// Gets the name of a font through its index
pub fn font_name(idx: usize) -> Option<String> {
    let f = FONTS.lock().unwrap();
    Some(f[idx].clone())
}

/// Returns a list of available fonts to the application
pub fn get_font_names() -> Vec<String> {
    let mut vec: Vec<String> = vec![];
    let cnt = set_fonts("*") as usize;
    for i in 0..cnt {
        let temp = unsafe {
            CStr::from_ptr(fl::Fl_get_font(i as i32))
                .to_string_lossy()
                .to_string()
        };
        vec.push(temp);
    }
    vec
}

/// Finds the index of a font through its name
pub fn font_index(name: &str) -> Option<usize> {
    let f = FONTS.lock().unwrap();
    f.iter().position(|i| i == name)
}

/// Gets the number of loaded fonts
pub fn font_count() -> usize {
    (*FONTS.lock().unwrap()).len()
}

/// Gets a Vector<String> of loaded fonts
pub fn fonts() -> Vec<String> {
    (*FONTS.lock().unwrap()).clone()
}

/// Adds a custom handler for unhandled events
pub fn add_handler(cb: fn(Event) -> bool) {
    unsafe {
        let callback: Option<unsafe extern "C" fn(ev: raw::c_int) -> raw::c_int> =
            Some(mem::transmute(move |ev| {
                let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| cb(ev) as i32));
            }));
        fl::Fl_add_handler(callback);
    }
}

/// Starts waiting for events.
/// Calls to redraw within wait require an explicit sleep
pub fn wait() -> bool {
    unsafe {
        if !IS_INIT.load(Ordering::Relaxed) {
            init_all();
        }
        fl::Fl_wait() != 0
    }
}

/// Put the thread to sleep for `dur` seconds
pub fn sleep(dur: f64) {
    let dur = dur * 1000.;
    thread::sleep(time::Duration::from_millis(dur as u64));
}

/// Add an idle callback to run within the event loop.
/// Calls to `WidgetExt::redraw` within the callback require an explicit sleep
pub fn add_idle<F: FnMut() + 'static>(cb: F) {
    unsafe {
        unsafe extern "C" fn shim(data: *mut raw::c_void) {
            let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
            let f: &mut (dyn FnMut()) = &mut **a;
            let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
        }
        let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
        let data: *mut raw::c_void = a as *mut raw::c_void;
        let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
        fl::Fl_add_idle(callback, data);
    }
}

/// Remove an idle function
pub fn remove_idle<F: FnMut() + 'static>(cb: F) {
    unsafe {
        unsafe extern "C" fn shim(data: *mut raw::c_void) {
            let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
            let f: &mut (dyn FnMut()) = &mut **a;
            let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
        }
        let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
        let data: *mut raw::c_void = a as *mut raw::c_void;
        let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
        fl::Fl_remove_idle(callback, data);
    }
}

/// Checks whether an idle function is installed
pub fn has_idle<F: FnMut() + 'static>(cb: F) -> bool {
    unsafe {
        unsafe extern "C" fn shim(data: *mut raw::c_void) {
            let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
            let f: &mut (dyn FnMut()) = &mut **a;
            let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
        }
        let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
        let data: *mut raw::c_void = a as *mut raw::c_void;
        let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
        fl::Fl_has_idle(callback, data) != 0
    }
}

/// Waits a maximum of `dur` seconds or until "something happens".
/// Returns true if an event happened (always true on windows).
/// Returns false if nothing happened.
/// # Errors
/// Can error out on X11 system if interrupted by a signal
pub fn wait_for(dur: f64) -> Result<bool, FltkError> {
    unsafe {
        if !IS_INIT.load(Ordering::Relaxed) {
            init_all();
        }
        match fl::Fl_wait_for(dur) as i32 {
            0 => Ok(false),
            1 => Ok(true),
            _ => Err(FltkError::Unknown(String::from(
                "An unknown error occured!",
            ))),
        }
    }
}

/// Sends a custom message
/// # Safety
/// The type must be Send and Sync safe
pub unsafe fn awake_msg<T>(msg: T) {
    fl::Fl_awake_msg(Box::into_raw(Box::from(msg)) as *mut raw::c_void);
}

#[allow(clippy::missing_safety_doc)]
/**
    Receives a custom message
    ```rust,no_run
    use fltk::{prelude::*, *};
    if let Some(msg) = unsafe { app::thread_msg::<i32>() } { /* do something */ }
    ```
    # Safety
    The type must correspond to the received message
*/
pub unsafe fn thread_msg<T>() -> Option<T> {
    let msg = fl::Fl_thread_msg();
    if msg.is_null() {
        None
    } else {
        let msg = Box::from_raw(msg as *const _ as *mut T);
        Some(*msg)
    }
}

#[repr(C)]
struct Message<T: Send + Sync> {
    hash: u64,
    sz: usize,
    msg: T,
}

/// Creates a sender struct
#[derive(Debug, Clone, Copy)]
pub struct Sender<T: Send + Sync> {
    data: marker::PhantomData<T>,
    hash: u64,
    sz: usize,
}

impl<T: Send + Sync> Sender<T> {
    /// Sends a message
    pub fn send(&self, val: T) {
        let msg = Message {
            hash: self.hash,
            sz: self.sz,
            msg: val,
        };
        unsafe { awake_msg(msg) }
    }
}

/// Creates a receiver struct
#[derive(Debug, Clone, Copy)]
pub struct Receiver<T: Send + Sync> {
    data: marker::PhantomData<T>,
    hash: u64,
    sz: usize,
}

impl<T: Send + Sync> Receiver<T> {
    /// Receives a message
    pub fn recv(&self) -> Option<T> {
        let data: Option<Message<T>> = unsafe { thread_msg() };
        data.and_then(|data| {
            if data.sz == self.sz && data.hash == self.hash {
                Some(data.msg)
            } else {
                None
            }
        })
    }
}

/// Creates a channel returning a Sender and Receiver structs (mpsc)
// The implementation could really use generic statics
pub fn channel<T: Send + Sync>() -> (Sender<T>, Receiver<T>) {
    let msg_sz = mem::size_of::<T>();
    let type_name = any::type_name::<T>();
    let mut hasher = DefaultHasher::new();
    type_name.hash(&mut hasher);
    let type_hash = hasher.finish();

    let s = Sender {
        data: marker::PhantomData,
        hash: type_hash,
        sz: msg_sz,
    };
    let r = Receiver {
        data: marker::PhantomData,
        hash: type_hash,
        sz: msg_sz,
    };
    (s, r)
}

/// Returns the first window of the application
pub fn first_window() -> Option<impl WindowExt> {
    unsafe {
        let x = fl::Fl_first_window();
        if x.is_null() {
            None
        } else {
            let x = Window::from_widget_ptr(x as *mut fltk_sys::widget::Fl_Widget);
            Some(x)
        }
    }
}

/// Returns the next window in order
pub fn next_window<W: WindowExt>(w: &W) -> Option<impl WindowExt> {
    unsafe {
        let x = fl::Fl_next_window(w.as_widget_ptr() as *const raw::c_void);
        if x.is_null() {
            None
        } else {
            let x = Window::from_widget_ptr(x as *mut fltk_sys::widget::Fl_Widget);
            Some(x)
        }
    }
}

/// Quit the app
pub fn quit() {
    if let Some(loaded_font) = *LOADED_FONT {
        // Shouldn't fail
        unload_font(loaded_font).unwrap_or(());
    }
    if let Some(wins) = windows() {
        for mut i in wins {
            if i.shown() {
                i.hide();
            }
        }
    }
}

/**
    Adds a one-shot timeout callback. The timeout duration `tm` is indicated in seconds
    Example:
    ```rust,no_run
    use fltk::{prelude::*, *};
    fn callback() {
        println!("TICK");
        app::repeat_timeout(1.0, callback);
    }
    fn main() {
        let app = app::App::default();
        let mut wind = window::Window::new(100, 100, 400, 300, "");
        wind.show();
        app::add_timeout(1.0, callback);
        app.run().unwrap();
    }
    ```
*/
pub fn add_timeout<F: FnMut() + 'static>(tm: f64, cb: F) {
    unsafe {
        unsafe extern "C" fn shim(data: *mut raw::c_void) {
            let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
            let f: &mut (dyn FnMut()) = &mut **a;
            let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
        }
        let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
        let data: *mut raw::c_void = a as *mut raw::c_void;
        let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
        fltk_sys::fl::Fl_add_timeout(tm, callback, data);
    }
}

/**
    Repeats a timeout callback from the expiration of the previous timeout.
    You may only call this method inside a timeout callback.
    The timeout duration `tm` is indicated in seconds
    Example:
    ```rust,no_run
    use fltk::{prelude::*, *};
    fn callback() {
        println!("TICK");
        app::repeat_timeout(1.0, callback);
    }
    fn main() {
        let app = app::App::default();
        let mut wind = window::Window::new(100, 100, 400, 300, "");
        wind.show();
        app::add_timeout(1.0, callback);
        app.run().unwrap();
    }
    ```
*/
pub fn repeat_timeout<F: FnMut() + 'static>(tm: f64, cb: F) {
    unsafe {
        unsafe extern "C" fn shim(data: *mut raw::c_void) {
            let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
            let f: &mut (dyn FnMut()) = &mut **a;
            let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
        }
        let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
        let data: *mut raw::c_void = a as *mut raw::c_void;
        let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
        fltk_sys::fl::Fl_repeat_timeout(tm, callback, data);
    }
}

/// Removes a timeout callback
pub fn remove_timeout<F: FnMut() + 'static>(cb: F) {
    unsafe {
        unsafe extern "C" fn shim(data: *mut raw::c_void) {
            let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
            let f: &mut (dyn FnMut()) = &mut **a;
            let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
        }
        let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
        let data: *mut raw::c_void = a as *mut raw::c_void;
        let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
        fltk_sys::fl::Fl_remove_timeout(callback, data);
    }
}

/// Check whether a timeout is installed
pub fn has_timeout<F: FnMut() + 'static>(cb: F) -> bool {
    unsafe {
        unsafe extern "C" fn shim(data: *mut raw::c_void) {
            let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
            let f: &mut (dyn FnMut()) = &mut **a;
            let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
        }
        let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
        let data: *mut raw::c_void = a as *mut raw::c_void;
        let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
        fltk_sys::fl::Fl_has_timeout(callback, data) != 0
    }
}

/// Returns whether a quit signal was sent
pub fn should_program_quit() -> bool {
    unsafe { fl::Fl_should_program_quit() != 0 }
}

/// Determines whether a program should quit
pub fn program_should_quit(flag: bool) {
    unsafe { fl::Fl_program_should_quit(flag as i32) }
}

/// Returns whether an event occured within a widget
pub fn event_inside_widget<Wid: WidgetExt>(wid: &Wid) -> bool {
    assert!(!wid.was_deleted());
    let x = wid.x();
    let y = wid.y();
    let w = wid.width();
    let h = wid.height();
    unsafe { fl::Fl_event_inside(x, y, w, h) != 0 }
}

/// Returns whether an event occured within a region
pub fn event_inside(x: i32, y: i32, w: i32, h: i32) -> bool {
    unsafe { fl::Fl_event_inside(x, y, w, h) != 0 }
}

/**
    Gets the widget that is below the mouse cursor.
    This returns an Option<impl WidgetExt> which can be specified in the function call
    ```rust,no_run
    use fltk::app;
    use fltk::widget;
    let w = app::belowmouse::<widget::Widget>(); // or by specifying a more concrete type
    ```
*/
pub fn belowmouse<Wid: WidgetExt>() -> Option<impl WidgetExt> {
    unsafe {
        let x = fl::Fl_belowmouse() as *mut fltk_sys::fl::Fl_Widget;
        if x.is_null() {
            None
        } else {
            Some(crate::widget::Widget::from_widget_ptr(
                x as *mut fltk_sys::widget::Fl_Widget,
            ))
        }
    }
}

/// Deletes widgets and their children.
pub fn delete_widget<Wid: WidgetBase>(wid: Wid) {
    assert!(!wid.was_deleted());
    WidgetBase::delete(wid)
}

/// Registers all images supported by `SharedImage`
pub fn register_images() {
    unsafe { fltk_sys::image::Fl_register_images() }
}

/// Inits all styles, fonts and images available to FLTK.
/// Also initializes global locking
/// # Panics
/// If the current environment lacks threading support. Practically this should never happen!
pub fn init_all() {
    unsafe {
        fltk_sys::fl::Fl_init_all();
        lock().expect("fltk-rs requires threading support!");
        register_images();
        // This should never appear!
        *FONTS.lock().unwrap() = vec![
            "Helvetica".to_owned(),
            "HelveticaBold".to_owned(),
            "HelveticaItalic".to_owned(),
            "HelveticaBoldItalic".to_owned(),
            "Courier".to_owned(),
            "CourierBold".to_owned(),
            "CourierItalic".to_owned(),
            "CourierBoldItalic".to_owned(),
            "Times".to_owned(),
            "TimesBold".to_owned(),
            "TimesItalic".to_owned(),
            "TimesBoldItalic".to_owned(),
            "Symbol".to_owned(),
            "Screen".to_owned(),
            "ScreenBold".to_owned(),
            "Zapfdingbats".to_owned(),
        ];
        #[cfg(feature = "enable-glwindow")]
        {
            gl_loader::init_gl();
        }
        if !IS_INIT.load(Ordering::Relaxed) {
            IS_INIT.store(true, Ordering::Relaxed);
        }
    }
}

/// Redraws everything
pub fn redraw() {
    unsafe { fl::Fl_redraw() }
}

/// Returns whether the event is a shift press
pub fn is_event_shift() -> bool {
    unsafe { fl::Fl_event_shift() != 0 }
}

/// Returns whether the event is a control key press
pub fn is_event_ctrl() -> bool {
    unsafe { fl::Fl_event_ctrl() != 0 }
}

/// Returns whether the event is a command key press
pub fn is_event_command() -> bool {
    unsafe { fl::Fl_event_command() != 0 }
}

/// Returns whether the event is a alt key press
pub fn is_event_alt() -> bool {
    unsafe { fl::Fl_event_alt() != 0 }
}

/// Sets the damage to true or false, illiciting a redraw by the application
pub fn set_damage(flag: bool) {
    unsafe { fl::Fl_set_damage(flag as i32) }
}

/// Returns whether any of the widgets were damaged
pub fn damage() -> bool {
    unsafe { fl::Fl_damage() != 0 }
}

/// Sets the visual mode of the application
/// # Errors
/// Returns Err(FailedOperation) if FLTK failed to set the visual mode
pub fn set_visual(mode: Mode) -> Result<(), FltkError> {
    unsafe {
        match fl::Fl_visual(mode.bits() as i32) {
            0 => Err(FltkError::Internal(FltkErrorKind::FailedOperation)),
            _ => Ok(()),
        }
    }
}

/// Makes FLTK use its own colormap. This may make FLTK display better
pub fn own_colormap() {
    unsafe { fl::Fl_own_colormap() }
}

/// Gets the widget which was pushed
pub fn pushed() -> Option<impl WidgetExt> {
    unsafe {
        let ptr = fl::Fl_pushed();
        if ptr.is_null() {
            None
        } else {
            Some(crate::widget::Widget::from_widget_ptr(ptr as *mut _))
        }
    }
}

/// Gets the widget which has focus
pub fn focus() -> Option<impl WidgetExt> {
    unsafe {
        let ptr = fl::Fl_focus();
        if ptr.is_null() {
            None
        } else {
            Some(crate::widget::Widget::from_widget_ptr(
                ptr as *mut fltk_sys::widget::Fl_Widget,
            ))
        }
    }
}

/// Sets the widget which has focus
pub fn set_focus<W: WidgetExt>(wid: &W) {
    unsafe { fl::Fl_set_focus(wid.as_widget_ptr() as *mut raw::c_void) }
}

/// Gets FLTK version
pub fn version() -> f64 {
    unsafe { fl::Fl_version() }
}

/// Gets FLTK API version
pub fn api_version() -> i32 {
    unsafe { fl::Fl_api_version() }
}

/// Gets FLTK ABI version
pub fn abi_version() -> i32 {
    unsafe { fl::Fl_abi_version() }
}

/// Gets FLTK crate version
pub fn crate_version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// The current graphics context of the app, `fl_gc`.
/// `*mut c_void` to `HDC` on Windows, `CGContextRef` on macOS, `_XGC` on X11
pub type GraphicsContext = *mut raw::c_void;

/// Get the graphics context, `fl_gc`
pub fn graphics_context() -> GraphicsContext {
    unsafe {
        let ctx = fltk_sys::window::Fl_gc();
        assert!(!ctx.is_null());
        ctx
    }
}

/// The display global variable, `fl_display`.
/// `_XDisplay` on X11, `HINSTANCE` on Windows.
pub type Display = *mut raw::c_void;

/// Gets the display global variable, `fl_display`.
/// `_XDisplay` on X11, `HINSTANCE` on Windows.
pub fn display() -> Display {
    unsafe {
        let disp = fltk_sys::window::Fl_display();
        assert!(!disp.is_null());
        disp
    }
}

/// Initiate dnd action
pub fn dnd() {
    unsafe {
        fl::Fl_dnd();
    }
}

/// Load a font from a file
fn load_font(path: &str) -> Result<String, FltkError> {
    unsafe {
        let path = CString::new(path)?;
        if let Some(load_font) = *LOADED_FONT {
            unload_font(load_font)?;
        }
        let ptr = fl::Fl_load_font(path.as_ptr());
        if ptr.is_null() {
            Err::<String, FltkError>(FltkError::Internal(FltkErrorKind::FailedOperation))
        } else {
            let name = CStr::from_ptr(ptr as *mut _).to_string_lossy().to_string();
            let mut f = FONTS.lock().unwrap();
            if f.len() < 17 {
                f.push(name.clone());
            } else {
                f[16] = name.clone();
            }
            fl::Fl_set_font2(16, ptr);
            Ok(name)
        }
    }
}

/// Unload a loaded font
fn unload_font(path: &str) -> Result<(), FltkError> {
    unsafe {
        let check = path::Path::new(path);
        if !check.exists() {
            return Err::<(), FltkError>(FltkError::Internal(FltkErrorKind::ResourceNotFound));
        }
        let path = CString::new(path)?;
        fl::Fl_unload_font(path.as_ptr());
        Ok(())
    }
}

/// Returns the apps windows.
pub fn windows() -> Option<Vec<impl WindowExt>> {
    let mut v: Vec<Window> = vec![];
    if let Some(first) = first_window() {
        let first: Window = unsafe { first.into_widget() };
        v.push(first.clone());
        let mut win = first;
        while let Some(wind) = next_window(&win) {
            let w = unsafe { wind.into_widget::<Window>() };
            v.push(w.clone());
            win = w;
        }
        Some(v)
    } else {
        None
    }
}

/// Set the foreground color
pub fn foreground(r: u8, g: u8, b: u8) {
    unsafe { fl::Fl_foreground(r, g, b) }
}

/// Set the background color
pub fn background(r: u8, g: u8, b: u8) {
    unsafe { fl::Fl_background(r, g, b) }
}

/// Set the background color for input and text widgets
pub fn background2(r: u8, g: u8, b: u8) {
    unsafe { fl::Fl_background2(r, g, b) }
}

/// Sets the app's default selection color
pub fn set_selection_color(r: u8, g: u8, b: u8) {
    unsafe { fl::Fl_selection_color(r, g, b) }
}
/// Sets the app's default selection color
pub fn set_inactive_color(r: u8, g: u8, b: u8) {
    unsafe { fl::Fl_inactive_color(r, g, b) }
}

/// Gets the system colors
pub fn get_system_colors() {
    unsafe { fl::Fl_get_system_colors() }
}

/**
    Send a signal to a window.
    Integral values from 0 to 30 are reserved.
    Returns Ok(true) if the event was handled.
    Returns Ok(false) if the event was not handled.
    Returns Err on error or in use of one of the reserved values.
    ```rust,no_run
    use fltk::{prelude::*, *};
    const CHANGE_FRAME: i32 = 100;
    let mut wind = window::Window::default();
    let mut but = button::Button::default();
    let mut frame = frame::Frame::default();
    but.set_callback(move |_| {
        let _ = app::handle(CHANGE_FRAME, &wind).unwrap();
    });
    frame.handle(move |f, ev| {
        if ev == CHANGE_FRAME.into() {
            f.set_label("Hello world");
            true
        } else {
            false
        }
    });
    ```
    # Errors
    Returns Err on error or in use of one of the reserved values.
*/
pub fn handle<I: Into<i32> + Copy + PartialEq + PartialOrd, W: WindowExt>(
    msg: I,
    w: &W,
) -> Result<bool, FltkError> {
    let val = msg.into();
    if val >= 0 && val <= 30 {
        Err(FltkError::Internal(FltkErrorKind::FailedOperation))
    } else {
        let ret = unsafe { fl::Fl_handle(val, w.as_widget_ptr() as _) != 0 };
        Ok(ret)
    }
}

/**
    Send a signal to the main window.
    Integral values from 0 to 30 are reserved.
    Returns Ok(true) if the event was handled.
    Returns Ok(false) if the event was not handled.
    ```rust,no_run
    use fltk::{prelude::*, *};
    const CHANGE_FRAME: i32 = 100;
    let mut wind = window::Window::default();
    let mut but = button::Button::default();
    let mut frame = frame::Frame::default();
    but.set_callback(move |_| {
        let _ = app::handle_main(CHANGE_FRAME).unwrap();
    });
    frame.handle(move |f, ev| {
        if ev == CHANGE_FRAME.into() {
            f.set_label("Hello world");
            true
        } else {
            false
        }
    });
    ```
    # Errors
    Returns Err on error or in use of one of the reserved values.
*/
pub fn handle_main<I: Into<i32> + Copy + PartialEq + PartialOrd>(
    msg: I,
) -> Result<bool, FltkError> {
    let val = msg.into();
    if val >= 0 && val <= 30 {
        Err(FltkError::Internal(FltkErrorKind::FailedOperation))
    } else {
        first_window().map_or(
            Err(FltkError::Internal(FltkErrorKind::FailedOperation)),
            |win| {
                let ret = unsafe { fl::Fl_handle(val, win.as_widget_ptr() as _) != 0 };
                Ok(ret)
            },
        )
    }
}

/// Flush the main window
pub fn flush() {
    unsafe { fl::Fl_flush() }
}

/// Set the screen scale
pub fn set_screen_scale(n: i32, factor: f32) {
    unsafe { fl::Fl_set_screen_scale(n as i32, factor) }
}

/// Get the screen scale
pub fn screen_scale(n: i32) -> f32 {
    unsafe { fl::Fl_screen_scale(n as i32) }
}

/// Return whether scaling the screen is supported
pub fn screen_scaling_supported() -> bool {
    unsafe { fl::Fl_screen_scaling_supported() != 0 }
}

/// Get the screen count
pub fn screen_count() -> i32 {
    unsafe { fl::Fl_screen_count() as i32 }
}

/// Get the screen number based on its coordinates
pub fn screen_num(x: i32, y: i32) -> i32 {
    unsafe { fl::Fl_screen_num(x, y) }
}

/// Get a screen's dpi resolution
/// # Returns
/// (vertical, horizontal) resolutions
pub fn screen_dpi(screen_num: i32) -> (f32, f32) {
    let mut h: f32 = 0.;
    let mut v: f32 = 0.;
    unsafe {
        fl::Fl_screen_dpi(&mut h, &mut v, screen_num);
    }
    (h, v)
}

/// Get a screen's xywh
pub fn screen_xywh(screen_num: i32) -> (i32, i32, i32, i32) {
    let mut x = 0;
    let mut y = 0;
    let mut w = 0;
    let mut h = 0;
    unsafe {
        fl::Fl_screen_xywh(&mut x, &mut y, &mut w, &mut h, screen_num);
    }
    (x, y, w, h)
}

/// Get a screen's working area
pub fn screen_work_area(screen_num: i32) -> (i32, i32, i32, i32) {
    let mut x = 0;
    let mut y = 0;
    let mut w = 0;
    let mut h = 0;
    unsafe {
        fl::Fl_screen_work_area(&mut x, &mut y, &mut w, &mut h, screen_num);
    }
    (x, y, w, h)
}

/// Open the current display
/// # Safety
/// A correct visual must be set prior to opening the display
pub unsafe fn open_display() {
    fl::Fl_open_display()
}

/// Close the current display
/// # Safety
/// The display shouldn't be closed while a window is shown
pub unsafe fn close_display() {
    fl::Fl_close_display()
}

/// Get the clipboard content if it's an image
pub fn event_clipboard_image() -> Option<crate::image::RgbImage> {
    unsafe {
        let image = fl::Fl_event_clipboard();
        if image.is_null() {
            None
        } else {
            use std::sync::atomic::AtomicUsize;
            Some(crate::image::RgbImage {
                inner: image as _,
                refcount: AtomicUsize::new(1),
            })
        }
    }
}

/// The event clipboard type
#[derive(Debug, Clone)]
pub enum ClipboardEvent {
    /// Text paste event
    Text(String),
    /// image paste event
    Image(Option<crate::image::RgbImage>),
}

/// Get the clipboard content type
pub fn event_clipboard() -> Option<ClipboardEvent> {
    unsafe {
        let txt = fl::Fl_event_clipboard_type();
        let txt = CStr::from_ptr(txt).to_string_lossy().to_string();
        if txt == "text/plain" {
            Some(ClipboardEvent::Text(event_text()))
        } else if txt == "image" {
            Some(ClipboardEvent::Image(event_clipboard_image()))
        } else {
            None
        }
    }
}

#[allow(clippy::missing_safety_doc)]
/**
    Send a signal to a window pointer from event_dispatch.
    Returns true if the event was handled.
    Returns false if the event was not handled or ignored.
    ```rust,no_run
    use fltk::{prelude::*, *};
    const CHANGE_FRAME: i32 = 100;
    let mut wind = window::Window::default();
    let mut but = button::Button::default();
    let mut frame = frame::Frame::default();
    wind.end();
    wind.show();
    but.set_callback(move |_| {
        let _ = app::handle_main(CHANGE_FRAME).unwrap();
    });

    frame.handle(move |f, ev| {
        if ev == CHANGE_FRAME.into() {
            f.set_label("Hello world");
            true
        } else {
            false
        }
    });
    unsafe {
        app::event_dispatch(|ev, winptr| {
            if ev == CHANGE_FRAME.into() {
                false // ignore CHANGE_FRAME event
            } else {
                app::handle_raw(ev, winptr)
            }
        });
    }
    ```
    # Safety
    The window pointer must be valid
*/
pub unsafe fn handle_raw(
    event: Event,
    w: WindowPtr,
) -> bool {
    fl::Fl_handle_(event.bits(), w as _) != 0
}

#[allow(clippy::missing_safety_doc)]
/**
    The event dispatch function is called after native events are converted to
    FLTK events, but before they are handled by FLTK. If the dispatch function
    handler is set, it is up to the dispatch function to call
    `app::handle2(Event, WindowPtr)` or to ignore the event.

    The dispatch function itself must return false if it ignored the event,
    or true if it used the event. If you call `app::handle2()`, then
    this will return the correct value.
    # Safety
    The window pointer must not be invalidated
*/
pub unsafe fn event_dispatch(f: fn(Event, WindowPtr) -> bool) {
    fl::Fl_event_dispatch(mem::transmute(f));
}