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
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::translate::{from_glib, from_glib_full, FromGlib, IntoGlib, ToGlibPtr};
#[cfg(any(unix, feature = "dox"))]
use crate::IOCondition;
use ffi::{self, gboolean, gpointer};
#[cfg(all(not(unix), feature = "dox"))]
use libc::c_int as RawFd;
use std::cell::RefCell;
use std::mem::transmute;
use std::num::NonZeroU32;
#[cfg(unix)]
use std::os::unix::io::RawFd;
use std::time::Duration;

use crate::MainContext;
use crate::Source;

/// The id of a source that is returned by `idle_add` and `timeout_add`.
///
/// This type does not implement `Clone` to prevent calling [`source_remove()`]
/// multiple times on the same source.
#[derive(Debug, Eq, PartialEq)]
pub struct SourceId(NonZeroU32);

impl SourceId {
    /// Returns the internal source ID.
    pub unsafe fn as_raw(&self) -> u32 {
        self.0.get()
    }
}

#[doc(hidden)]
impl FromGlib<u32> for SourceId {
    #[inline]
    unsafe fn from_glib(val: u32) -> Self {
        assert_ne!(val, 0);
        Self(NonZeroU32::new_unchecked(val))
    }
}

/// Process identificator
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[doc(alias = "GPid")]
pub struct Pid(pub ffi::GPid);

unsafe impl Send for Pid {}
unsafe impl Sync for Pid {}

#[doc(hidden)]
impl IntoGlib for Pid {
    type GlibType = ffi::GPid;

    #[inline]
    fn into_glib(self) -> ffi::GPid {
        self.0
    }
}

#[doc(hidden)]
impl FromGlib<ffi::GPid> for Pid {
    #[inline]
    unsafe fn from_glib(val: ffi::GPid) -> Self {
        Self(val)
    }
}

/// Continue calling the closure in the future iterations or drop it.
///
/// This is the return type of `idle_add` and `timeout_add` closures.
///
/// `Continue(true)` keeps the closure assigned, to be rerun when appropriate.
///
/// `Continue(false)` disconnects and drops it.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Continue(pub bool);

#[doc(hidden)]
impl IntoGlib for Continue {
    type GlibType = gboolean;

    #[inline]
    fn into_glib(self) -> gboolean {
        self.0.into_glib()
    }
}

unsafe extern "C" fn trampoline<F: FnMut() -> Continue + 'static>(func: gpointer) -> gboolean {
    let func: &RefCell<F> = &*(func as *const RefCell<F>);
    (&mut *func.borrow_mut())().into_glib()
}

unsafe extern "C" fn destroy_closure<F: FnMut() -> Continue + 'static>(ptr: gpointer) {
    Box::<RefCell<F>>::from_raw(ptr as *mut _);
}

fn into_raw<F: FnMut() -> Continue + 'static>(func: F) -> gpointer {
    let func: Box<RefCell<F>> = Box::new(RefCell::new(func));
    Box::into_raw(func) as gpointer
}

unsafe extern "C" fn trampoline_child_watch<F: FnMut(Pid, i32) + 'static>(
    pid: ffi::GPid,
    status: i32,
    func: gpointer,
) {
    let func: &RefCell<F> = &*(func as *const RefCell<F>);
    (&mut *func.borrow_mut())(Pid(pid), status)
}

unsafe extern "C" fn destroy_closure_child_watch<F: FnMut(Pid, i32) + 'static>(ptr: gpointer) {
    Box::<RefCell<F>>::from_raw(ptr as *mut _);
}

fn into_raw_child_watch<F: FnMut(Pid, i32) + 'static>(func: F) -> gpointer {
    let func: Box<RefCell<F>> = Box::new(RefCell::new(func));
    Box::into_raw(func) as gpointer
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
unsafe extern "C" fn trampoline_unix_fd<F: FnMut(RawFd, IOCondition) -> Continue + 'static>(
    fd: i32,
    condition: ffi::GIOCondition,
    func: gpointer,
) -> gboolean {
    let func: &RefCell<F> = &*(func as *const RefCell<F>);
    (&mut *func.borrow_mut())(fd, from_glib(condition)).into_glib()
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
unsafe extern "C" fn destroy_closure_unix_fd<F: FnMut(RawFd, IOCondition) -> Continue + 'static>(
    ptr: gpointer,
) {
    Box::<RefCell<F>>::from_raw(ptr as *mut _);
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
fn into_raw_unix_fd<F: FnMut(RawFd, IOCondition) -> Continue + 'static>(func: F) -> gpointer {
    let func: Box<RefCell<F>> = Box::new(RefCell::new(func));
    Box::into_raw(func) as gpointer
}

/// Transform a generic FnOnce into a closure that can be used as callback in various glib methods
///
/// The resulting function can only be called once and will panic otherwise. It will return `Continue(false)`
/// in order to prevent being called twice.
#[inline(always)]
fn fnmut_callback_wrapper(
    func: impl FnOnce() + Send + 'static,
) -> impl FnMut() -> Continue + Send + 'static {
    let mut func = Some(func);
    move || {
        let func = func
            .take()
            .expect("GSource closure called after returning glib::Continue(false)");
        func();
        Continue(false)
    }
}

/// Transform a generic FnOnce into a closure that can be used as callback in various glib methods
///
/// The resulting function can only be called once and will panic otherwise. It will return `Continue(false)`
/// in order to prevent being called twice.
///
/// Different to `fnmut_callback_wrapper()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
#[inline(always)]
fn fnmut_callback_wrapper_local(
    func: impl FnOnce() + 'static,
) -> impl FnMut() -> Continue + 'static {
    let mut func = Some(func);
    move || {
        let func = func
            .take()
            .expect("GSource closure called after returning glib::Continue(false)");
        func();
        Continue(false)
    }
}

/// Adds a closure to be called by the default main loop when it's idle.
///
/// `func` will be called repeatedly until it returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
#[doc(alias = "g_idle_add_full")]
pub fn idle_add<F>(func: F) -> SourceId
where
    F: FnMut() -> Continue + Send + 'static,
{
    unsafe {
        from_glib(ffi::g_idle_add_full(
            ffi::G_PRIORITY_DEFAULT_IDLE,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        ))
    }
}

/// Adds a closure to be called by the default main loop when it's idle.
///
/// `func` will be called repeatedly until it returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// In comparison to `idle_add()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `Continue(false)`.
#[doc(alias = "g_idle_add_full")]
pub fn idle_add_once<F>(func: F) -> SourceId
where
    F: FnOnce() + Send + 'static,
{
    idle_add(fnmut_callback_wrapper(func))
}

/// Adds a closure to be called by the default main loop when it's idle.
///
/// `func` will be called repeatedly until it returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// Different to `idle_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
#[doc(alias = "g_idle_add_full")]
pub fn idle_add_local<F>(func: F) -> SourceId
where
    F: FnMut() -> Continue + 'static,
{
    unsafe {
        assert!(MainContext::default().is_owner());
        from_glib(ffi::g_idle_add_full(
            ffi::G_PRIORITY_DEFAULT_IDLE,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        ))
    }
}

/// Adds a closure to be called by the default main loop when it's idle.
///
/// `func` will be called repeatedly until it returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// Different to `idle_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
///
/// In comparison to `idle_add_local()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `Continue(false)`.
#[doc(alias = "g_idle_add_full")]
pub fn idle_add_local_once<F>(func: F) -> SourceId
where
    F: FnOnce() + 'static,
{
    idle_add_local(fnmut_callback_wrapper_local(func))
}

/// Adds a closure to be called by the default main loop at regular intervals
/// with millisecond granularity.
///
/// `func` will be called repeatedly every `interval` milliseconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events. Prefer `timeout_add_seconds` when millisecond
/// precision is not necessary.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
// rustdoc-stripper-ignore-next-stop
/// Sets a function to be called at regular intervals, with the default
/// priority, `G_PRIORITY_DEFAULT`. The function is called repeatedly
/// until it returns [`false`], at which point the timeout is automatically
/// destroyed and the function will not be called again. The first call
/// to the function will be at the end of the first `interval`.
///
/// Note that timeout functions may be delayed, due to the processing of other
/// event sources. Thus they should not be relied on for precise timing.
/// After each call to the timeout function, the time of the next
/// timeout is recalculated based on the current time and the given interval
/// (it does not try to 'catch up' time lost in delays).
///
/// See [memory management of sources][mainloop-memory-management] for details
/// on how to handle the return value and memory management of `data`.
///
/// If you want to have a timer in the "seconds" range and do not care
/// about the exact time of the first call of the timer, use the
/// `g_timeout_add_seconds()` function; this function allows for more
/// optimizations and more efficient system power usage.
///
/// This internally creates a main loop source using `g_timeout_source_new()`
/// and attaches it to the global [`MainContext`][crate::MainContext] using `g_source_attach()`, so
/// the callback will be invoked in whichever thread is running that main
/// context. You can do these steps manually if you need greater control or to
/// use a custom main context.
///
/// It is safe to call this function from any thread.
///
/// The interval given is in terms of monotonic time, not wall clock
/// time. See [`monotonic_time()`][crate::monotonic_time()].
/// ## `interval`
/// the time between calls to the function, in milliseconds
///  (1/1000ths of a second)
/// ## `function`
/// function to call
///
/// # Returns
///
/// the ID (greater than 0) of the event source.
#[doc(alias = "g_timeout_add_full")]
pub fn timeout_add<F>(interval: Duration, func: F) -> SourceId
where
    F: FnMut() -> Continue + Send + 'static,
{
    unsafe {
        from_glib(ffi::g_timeout_add_full(
            ffi::G_PRIORITY_DEFAULT,
            interval.as_millis() as _,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        ))
    }
}

/// Adds a closure to be called by the default main loop at regular intervals
/// with millisecond granularity.
///
/// `func` will be called repeatedly every `interval` milliseconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events. Prefer `timeout_add_seconds` when millisecond
/// precision is not necessary.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// In comparison to `timeout_add()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `Continue(false)`.
#[doc(alias = "g_timeout_add_full")]
pub fn timeout_add_once<F>(interval: Duration, func: F) -> SourceId
where
    F: FnOnce() + Send + 'static,
{
    timeout_add(interval, fnmut_callback_wrapper(func))
}

/// Adds a closure to be called by the default main loop at regular intervals
/// with millisecond granularity.
///
/// `func` will be called repeatedly every `interval` milliseconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events. Prefer `timeout_add_seconds` when millisecond
/// precision is not necessary.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// Different to `timeout_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
#[doc(alias = "g_timeout_add_full")]
pub fn timeout_add_local<F>(interval: Duration, func: F) -> SourceId
where
    F: FnMut() -> Continue + 'static,
{
    unsafe {
        assert!(MainContext::default().is_owner());
        from_glib(ffi::g_timeout_add_full(
            ffi::G_PRIORITY_DEFAULT,
            interval.as_millis() as _,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        ))
    }
}

/// Adds a closure to be called by the default main loop at regular intervals
/// with millisecond granularity.
///
/// `func` will be called repeatedly every `interval` milliseconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events. Prefer `timeout_add_seconds` when millisecond
/// precision is not necessary.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// Different to `timeout_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
///
/// In comparison to `timeout_add_local()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `Continue(false)`.
#[doc(alias = "g_timeout_add_full")]
pub fn timeout_add_local_once<F>(interval: Duration, func: F) -> SourceId
where
    F: FnOnce() + 'static,
{
    timeout_add_local(interval, fnmut_callback_wrapper_local(func))
}

/// Adds a closure to be called by the default main loop at regular intervals
/// with second granularity.
///
/// `func` will be called repeatedly every `interval` seconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
// rustdoc-stripper-ignore-next-stop
/// Sets a function to be called at regular intervals with the default
/// priority, `G_PRIORITY_DEFAULT`. The function is called repeatedly until
/// it returns [`false`], at which point the timeout is automatically destroyed
/// and the function will not be called again.
///
/// This internally creates a main loop source using
/// `g_timeout_source_new_seconds()` and attaches it to the main loop context
/// using `g_source_attach()`. You can do these steps manually if you need
/// greater control. Also see `g_timeout_add_seconds_full()`.
///
/// It is safe to call this function from any thread.
///
/// Note that the first call of the timer may not be precise for timeouts
/// of one second. If you need finer precision and have such a timeout,
/// you may want to use `g_timeout_add()` instead.
///
/// See [memory management of sources][mainloop-memory-management] for details
/// on how to handle the return value and memory management of `data`.
///
/// The interval given is in terms of monotonic time, not wall clock
/// time. See [`monotonic_time()`][crate::monotonic_time()].
/// ## `interval`
/// the time between calls to the function, in seconds
/// ## `function`
/// function to call
///
/// # Returns
///
/// the ID (greater than 0) of the event source.
#[doc(alias = "g_timeout_add_seconds_full")]
pub fn timeout_add_seconds<F>(interval: u32, func: F) -> SourceId
where
    F: FnMut() -> Continue + Send + 'static,
{
    unsafe {
        from_glib(ffi::g_timeout_add_seconds_full(
            ffi::G_PRIORITY_DEFAULT,
            interval,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        ))
    }
}

/// Adds a closure to be called by the default main loop at regular intervals
/// with second granularity.
///
/// `func` will be called repeatedly every `interval` seconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// In comparison to `timeout_add_seconds()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `Continue(false)`.
#[doc(alias = "g_timeout_add_seconds_full")]
pub fn timeout_add_seconds_once<F>(interval: u32, func: F) -> SourceId
where
    F: FnOnce() + Send + 'static,
{
    timeout_add_seconds(interval, fnmut_callback_wrapper(func))
}

/// Adds a closure to be called by the default main loop at regular intervals
/// with second granularity.
///
/// `func` will be called repeatedly every `interval` seconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// Different to `timeout_add_seconds()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
#[doc(alias = "g_timeout_add_seconds_full")]
pub fn timeout_add_seconds_local<F>(interval: u32, func: F) -> SourceId
where
    F: FnMut() -> Continue + 'static,
{
    unsafe {
        assert!(MainContext::default().is_owner());
        from_glib(ffi::g_timeout_add_seconds_full(
            ffi::G_PRIORITY_DEFAULT,
            interval,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        ))
    }
}

/// Adds a closure to be called by the default main loop at regular intervals
/// with second granularity.
///
/// `func` will be called repeatedly every `interval` seconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// Different to `timeout_add_seconds()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
///
/// In comparison to `timeout_add_seconds_local()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `Continue(false)`.
#[doc(alias = "g_timeout_add_seconds_full")]
pub fn timeout_add_seconds_local_once<F>(interval: u32, func: F) -> SourceId
where
    F: FnOnce() + 'static,
{
    timeout_add_seconds_local(interval, fnmut_callback_wrapper_local(func))
}

/// Adds a closure to be called by the main loop the returned `Source` is attached to when a child
/// process exits.
///
/// `func` will be called when `pid` exits
// rustdoc-stripper-ignore-next-stop
/// Sets a function to be called when the child indicated by `pid`
/// exits, at a default priority, `G_PRIORITY_DEFAULT`.
///
/// If you obtain `pid` from [`spawn_async()`][crate::spawn_async()] or `g_spawn_async_with_pipes()`
/// you will need to pass [`SpawnFlags::DO_NOT_REAP_CHILD`][crate::SpawnFlags::DO_NOT_REAP_CHILD] as flag to
/// the spawn function for the child watching to work.
///
/// Note that on platforms where `GPid` must be explicitly closed
/// (see `g_spawn_close_pid()`) `pid` must not be closed while the
/// source is still active. Typically, you will want to call
/// `g_spawn_close_pid()` in the callback function for the source.
///
/// GLib supports only a single callback per process id.
/// On POSIX platforms, the same restrictions mentioned for
/// `g_child_watch_source_new()` apply to this function.
///
/// This internally creates a main loop source using
/// `g_child_watch_source_new()` and attaches it to the main loop context
/// using `g_source_attach()`. You can do these steps manually if you
/// need greater control.
/// ## `pid`
/// process id to watch. On POSIX the positive pid of a child
/// process. On Windows a handle for a process (which doesn't have to be
/// a child).
/// ## `function`
/// function to call
///
/// # Returns
///
/// the ID (greater than 0) of the event source.
#[doc(alias = "g_child_watch_add_full")]
pub fn child_watch_add<F>(pid: Pid, func: F) -> SourceId
where
    F: FnMut(Pid, i32) + Send + 'static,
{
    unsafe {
        from_glib(ffi::g_child_watch_add_full(
            ffi::G_PRIORITY_DEFAULT,
            pid.0,
            Some(trampoline_child_watch::<F>),
            into_raw_child_watch(func),
            Some(destroy_closure_child_watch::<F>),
        ))
    }
}

/// Adds a closure to be called by the main loop the returned `Source` is attached to when a child
/// process exits.
///
/// `func` will be called when `pid` exits
///
/// Different to `child_watch_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
#[doc(alias = "g_child_watch_add_full")]
pub fn child_watch_add_local<F>(pid: Pid, func: F) -> SourceId
where
    F: FnMut(Pid, i32) + 'static,
{
    unsafe {
        assert!(MainContext::default().is_owner());
        from_glib(ffi::g_child_watch_add_full(
            ffi::G_PRIORITY_DEFAULT,
            pid.0,
            Some(trampoline_child_watch::<F>),
            into_raw_child_watch(func),
            Some(destroy_closure_child_watch::<F>),
        ))
    }
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
/// Adds a closure to be called by the default main loop whenever a UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
// rustdoc-stripper-ignore-next-stop
/// A convenience function for `g_unix_signal_source_new()`, which
/// attaches to the default [`MainContext`][crate::MainContext]. You can remove the watch
/// using `g_source_remove()`.
/// ## `signum`
/// Signal number
/// ## `handler`
/// Callback
///
/// # Returns
///
/// An ID (greater than 0) for the event source
#[doc(alias = "g_unix_signal_add_full")]
pub fn unix_signal_add<F>(signum: i32, func: F) -> SourceId
where
    F: FnMut() -> Continue + Send + 'static,
{
    unsafe {
        from_glib(ffi::g_unix_signal_add_full(
            ffi::G_PRIORITY_DEFAULT,
            signum,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        ))
    }
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
/// Adds a closure to be called by the default main loop whenever a UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// In comparison to `unix_signal_add()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `Continue(false)`.
#[doc(alias = "g_unix_signal_add_full")]
pub fn unix_signal_add_once<F>(signum: i32, func: F) -> SourceId
where
    F: FnOnce() + Send + 'static,
{
    unix_signal_add(signum, fnmut_callback_wrapper(func))
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
/// Adds a closure to be called by the default main loop whenever a UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// Different to `unix_signal_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
#[doc(alias = "g_unix_signal_add_full")]
pub fn unix_signal_add_local<F>(signum: i32, func: F) -> SourceId
where
    F: FnMut() -> Continue + 'static,
{
    unsafe {
        assert!(MainContext::default().is_owner());
        from_glib(ffi::g_unix_signal_add_full(
            ffi::G_PRIORITY_DEFAULT,
            signum,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        ))
    }
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
/// Adds a closure to be called by the default main loop whenever a UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// Different to `unix_signal_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
///
/// In comparison to `unix_signal_add_local()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `Continue(false)`.
#[doc(alias = "g_unix_signal_add_full")]
pub fn unix_signal_add_local_once<F>(signum: i32, func: F) -> SourceId
where
    F: FnOnce() + 'static,
{
    unix_signal_add_local(signum, fnmut_callback_wrapper_local(func))
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX file descriptor reaches the given IO condition.
///
/// `func` will be called repeatedly while the file descriptor matches the given IO condition
/// until it returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
// rustdoc-stripper-ignore-next-stop
/// Sets a function to be called when the IO condition, as specified by
/// `condition` becomes true for `fd`.
///
/// `function` will be called when the specified IO condition becomes
/// [`true`]. The function is expected to clear whatever event caused the
/// IO condition to become true and return [`true`] in order to be notified
/// when it happens again. If `function` returns [`false`] then the watch
/// will be cancelled.
///
/// The return value of this function can be passed to `g_source_remove()`
/// to cancel the watch at any time that it exists.
///
/// The source will never close the fd -- you must do it yourself.
/// ## `fd`
/// a file descriptor
/// ## `condition`
/// IO conditions to watch for on `fd`
/// ## `function`
/// a `GUnixFDSourceFunc`
///
/// # Returns
///
/// the ID (greater than 0) of the event source
#[doc(alias = "g_unix_fd_add_full")]
pub fn unix_fd_add<F>(fd: RawFd, condition: IOCondition, func: F) -> SourceId
where
    F: FnMut(RawFd, IOCondition) -> Continue + Send + 'static,
{
    unsafe {
        from_glib(ffi::g_unix_fd_add_full(
            ffi::G_PRIORITY_DEFAULT,
            fd,
            condition.into_glib(),
            Some(trampoline_unix_fd::<F>),
            into_raw_unix_fd(func),
            Some(destroy_closure_unix_fd::<F>),
        ))
    }
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX file descriptor reaches the given IO condition.
///
/// `func` will be called repeatedly while the file descriptor matches the given IO condition
/// until it returns `Continue(false)`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus the closure is called on the main thread.
///
/// Different to `unix_fd_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
#[doc(alias = "g_unix_fd_add_full")]
pub fn unix_fd_add_local<F>(fd: RawFd, condition: IOCondition, func: F) -> SourceId
where
    F: FnMut(RawFd, IOCondition) -> Continue + 'static,
{
    unsafe {
        assert!(MainContext::default().is_owner());
        from_glib(ffi::g_unix_fd_add_full(
            ffi::G_PRIORITY_DEFAULT,
            fd,
            condition.into_glib(),
            Some(trampoline_unix_fd::<F>),
            into_raw_unix_fd(func),
            Some(destroy_closure_unix_fd::<F>),
        ))
    }
}

/// Removes the source with the given id `source_id` from the default main context.
///
/// It is a programmer error to attempt to remove a non-existent source.
/// Note: source id are reused.
///
/// For historical reasons, the native function always returns true, so we
/// ignore it here.
#[allow(clippy::needless_pass_by_value)]
#[doc(alias = "g_source_remove")]
pub fn source_remove(source_id: SourceId) {
    unsafe {
        ffi::g_source_remove(source_id.as_raw());
    }
}

/// The priority of sources
///
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Priority(i32);

#[doc(hidden)]
impl IntoGlib for Priority {
    type GlibType = i32;

    #[inline]
    fn into_glib(self) -> i32 {
        self.0
    }
}

#[doc(hidden)]
impl FromGlib<i32> for Priority {
    #[inline]
    unsafe fn from_glib(val: i32) -> Self {
        Self(val)
    }
}

impl Default for Priority {
    fn default() -> Self {
        PRIORITY_DEFAULT
    }
}

/// Use this for high priority event sources.
///
/// It is not used within GLib or GTK+.
pub const PRIORITY_HIGH: Priority = Priority(ffi::G_PRIORITY_HIGH);
/// Use this for default priority event sources.
///
/// In GLib this priority is used when adding timeout functions
/// with `g_timeout_add()`. In GDK this priority is used for events
/// from the X server.
pub const PRIORITY_DEFAULT: Priority = Priority(ffi::G_PRIORITY_DEFAULT);
/// Use this for high priority idle functions.
///
/// GTK+ uses `G_PRIORITY_HIGH_IDLE` + 10 for resizing operations,
/// and `G_PRIORITY_HIGH_IDLE` + 20 for redrawing operations. (This is
/// done to ensure that any pending resizes are processed before any
/// pending redraws, so that widgets are not redrawn twice unnecessarily.)
pub const PRIORITY_HIGH_IDLE: Priority = Priority(ffi::G_PRIORITY_HIGH_IDLE);
/// Use this for default priority idle functions.
///
/// In GLib this priority is used when adding idle functions with
/// `g_idle_add()`.
pub const PRIORITY_DEFAULT_IDLE: Priority = Priority(ffi::G_PRIORITY_DEFAULT_IDLE);
/// Use this for very low priority background tasks.
///
/// It is not used within GLib or GTK+.
pub const PRIORITY_LOW: Priority = Priority(ffi::G_PRIORITY_LOW);

/// Adds a closure to be called by the main loop the return `Source` is attached to when it's idle.
///
/// `func` will be called repeatedly until it returns `Continue(false)`.
#[doc(alias = "g_idle_source_new")]
pub fn idle_source_new<F>(name: Option<&str>, priority: Priority, func: F) -> Source
where
    F: FnMut() -> Continue + Send + 'static,
{
    unsafe {
        let source = ffi::g_idle_source_new();
        ffi::g_source_set_callback(
            source,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        );
        ffi::g_source_set_priority(source, priority.into_glib());

        if let Some(name) = name {
            ffi::g_source_set_name(source, name.to_glib_none().0);
        }

        from_glib_full(source)
    }
}

/// Adds a closure to be called by the main loop the returned `Source` is attached to at regular
/// intervals with millisecond granularity.
///
/// `func` will be called repeatedly every `interval` milliseconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events. Prefer `timeout_add_seconds` when millisecond
/// precision is not necessary.
// rustdoc-stripper-ignore-next-stop
/// Creates a new timeout source.
///
/// The source will not initially be associated with any [`MainContext`][crate::MainContext]
/// and must be added to one with `g_source_attach()` before it will be
/// executed.
///
/// The interval given is in terms of monotonic time, not wall clock
/// time. See [`monotonic_time()`][crate::monotonic_time()].
/// ## `interval`
/// the timeout interval in milliseconds.
///
/// # Returns
///
/// the newly-created timeout source
#[doc(alias = "g_timeout_source_new")]
pub fn timeout_source_new<F>(
    interval: Duration,
    name: Option<&str>,
    priority: Priority,
    func: F,
) -> Source
where
    F: FnMut() -> Continue + Send + 'static,
{
    unsafe {
        let source = ffi::g_timeout_source_new(interval.as_millis() as _);
        ffi::g_source_set_callback(
            source,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        );
        ffi::g_source_set_priority(source, priority.into_glib());

        if let Some(name) = name {
            ffi::g_source_set_name(source, name.to_glib_none().0);
        }

        from_glib_full(source)
    }
}

/// Adds a closure to be called by the main loop the returned `Source` is attached to at regular
/// intervals with second granularity.
///
/// `func` will be called repeatedly every `interval` seconds until it
/// returns `Continue(false)`. Precise timing is not guaranteed, the timeout may
/// be delayed by other events.
// rustdoc-stripper-ignore-next-stop
/// Creates a new timeout source.
///
/// The source will not initially be associated with any [`MainContext`][crate::MainContext]
/// and must be added to one with `g_source_attach()` before it will be
/// executed.
///
/// The scheduling granularity/accuracy of this timeout source will be
/// in seconds.
///
/// The interval given is in terms of monotonic time, not wall clock time.
/// See [`monotonic_time()`][crate::monotonic_time()].
/// ## `interval`
/// the timeout interval in seconds
///
/// # Returns
///
/// the newly-created timeout source
#[doc(alias = "g_timeout_source_new_seconds")]
pub fn timeout_source_new_seconds<F>(
    interval: u32,
    name: Option<&str>,
    priority: Priority,
    func: F,
) -> Source
where
    F: FnMut() -> Continue + Send + 'static,
{
    unsafe {
        let source = ffi::g_timeout_source_new_seconds(interval);
        ffi::g_source_set_callback(
            source,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        );
        ffi::g_source_set_priority(source, priority.into_glib());

        if let Some(name) = name {
            ffi::g_source_set_name(source, name.to_glib_none().0);
        }

        from_glib_full(source)
    }
}

/// Adds a closure to be called by the main loop the returned `Source` is attached to when a child
/// process exits.
///
/// `func` will be called when `pid` exits
// rustdoc-stripper-ignore-next-stop
/// Creates a new child_watch source.
///
/// The source will not initially be associated with any [`MainContext`][crate::MainContext]
/// and must be added to one with `g_source_attach()` before it will be
/// executed.
///
/// Note that child watch sources can only be used in conjunction with
/// `g_spawn...` when the [`SpawnFlags::DO_NOT_REAP_CHILD`][crate::SpawnFlags::DO_NOT_REAP_CHILD] flag is used.
///
/// Note that on platforms where `GPid` must be explicitly closed
/// (see `g_spawn_close_pid()`) `pid` must not be closed while the
/// source is still active. Typically, you will want to call
/// `g_spawn_close_pid()` in the callback function for the source.
///
/// On POSIX platforms, the following restrictions apply to this API
/// due to limitations in POSIX process interfaces:
///
/// * `pid` must be a child of this process
/// * `pid` must be positive
/// * the application must not call `waitpid` with a non-positive
///  first argument, for instance in another thread
/// * the application must not wait for `pid` to exit by any other
///  mechanism, including `waitpid(pid, ...)` or a second child-watch
///  source for the same `pid`
/// * the application must not ignore `SIGCHLD`
///
/// If any of those conditions are not met, this and related APIs will
/// not work correctly. This can often be diagnosed via a GLib warning
/// stating that `ECHILD` was received by `waitpid`.
///
/// Calling `waitpid` for specific processes other than `pid` remains a
/// valid thing to do.
/// ## `pid`
/// process to watch. On POSIX the positive pid of a child process. On
/// Windows a handle for a process (which doesn't have to be a child).
///
/// # Returns
///
/// the newly-created child watch source
#[doc(alias = "g_child_watch_source_new")]
pub fn child_watch_source_new<F>(
    pid: Pid,
    name: Option<&str>,
    priority: Priority,
    func: F,
) -> Source
where
    F: FnMut(Pid, i32) + Send + 'static,
{
    unsafe {
        let source = ffi::g_child_watch_source_new(pid.0);
        ffi::g_source_set_callback(
            source,
            Some(transmute::<
                _,
                unsafe extern "C" fn(ffi::gpointer) -> ffi::gboolean,
            >(trampoline_child_watch::<F> as *const ())),
            into_raw_child_watch(func),
            Some(destroy_closure_child_watch::<F>),
        );
        ffi::g_source_set_priority(source, priority.into_glib());

        if let Some(name) = name {
            ffi::g_source_set_name(source, name.to_glib_none().0);
        }

        from_glib_full(source)
    }
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `Continue(false)`.
// rustdoc-stripper-ignore-next-stop
/// Create a [`Source`][crate::Source] that will be dispatched upon delivery of the UNIX
/// signal `signum`. In GLib versions before 2.36, only `SIGHUP`, `SIGINT`,
/// `SIGTERM` can be monitored. In GLib 2.36, `SIGUSR1` and `SIGUSR2`
/// were added. In GLib 2.54, `SIGWINCH` was added.
///
/// Note that unlike the UNIX default, all sources which have created a
/// watch will be dispatched, regardless of which underlying thread
/// invoked `g_unix_signal_source_new()`.
///
/// For example, an effective use of this function is to handle `SIGTERM`
/// cleanly; flushing any outstanding files, and then calling
/// g_main_loop_quit (). It is not safe to do any of this a regular
/// UNIX signal handler; your handler may be invoked while `malloc()` or
/// another library function is running, causing reentrancy if you
/// attempt to use it from the handler. None of the GLib/GObject API
/// is safe against this kind of reentrancy.
///
/// The interaction of this source when combined with native UNIX
/// functions like `sigprocmask()` is not defined.
///
/// The source will not initially be associated with any [`MainContext`][crate::MainContext]
/// and must be added to one with `g_source_attach()` before it will be
/// executed.
/// ## `signum`
/// A signal number
///
/// # Returns
///
/// A newly created [`Source`][crate::Source]
#[doc(alias = "g_unix_signal_source_new")]
pub fn unix_signal_source_new<F>(
    signum: i32,
    name: Option<&str>,
    priority: Priority,
    func: F,
) -> Source
where
    F: FnMut() -> Continue + Send + 'static,
{
    unsafe {
        let source = ffi::g_unix_signal_source_new(signum);
        ffi::g_source_set_callback(
            source,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        );
        ffi::g_source_set_priority(source, priority.into_glib());

        if let Some(name) = name {
            ffi::g_source_set_name(source, name.to_glib_none().0);
        }

        from_glib_full(source)
    }
}

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX file descriptor reaches the given IO condition.
///
/// `func` will be called repeatedly while the file descriptor matches the given IO condition
/// until it returns `Continue(false)`.
// rustdoc-stripper-ignore-next-stop
/// Creates a [`Source`][crate::Source] to watch for a particular IO condition on a file
/// descriptor.
///
/// The source will never close the fd -- you must do it yourself.
/// ## `fd`
/// a file descriptor
/// ## `condition`
/// IO conditions to watch for on `fd`
///
/// # Returns
///
/// the newly created [`Source`][crate::Source]
#[doc(alias = "g_unix_fd_source_new")]
pub fn unix_fd_source_new<F>(
    fd: RawFd,
    condition: IOCondition,
    name: Option<&str>,
    priority: Priority,
    func: F,
) -> Source
where
    F: FnMut(RawFd, IOCondition) -> Continue + Send + 'static,
{
    unsafe {
        let source = ffi::g_unix_fd_source_new(fd, condition.into_glib());
        ffi::g_source_set_callback(
            source,
            Some(transmute::<
                _,
                unsafe extern "C" fn(ffi::gpointer) -> ffi::gboolean,
            >(trampoline_unix_fd::<F> as *const ())),
            into_raw_unix_fd(func),
            Some(destroy_closure_unix_fd::<F>),
        );
        ffi::g_source_set_priority(source, priority.into_glib());

        if let Some(name) = name {
            ffi::g_source_set_name(source, name.to_glib_none().0);
        }

        from_glib_full(source)
    }
}

impl Source {
    /// Adds a [`Source`][crate::Source] to a `context` so that it will be executed within
    /// that context. Remove it by calling `g_source_destroy()`.
    ///
    /// This function is safe to call from any thread, regardless of which thread
    /// the `context` is running in.
    /// ## `context`
    /// a [`MainContext`][crate::MainContext] (if [`None`], the default context will be used)
    ///
    /// # Returns
    ///
    /// the ID (greater than 0) for the source within the
    ///  [`MainContext`][crate::MainContext].
    #[doc(alias = "g_source_attach")]
    pub fn attach(&self, context: Option<&MainContext>) -> SourceId {
        unsafe {
            from_glib(ffi::g_source_attach(
                self.to_glib_none().0,
                context.to_glib_none().0,
            ))
        }
    }

    /// Removes the source with the given ID from the default main context. You must
    /// use `g_source_destroy()` for sources added to a non-default main context.
    ///
    /// The ID of a [`Source`][crate::Source] is given by `g_source_get_id()`, or will be
    /// returned by the functions `g_source_attach()`, `g_idle_add()`,
    /// `g_idle_add_full()`, `g_timeout_add()`, `g_timeout_add_full()`,
    /// `g_child_watch_add()`, `g_child_watch_add_full()`, `g_io_add_watch()`, and
    /// `g_io_add_watch_full()`.
    ///
    /// It is a programmer error to attempt to remove a non-existent source.
    ///
    /// More specifically: source IDs can be reissued after a source has been
    /// destroyed and therefore it is never valid to use this function with a
    /// source ID which may have already been removed. An example is when
    /// scheduling an idle to run in another thread with `g_idle_add()`: the
    /// idle may already have run and been removed by the time this function
    /// is called on its (now invalid) source ID. This source ID may have
    /// been reissued, leading to the operation being performed against the
    /// wrong source.
    /// ## `tag`
    /// the ID of the source to remove.
    ///
    /// # Returns
    ///
    /// For historical reasons, this function always returns [`true`]
    #[doc(alias = "g_source_remove")]
    pub fn remove(tag: SourceId) -> Result<(), crate::BoolError> {
        unsafe {
            result_from_gboolean!(
                ffi::g_source_remove(tag.as_raw()),
                "Failed to remove source"
            )
        }
    }
}