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
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
use crate::error::{self, ProtocolError};
use crate::event::{self, Event};
use crate::ext::{Extension, ExtensionData};
#[cfg(feature = "present")]
use crate::present;
use crate::x::{Atom, Keysym, Setup, Timestamp};
#[cfg(feature = "xinput")]
use crate::xinput;
use crate::{cache_extensions_data, ffi::*};

#[cfg(feature = "xlib_xcb")]
use x11::xlib;

use bitflags::bitflags;

use libc::{c_char, c_int};

use std::cell::RefCell;
use std::ffi::{CStr, CString};
use std::fmt::{self, Display, Formatter};
use std::marker::{self, PhantomData};
use std::mem;
use std::os::unix::prelude::{AsRawFd, RawFd};
use std::ptr;
use std::result;
use std::slice;

/// A X resource trait
pub trait Xid {
    /// Build a null X resource
    fn none() -> Self;

    /// Get the underlying id of the resource
    fn resource_id(&self) -> u32;

    /// Check whether this resource is null or not
    fn is_none(&self) -> bool {
        self.resource_id() == 0
    }
}

/// Trait for X resources that can be created directly from `Connection::generate_id`
///
/// The resources that cannot be created that way are the Xid unions, which are created
/// from their underlying resource.
pub trait XidNew: Xid {
    /// Build a new X resource
    ///
    /// # Safety
    /// res_id must be obtained from `xcb_generate_id`. `0` is also a valid value to create a null resource.
    /// Users should not use this function directly but rather use
    /// `Connection::generate_id`
    unsafe fn new(res_id: u32) -> Self;
}

/// Trait for base events (aka. non GE_GENERIC events)
pub trait BaseEvent {
    /// The extension associated to this event, or `None` for the main protocol
    const EXTENSION: Option<Extension>;

    /// The number associated to this event
    const NUMBER: u32;

    /// Build an event from a raw pointer
    ///
    /// # Safety
    /// `raw` must be a valid pointer to the event, and be allocated with `libc::malloc`
    unsafe fn from_raw(raw: *mut xcb_generic_event_t) -> Self;

    /// Convert the event into a raw pointer
    ///
    /// # Safety
    /// returned value should be freed with `libc::free` to avoid memory leak, or used to build a new event
    unsafe fn into_raw(self) -> *mut xcb_generic_event_t;

    /// Obtain the event as a raw pointer
    fn as_raw(&self) -> *mut xcb_generic_event_t;

    /// Access to the raw event data
    fn as_slice(&self) -> &[u8];
}

/// A trait for GE_GENERIC events
///
/// A GE_GENERIC event is an extension event that does not follow
/// the regular `response_type` offset.
/// This system was introduced because the protocol eventually run
/// out of event numbers.
///
/// This should be completely transparent to the user, as [Event] is
/// resolving all types of events together.
pub trait GeEvent {
    /// The extension associated to this event
    const EXTENSION: Extension;

    /// The number associated to this event
    const NUMBER: u32;

    /// Build an event from a raw pointer
    ///
    /// # Safety
    /// `raw` must be a valid pointer to the event, and be allocated with `libc::malloc`
    unsafe fn from_raw(raw: *mut xcb_ge_generic_event_t) -> Self;

    /// Convert the event into a raw pointer
    ///
    /// # Safety
    /// returned value should be freed with `libc::free` to avoid memory leak, or used to build a new event
    unsafe fn into_raw(self) -> *mut xcb_ge_generic_event_t;

    /// Obtain the event as a raw pointer
    fn as_raw(&self) -> *mut xcb_ge_generic_event_t;

    /// Access to the raw event data
    fn as_slice(&self) -> &[u8];
}

/// A trait to designate base protocol errors.
///
/// The base errors follow the usual resolution idiom of `error_code` offset.
///
/// This should be completely transparent to the user, as [ProtocolError] is
/// resolving all types of errors together.
pub trait BaseError {
    /// The extension associated to this error, or `None` for the main protocol
    const EXTENSION: Option<Extension>;

    /// The number associated to this error
    const NUMBER: u32;

    /// Build an error from a raw pointer
    ///
    /// # Safety
    /// `raw` must be a valid pointer to the error, and be allocated with `libc::malloc`
    unsafe fn from_raw(raw: *mut xcb_generic_error_t) -> Self;

    /// Convert the error into a raw pointer
    ///
    /// # Safety
    /// returned value should be freed with `libc::free` to avoid memory leak, or used to build a new error
    unsafe fn into_raw(self) -> *mut xcb_generic_error_t;

    /// Obtain the error as a raw pointer
    fn as_raw(&self) -> *mut xcb_generic_error_t;

    /// Access to the raw error data
    fn as_slice(&self) -> &[u8];
}

/// Trait for the resolution of raw wire event to a unified event enum.
///
/// `Self` is normally an enum of several event subtypes.
/// See [crate::x::Event] and [crate::Event]
pub trait ResolveWireEvent: Sized {
    /// Resolve a pointer to `xcb_generic_event_t` to `Self`, inferring the correct subtype
    /// using `response_type` field and `first_event`
    ///
    /// # Panics
    /// Panics if the event subtype cannot be resolved to `Self`. That is,
    /// `response_type` field must be checked beforehand to be in range with
    /// `first_event`.
    ///
    /// # Safety
    /// `event` must be a valid, non-null event returned by `xcb_wait_for_event`
    /// or similar function
    unsafe fn resolve_wire_event(first_event: u8, event: *mut xcb_generic_event_t) -> Self;
}

/// Trait for the resolution of raw wire GE_GENERIC event to a unified event enum.
///
/// `Self` is normally an enum of several event subtypes.
/// See [crate::xinput::Event] and [crate::Event]
pub trait ResolveWireGeEvent: Sized {
    /// Resolve a pointer to `xcb_ge_generic_event_t` to `Self`, inferring the correct subtype
    /// using `event_type` field.
    ///
    /// # Panics
    /// Panics if the event subtype cannot be resolved for `Self`. That is, `event_type`
    /// must be checked beforehand to be in range.
    ///
    /// # Safety
    /// `event` must be a valid, non-null event returned by `xcb_wait_for_event`
    /// or similar function
    unsafe fn resolve_wire_ge_event(event: *mut xcb_ge_generic_event_t) -> Self;
}

/// Trait for the resolution of raw wire error to a unified error enum.
///
/// `Self` is normally an enum of several event subtypes.
/// See [crate::x::Error] and [crate::ProtocolError]
pub trait ResolveWireError {
    /// Convert a pointer to `xcb_generic_error_t` to `Self`, inferring the correct subtype
    /// using `response_type` field and `first_error`.
    ///
    /// # Panics
    /// Panics if the error subtype cannot be resolved for `self`. That is,
    /// `response_type` field must be checked beforehand to be in range with
    /// `first_error`.
    ///
    /// # Safety
    /// `err` must be a valid, non-null error obtained by `xcb_wait_for_reply`
    /// or similar function
    unsafe fn resolve_wire_error(first_error: u8, error: *mut xcb_generic_error_t) -> Self;
}

/// Trait for types that can serialize themselves over the X wire.
///
/// This trait is used internally for requests serialization, or in some accessors
/// that have to compute the size of some wire data.
pub trait Wired {
    /// type to external context necessary to compute the length
    type Params: Copy;

    /// Compute the length of serialized data of an instance starting by `ptr`.
    ///
    /// # Safety
    /// This function is highly unsafe as the pointer must point to data that is a valid
    /// wired representation of `Self`. Failure to respect this will lead to reading
    /// of invalid memory.
    unsafe fn compute_wire_len(ptr: *const u8, params: Self::Params) -> usize;

    /// Compute the length of wired serialized data of self
    fn wire_len(&self) -> usize;

    /// Serialize `self` over the X wire and returns how many bytes were written.
    ///
    /// `wire_buf` must be larger or as long as the value returned by `wire_len`.
    /// `serialize` MUST write the data in its entirety at once, at the begining of `wire_buf`.
    /// That is, it returns the same value as `wire_len`.
    /// The interest in returning the value is that it is easy to compute in `serialize` and allow
    /// to easily chain serialization of fields in a struct.
    ///
    /// # Panics
    /// Panics if `wire_buf` is too small to contain the serialized representation of `self`.
    fn serialize(&self, wire_buf: &mut [u8]) -> usize;
}

macro_rules! impl_wired_simple {
    ($typ:ty) => {
        impl Wired for $typ {
            type Params = ();

            unsafe fn compute_wire_len(_ptr: *const u8, _params: Self::Params) -> usize {
                mem::size_of::<Self>()
            }

            fn wire_len(&self) -> usize {
                mem::size_of::<Self>()
            }

            fn serialize(&self, wire_buf: &mut [u8]) -> usize {
                debug_assert!(wire_buf.len() >= mem::size_of::<Self>());
                unsafe {
                    *(wire_buf.as_mut_ptr() as *mut Self) = *self;
                }
                mem::size_of::<Self>()
            }
        }
    };
}

impl_wired_simple!(u8);
impl_wired_simple!(u16);
impl_wired_simple!(u32);
impl_wired_simple!(u64);
impl_wired_simple!(i8);
impl_wired_simple!(i16);
impl_wired_simple!(i32);
impl_wired_simple!(f32);

impl<T: Xid> Wired for T {
    type Params = ();

    unsafe fn compute_wire_len(_ptr: *const u8, _params: Self::Params) -> usize {
        4
    }

    fn wire_len(&self) -> usize {
        4
    }

    fn serialize(&self, wire_buf: &mut [u8]) -> usize {
        debug_assert!(wire_buf.len() >= 4);
        unsafe {
            *(wire_buf.as_mut_ptr() as *mut u32) = self.resource_id();
        }
        4
    }
}

/// Trait for request replies
pub trait Reply {
    /// Build the reply struct from a raw pointer.
    ///
    /// # Safety
    /// `raw` must be a pointer to a valid wire representation of `Self`, allocated with [`libc::malloc`].
    unsafe fn from_raw(raw: *const u8) -> Self;

    /// Consume the reply struct into a raw pointer.
    ///
    /// # Safety
    /// The returned pointer must be freed with [`libc::free`] to avoid any memory leak, or be used
    /// to build another reply.
    unsafe fn into_raw(self) -> *const u8;
}

/// General trait for cookies returned by requests.
pub trait Cookie {
    /// # Safety
    /// `seq` must be a valid cookie for a given `Request` or `Reply`.
    unsafe fn from_sequence(seq: u64) -> Self;

    /// The raw sequence number associated with the cookie.
    fn sequence(&self) -> u64;
}

/// A marker trait for a cookie that allows synchronized error checking.
///
/// # Safety
/// Cookies not implementing this trait acknowledge that the error is sent to the event loop
///
/// See also [Connection::send_request], [Connection::send_request_checked] and [Connection::check_request]
pub unsafe trait CookieChecked: Cookie {}

/// A trait for checked cookies of requests that send a reply.
///
/// # Safety
/// Cookies implementing this trait acknowledge that their error is checked when the reply is fetched from the server.
/// This is the default cookie type for requests with reply.
///
/// See also [Connection::send_request], [Connection::wait_for_reply]
pub unsafe trait CookieWithReplyChecked: CookieChecked {
    /// The reply type associated with the cookie
    type Reply: Reply;
}

/// A trait for unchecked cookies of requests that send a reply.
///
/// # Safety
/// Cookies implementing this trait acknowledge that their error is not checked when the reply is fetched from the server
/// but in the event loop.
///
/// See also [Connection::send_request_unchecked], [Connection::wait_for_event]
pub unsafe trait CookieWithReplyUnchecked: Cookie {
    /// The reply type associated with the cookie
    type Reply: Reply;
}

/// The default cookie type returned by void-requests.
///
/// See [Connection::send_request]
#[derive(Debug)]
pub struct VoidCookie {
    seq: u64,
}

impl Cookie for VoidCookie {
    unsafe fn from_sequence(seq: u64) -> Self {
        VoidCookie { seq }
    }

    fn sequence(&self) -> u64 {
        self.seq
    }
}

/// The checked cookie type returned by void-requests.
///
/// See [Connection::send_request_checked]
#[derive(Debug)]
pub struct VoidCookieChecked {
    seq: u64,
}

impl Cookie for VoidCookieChecked {
    unsafe fn from_sequence(seq: u64) -> Self {
        VoidCookieChecked { seq }
    }

    fn sequence(&self) -> u64 {
        self.seq
    }
}

unsafe impl CookieChecked for VoidCookieChecked {}

/// Trait implemented by all requests to send the serialized data over the wire.
///
/// # Safety
/// Types implementing this trait acknowledge that the returned value of `raw_request` correspond
/// to a cookie for `Self` request and is checked or unchecked depending on the `checked` flag value.
pub unsafe trait RawRequest {
    /// Actual implementation of the request sending
    ///
    /// Send the request over the `conn` wire and return a cookie sequence fitting with the `checked` flag
    /// of `Self`
    fn raw_request(&self, conn: &Connection, checked: bool) -> u64;
}

/// Trait implemented by requests types.
///
/// See [crate::x::CreateWindow] as an example.
pub trait Request: RawRequest {
    /// The default cookie associated to this request.
    type Cookie: Cookie;

    /// `false` if the request returns a reply, `true` otherwise.
    const IS_VOID: bool;
}

/// Marker trait for requests that do not return a reply.
///
/// These trait is implicitely associated with [`VoidCookie`] and [`VoidCookieChecked`].
pub trait RequestWithoutReply: Request {}

/// Trait for requests that return a reply.
pub trait RequestWithReply: Request {
    /// Reply associated with the request
    type Reply: Reply;
    /// Default cookie type for the request, as returned by [Connection::send_request].
    type Cookie: CookieWithReplyChecked<Reply = Self::Reply>;
    /// Unchecked cookie type for the request, as returned by [Connection::send_request_unchecked].
    type CookieUnchecked: CookieWithReplyUnchecked<Reply = Self::Reply>;
}

/// Determines whether Xlib or XCB owns the event queue of [`Connection`].
///
/// See [`Connection::set_event_queue_owner`].
#[cfg(feature = "xlib_xcb")]
#[derive(Debug)]
pub enum EventQueueOwner {
    /// XCB owns the event queue
    Xcb,
    /// Xlib owns the event queue
    Xlib,
}

/// Container for authentication information to connect to the X server
///
/// See [Connection::connect_to_display_with_auth_info] and [Connection::connect_to_fd].
#[derive(Copy, Clone, Debug)]
pub struct AuthInfo<'a> {
    /// String containing the authentication protocol name,
    /// such as "MIT-MAGIC-COOKIE-1" or "XDM-AUTHORIZATION-1".
    pub name: &'a str,
    /// data interpreted in a protocol specific manner
    pub data: &'a str,
}

/// Display info returned by [`parse_display`]
#[derive(Debug)]
pub struct DisplayInfo {
    /// The hostname
    host: String,
    /// The display number
    display: i32,
    /// The screen number
    screen: i32,
}

/// Parses a display string in the form documented by [X (7x)](https://linux.die.net/man/7/x).
///
/// Returns `Some(DisplayInfo)` on success and `None` otherwise.
/// Has no side effects on failure.
///
/// If `name` empty, it uses the environment variable `DISPLAY`.
///
/// If `name` does not contain a screen number, `DisplayInfo::screen` is set to `0`.
pub fn parse_display(name: &str) -> Option<DisplayInfo> {
    unsafe {
        let name = CString::new(name).unwrap();
        let mut hostp: *mut c_char = ptr::null_mut();
        let mut display = 0i32;
        let mut screen = 0i32;

        let success = xcb_parse_display(
            name.as_ptr(),
            &mut hostp as *mut _,
            &mut display as *mut _,
            &mut screen as *mut _,
        );

        if success != 0 {
            let host = CStr::from_ptr(hostp as *const _)
                .to_str()
                .unwrap()
                .to_string();

            libc::free(hostp as *mut _);

            Some(DisplayInfo {
                host,
                display,
                screen,
            })
        } else {
            None
        }
    }
}

/// A struct that serve as an identifier for internal special queue in XCB
///
/// See [Connection::register_for_special_xge].
#[cfg(any(feature = "xinput", feature = "present"))]
#[derive(Debug)]
pub struct SpecialEventId {
    raw: *mut xcb_special_event_t,
    stamp: Timestamp,
}

#[cfg(any(feature = "xinput", feature = "present"))]
impl SpecialEventId {
    /// The X timestamp associated with this special event Id
    pub fn stamp(&self) -> Timestamp {
        self.stamp
    }
}

/// Error type that is returned by `Connection::has_error`.
#[derive(Debug)]
pub enum ConnError {
    /// xcb connection errors because of socket, pipe and other stream errors.
    Connection,
    /// xcb connection shutdown because of extension not supported
    ClosedExtNotSupported,
    /// malloc(), calloc() and realloc() error upon failure, for eg ENOMEM
    ClosedMemInsufficient,
    /// Connection closed, exceeding request length that server accepts.
    ClosedReqLenExceed,
    /// Connection closed, error during parsing display string.
    ClosedParseErr,
    /// Connection closed because the server does not have a screen
    /// matching the display.
    ClosedInvalidScreen,
}

impl ConnError {
    fn to_str(&self) -> &str {
        match *self {
            ConnError::Connection => "Connection error, possible I/O error",
            ConnError::ClosedExtNotSupported => "Connection closed, X extension not supported",
            ConnError::ClosedMemInsufficient => "Connection closed, insufficient memory",
            ConnError::ClosedReqLenExceed => {
                "Connection closed, exceeded request length that server accepts."
            }
            ConnError::ClosedParseErr => "Connection closed, error during parsing display string",
            ConnError::ClosedInvalidScreen => {
                "Connection closed, the server does not have a screen matching the display"
            }
        }
    }
}

impl Display for ConnError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.to_str().fmt(f)
    }
}

impl std::error::Error for ConnError {
    fn description(&self) -> &str {
        self.to_str()
    }
}

/// The result type associated with [ConnError].
pub type ConnResult<T> = result::Result<T, ConnError>;

/// The result type associated with [ProtocolError].
pub type ProtocolResult<T> = result::Result<T, ProtocolError>;

/// The general error type for Rust-XCB.
#[derive(Debug)]
pub enum Error {
    /// I/O error issued from the connection.
    Connection(ConnError),
    /// A protocol related error issued by the X server.
    Protocol(ProtocolError),
}

impl From<ConnError> for Error {
    fn from(err: ConnError) -> Error {
        Error::Connection(err)
    }
}

impl From<ProtocolError> for Error {
    fn from(err: ProtocolError) -> Error {
        Error::Protocol(err)
    }
}

/// The general result type for Rust-XCB.
pub type Result<T> = result::Result<T, Error>;

/// `Connection` is the central object of XCB.
///
/// It handles all communications with the X server.
/// It dispatches the requests, receives the replies, poll/wait the events.
/// It also resolves the errors and events from X server.
///
/// `Connection` is thread safe.
///
/// It internally wraps an `xcb_connection_t` object and
/// will call `xcb_disconnect` when the `Connection` goes out of scope.
pub struct Connection {
    c: *mut xcb_connection_t,

    #[cfg(feature = "xlib_xcb")]
    dpy: *mut xlib::Display,

    ext_data: Vec<ExtensionData>,

    // Following field is used to handle the
    // rare (if existing) cases of multiple connections
    // per application.
    // Only the first established connections is used
    // to print the name of atoms during Debug
    #[cfg(feature = "debug_atom_names")]
    dbg_atom_names: bool,
}

unsafe impl Send for Connection {}
unsafe impl Sync for Connection {}

impl Connection {
    /// Connects to the X server.
    ///
    /// Connects to the X server specified by `display_name.` If
    /// `display_name` is `None,` uses the value of the `DISPLAY` environment
    /// variable.
    ///
    /// If no screen is preferred, the second member of the tuple is set to 0.
    ///
    /// # Example
    /// ```no_run
    /// fn main() -> xcb::Result<()> {
    ///     let (conn, screen) = xcb::Connection::connect(None)?;
    ///     Ok(())
    /// }
    /// ```
    pub fn connect(display_name: Option<&str>) -> ConnResult<(Connection, i32)> {
        Self::connect_with_extensions(display_name, &[], &[])
    }

    /// Connects to the X server and cache extension data.
    ///
    /// Connects to the X server specified by `display_name.` If
    /// `display_name` is `None,` uses the value of the `DISPLAY` environment
    /// variable.
    ///
    /// Extension data specified by `mandatory` and `optional` is cached to allow
    /// the resolution of events and errors in these extensions.
    ///
    /// If no screen is preferred, the second member of the tuple is set to 0.
    ///
    /// # Panics
    /// Panics if one of the mandatory extension is not present.
    ///
    /// # Example
    /// ```no_run
    /// fn main() -> xcb::Result<()> {
    ///     let (conn, screen) = xcb::Connection::connect_with_extensions(
    ///         None, &[xcb::Extension::Input, xcb::Extension::Xkb], &[]
    ///     )?;
    ///     Ok(())
    /// }
    /// ```
    pub fn connect_with_extensions(
        display_name: Option<&str>,
        mandatory: &[Extension],
        optional: &[Extension],
    ) -> ConnResult<(Connection, i32)> {
        let mut screen_num: c_int = 0;
        let displayname = display_name.map(|s| CString::new(s).unwrap());
        unsafe {
            let conn = if let Some(display) = displayname {
                xcb_connect(display.as_ptr(), &mut screen_num)
            } else {
                xcb_connect(ptr::null(), &mut screen_num)
            };

            check_connection_error(conn)?;

            let conn = Self::from_raw_conn_and_extensions(conn, mandatory, optional);
            conn.has_error().map(|_| (conn, screen_num as i32))
        }
    }

    /// Open a new connection with Xlib.
    ///
    /// The event queue owner defaults to Xlib.
    /// One would need to open an XCB connection with Xlib in order to use
    /// OpenGL.
    #[cfg(feature = "xlib_xcb")]
    pub fn connect_with_xlib_display() -> ConnResult<(Connection, i32)> {
        unsafe {
            let dpy = xlib::XOpenDisplay(ptr::null());

            check_connection_error(XGetXCBConnection(dpy))?;

            let conn = Self::from_xlib_display(dpy);

            conn.has_error()
                .map(|_| (conn, xlib::XDefaultScreen(dpy) as i32))
        }
    }

    /// Open a new connection with Xlib and cache the provided extensions data.
    ///
    /// Data of extensions specified by `mandatory` and `optional` is cached to allow
    /// the resolution of events and errors in these extensions.
    ///
    /// The event queue owner defaults to Xlib.
    /// One would need to open an XCB connection with Xlib in order to use
    /// OpenGL.
    ///
    /// # Panics
    /// Panics if one of the mandatory extension is not present.
    #[cfg(feature = "xlib_xcb")]
    pub fn connect_with_xlib_display_and_extensions(
        mandatory: &[Extension],
        optional: &[Extension],
    ) -> ConnResult<(Connection, i32)> {
        unsafe {
            let dpy = xlib::XOpenDisplay(ptr::null());

            check_connection_error(XGetXCBConnection(dpy))?;

            let conn = Self::from_xlib_display_and_extensions(dpy, mandatory, optional);

            conn.has_error()
                .map(|_| (conn, xlib::XDefaultScreen(dpy) as i32))
        }
    }

    /// Connects to the X server with an open socket file descriptor and optional authentification info.
    ///
    /// Connects to an X server, given the open socket fd and the
    /// `auth_info`. The file descriptor `fd` is bidirectionally connected to an X server.
    /// If the connection should be unauthenticated, `auth_info` must be `None`.
    pub fn connect_to_fd(fd: RawFd, auth_info: Option<AuthInfo<'_>>) -> ConnResult<Self> {
        Self::connect_to_fd_with_extensions(fd, auth_info, &[], &[])
    }

    /// Connects to the X server with an open socket file descriptor and optional authentification info.
    ///
    /// Extension data specified by `mandatory` and `optional` is cached to allow
    /// the resolution of events and errors in these extensions.
    ///
    /// Connects to an X server, given the open socket fd and the
    /// `auth_info`. The file descriptor `fd` is bidirectionally connected to an X server.
    /// If the connection should be unauthenticated, `auth_info` must be `None`.
    ///
    /// # Panics
    /// Panics if one of the mandatory extension is not present.
    pub fn connect_to_fd_with_extensions(
        fd: RawFd,
        auth_info: Option<AuthInfo<'_>>,
        mandatory: &[Extension],
        optional: &[Extension],
    ) -> ConnResult<Self> {
        let mut auth_info = auth_info.map(|auth_info| {
            let auth_name = CString::new(auth_info.name).unwrap();
            let auth_data = CString::new(auth_info.data).unwrap();

            let auth_info = xcb_auth_info_t {
                namelen: auth_name.as_bytes().len() as _,
                name: auth_name.as_ptr() as *mut _,
                datalen: auth_data.as_bytes().len() as _,
                data: auth_data.as_ptr() as *mut _,
            };
            // return the strings too otherwise they would drop
            (auth_info, auth_name, auth_data)
        });

        let ai_ptr = if let Some(auth_info) = auth_info.as_mut() {
            &mut auth_info.0 as *mut _
        } else {
            ptr::null_mut()
        };

        let conn = unsafe {
            let conn = xcb_connect_to_fd(fd, ai_ptr);
            check_connection_error(conn)?;

            Self::from_raw_conn_and_extensions(conn, mandatory, optional)
        };

        conn.has_error().map(|_| conn)
    }

    /// Connects to the X server, using an authorization information.
    ///
    /// Connects to the X server specified by `display_name`, using the
    /// authorization `auth_info`. If a particular screen on that server, it is
    /// returned in the second tuple member, which is otherwise set to `0`.
    pub fn connect_to_display_with_auth_info(
        display_name: Option<&str>,
        auth_info: AuthInfo<'_>,
    ) -> ConnResult<(Connection, i32)> {
        Self::connect_to_display_with_auth_info_and_extensions(display_name, auth_info, &[], &[])
    }

    /// Connects to the X server, using an authorization information.
    ///
    /// Extension data specified by `mandatory` and `optional` is cached to allow
    /// the resolution of events and errors in these extensions.
    ///
    /// Connects to the X server specified by `display_name`, using the
    /// authorization `auth_info`. If a particular screen on that server, it is
    /// returned in the second tuple member, which is otherwise set to `0`.
    ///
    /// # Panics
    /// Panics if one of the mandatory extension is not present.
    pub fn connect_to_display_with_auth_info_and_extensions(
        display_name: Option<&str>,
        auth_info: AuthInfo<'_>,
        mandatory: &[Extension],
        optional: &[Extension],
    ) -> ConnResult<(Connection, i32)> {
        let mut screen_num: c_int = 0;
        let display_name = display_name.map(|s| CString::new(s).unwrap());

        unsafe {
            let display_name = if let Some(display_name) = &display_name {
                display_name.as_ptr()
            } else {
                ptr::null()
            };

            let auth_name = CString::new(auth_info.name).unwrap();
            let auth_data = CString::new(auth_info.data).unwrap();

            let mut auth_info = xcb_auth_info_t {
                namelen: auth_name.as_bytes().len() as _,
                name: auth_name.as_ptr() as *mut _,
                datalen: auth_data.as_bytes().len() as _,
                data: auth_data.as_ptr() as *mut _,
            };

            let conn = xcb_connect_to_display_with_auth_info(
                display_name,
                &mut auth_info as *mut _,
                &mut screen_num as *mut _,
            );

            check_connection_error(conn)?;

            let conn = Self::from_raw_conn_and_extensions(conn, mandatory, optional);
            conn.has_error().map(|_| (conn, screen_num as i32))
        }
    }

    /// builds a new Connection object from an available connection
    ///
    /// # Safety
    /// The `conn` pointer must point to a valid `xcb_connection_t`
    pub unsafe fn from_raw_conn(conn: *mut xcb_connection_t) -> Connection {
        Self::from_raw_conn_and_extensions(conn, &[], &[])
    }

    /// Builds a new `Connection` object from an available connection and cache the extension data
    ///
    /// Extension data specified by `mandatory` and `optional` is cached to allow
    /// the resolution of events and errors in these extensions.
    ///
    /// # Panics
    /// Panics if the connection is null or in error state.
    /// Panics if one of the mandatory extension is not present.
    ///
    /// # Safety
    /// The `conn` pointer must point to a valid `xcb_connection_t`
    pub unsafe fn from_raw_conn_and_extensions(
        conn: *mut xcb_connection_t,
        mandatory: &[Extension],
        optional: &[Extension],
    ) -> Connection {
        assert!(!conn.is_null());
        assert!(check_connection_error(conn).is_ok());

        #[cfg(feature = "debug_atom_names")]
        let dbg_atom_names = {
            if dan::DAN_CONN.is_null() {
                dan::DAN_CONN = conn;
                true
            } else {
                false
            }
        };

        let ext_data = cache_extensions_data(conn, mandatory, optional);

        #[cfg(not(feature = "xlib_xcb"))]
        #[cfg(not(feature = "debug_atom_names"))]
        return Connection { c: conn, ext_data };

        #[cfg(not(feature = "xlib_xcb"))]
        #[cfg(feature = "debug_atom_names")]
        return Connection {
            c: conn,
            ext_data,
            dbg_atom_names,
        };

        #[cfg(feature = "xlib_xcb")]
        #[cfg(not(feature = "debug_atom_names"))]
        return Connection {
            c: conn,
            dpy: ptr::null_mut(),
            ext_data,
        };

        #[cfg(feature = "xlib_xcb")]
        #[cfg(feature = "debug_atom_names")]
        return Connection {
            c: conn,
            dpy: ptr::null_mut(),
            ext_data,
            dbg_atom_names,
        };
    }

    /// Initialize a new `Connection` from an existing Xlib display.
    ///
    /// Wraps a `xlib::Display` and get an XCB connection from an exisiting object
    /// `xlib::XCloseDisplay` will be called when the returned object is dropped.
    ///
    /// # Safety
    /// The `dpy` pointer must be a pointer to a valid `xlib::Display`
    #[cfg(feature = "xlib_xcb")]
    pub unsafe fn from_xlib_display(dpy: *mut xlib::Display) -> Connection {
        Self::from_xlib_display_and_extensions(dpy, &[], &[])
    }

    /// Initialize a new `Connection` from an existing Xlib display.
    ///
    /// Wraps a `xlib::Display` and get an XCB connection from an exisiting object
    /// `xlib::XCloseDisplay` will be called when the returned object is dropped.
    ///
    /// Extension data specified by `mandatory` and `optional` is cached to allow
    /// the resolution of events and errors in these extensions.
    ///
    /// # Panics
    /// Panics if the connection is null or in error state.
    ///
    /// # Safety
    /// The `dpy` pointer must be a pointer to a valid `xlib::Display`.
    #[cfg(feature = "xlib_xcb")]
    pub unsafe fn from_xlib_display_and_extensions(
        dpy: *mut xlib::Display,
        mandatory: &[Extension],
        optional: &[Extension],
    ) -> Connection {
        assert!(!dpy.is_null(), "attempt connect with null display");
        let c = XGetXCBConnection(dpy);

        assert!(check_connection_error(c).is_ok());

        #[cfg(feature = "debug_atom_names")]
        let dbg_atom_names = {
            if dan::DAN_CONN.is_null() {
                dan::DAN_CONN = c;
                true
            } else {
                false
            }
        };

        let ext_data = cache_extensions_data(c, mandatory, optional);

        #[cfg(feature = "debug_atom_names")]
        return Connection {
            c,
            dpy,
            ext_data,
            dbg_atom_names,
        };

        #[cfg(not(feature = "debug_atom_names"))]
        return Connection { c, dpy, ext_data };
    }

    /// Get the extensions activated for this connection.
    ///
    /// You may use this to check if an optional extension is present or not.
    ///
    /// # Example
    /// ```no_run
    /// # fn main() -> xcb::Result<()> {
    ///     // Xkb is mandatory, Input is optional
    ///     let (conn, screen) = xcb::Connection::connect_with_extensions(
    ///         None, &[xcb::Extension::Xkb], &[xcb::Extension::Input]
    ///     )?;
    ///     // now we check if Input is present or not
    ///     let has_input_ext = conn.active_extensions().any(|e| e == xcb::Extension::Input);
    /// #   Ok(())
    /// # }
    /// ```
    pub fn active_extensions(&self) -> impl Iterator<Item = Extension> + '_ {
        self.ext_data.iter().map(|eed| eed.ext)
    }

    /// Returns the inner ffi `xcb_connection_t` pointer
    pub fn get_raw_conn(&self) -> *mut xcb_connection_t {
        self.c
    }

    /// Consumes this object, returning the inner ffi `xcb_connection_t` pointer
    pub fn into_raw_conn(self) -> *mut xcb_connection_t {
        let c = self.c;
        mem::forget(self);
        c
    }

    /// Returns the inner ffi `xlib::Display` pointer.
    #[cfg(feature = "xlib_xcb")]
    pub fn get_raw_dpy(&self) -> *mut xlib::Display {
        self.dpy
    }

    /// Sets the owner of the event queue in the case if the connection is opened
    /// with the Xlib interface. In that case, the default owner is Xlib.
    #[cfg(feature = "xlib_xcb")]
    pub fn set_event_queue_owner(&self, owner: EventQueueOwner) {
        debug_assert!(!self.dpy.is_null());
        unsafe {
            XSetEventQueueOwner(
                self.dpy,
                match owner {
                    EventQueueOwner::Xcb => XCBOwnsEventQueue,
                    EventQueueOwner::Xlib => XlibOwnsEventQueue,
                },
            );
        }
    }

    /// Returns the maximum request length that this server accepts.
    ///
    /// In the absence of the BIG-REQUESTS extension, returns the
    /// maximum request length field from the connection setup data, which
    /// may be as much as 65535. If the server supports BIG-REQUESTS, then
    /// the maximum request length field from the reply to the
    /// BigRequestsEnable request will be returned instead.
    ///
    /// Note that this length is measured in four-byte units, making the
    /// theoretical maximum lengths roughly 256kB without BIG-REQUESTS and
    /// 16GB with.
    pub fn get_maximum_request_length(&self) -> u32 {
        unsafe { xcb_get_maximum_request_length(self.c) }
    }

    /// Prefetch the maximum request length without blocking.
    ///
    /// Without blocking, does as much work as possible toward computing
    /// the maximum request length accepted by the X server.
    ///
    /// Invoking this function may send the [crate::bigreq::Enable] request,
    /// but will not block waiting for the reply.
    /// [Connection::get_maximum_request_length] will return the prefetched data
    /// after possibly blocking while the reply is retrieved.
    ///
    /// Note that in order for this function to be fully non-blocking, the
    /// application must previously have called [crate::bigreq::prefetch_extension_data].
    pub fn prefetch_maximum_request_length(&self) {
        unsafe {
            xcb_prefetch_maximum_request_length(self.c);
        }
    }

    /// Allocates an XID for a new object.
    ///
    /// Returned value is typically used in requests such as `CreateWindow`.
    ///
    /// # Example
    /// ```no_run
    /// # use xcb::x;
    /// # fn main() -> xcb::Result<()> {
    /// # let conn = xcb::Connection::connect(None)?.0;
    /// let window: x::Window = conn.generate_id();
    /// # Ok(())
    /// # }
    /// ```
    pub fn generate_id<T: XidNew>(&self) -> T {
        unsafe { XidNew::new(xcb_generate_id(self.c)) }
    }

    /// Forces any buffered output to be written to the server.
    ///
    /// Forces any buffered output to be written to the server. Blocks
    /// until the write is complete.
    ///
    /// There are several occasions ones want to flush the connection.
    /// One of them is before entering or re-entering the event loop after performing unchecked requests.
    pub fn flush(&self) -> ConnResult<()> {
        unsafe {
            let ret = xcb_flush(self.c);
            if ret > 0 {
                Ok(())
            } else {
                self.has_error()?;
                unreachable!()
            }
        }
    }

    unsafe fn handle_wait_for_event(&self, ev: *mut xcb_generic_event_t) -> Result<Event> {
        if ev.is_null() {
            self.has_error()?;
            panic!("xcb_wait_for_event returned null with I/O error");
        } else if is_error(ev) {
            Err(error::resolve_error(ev as *mut _, &self.ext_data).into())
        } else {
            Ok(event::resolve_event(ev, &self.ext_data))
        }
    }

    unsafe fn handle_poll_for_event(&self, ev: *mut xcb_generic_event_t) -> Result<Option<Event>> {
        if ev.is_null() {
            self.has_error()?;
            Ok(None)
        } else if is_error(ev) {
            Err(error::resolve_error(ev as *mut _, &self.ext_data).into())
        } else {
            Ok(Some(event::resolve_event(ev, &self.ext_data)))
        }
    }

    /// Blocks and returns the next event or error from the server.
    ///
    /// # Example
    /// ```no_run
    /// use xcb::x;
    /// fn main() -> xcb::Result<()> {
    /// #   let conn = xcb::Connection::connect(None)?.0;
    ///     // ...
    ///     loop {
    ///         let event = match conn.wait_for_event() {
    ///             Err(xcb::Error::Connection(err)) => {
    ///                 panic!("unexpected I/O error: {}", err);
    ///             }
    ///             Err(xcb::Error::Protocol(xcb::ProtocolError::X(x::Error::Font(err), _req_name))) => {
    ///                 // may be this particular error is fine?
    ///                 continue;
    ///             }
    ///             Err(xcb::Error::Protocol(err)) => {
    ///                 panic!("unexpected protocol error: {:#?}", err);
    ///             }
    ///             Ok(event) => event,
    ///         };
    ///         match event {
    ///             xcb::Event::X(x::Event::KeyPress(ev)) => {
    ///                 // do stuff with the key press
    ///             }
    ///             // handle other events
    ///             _ => {
    ///                 break Ok(());
    ///             }
    ///         }
    ///     }
    ///  }
    /// ```
    pub fn wait_for_event(&self) -> Result<Event> {
        unsafe {
            let ev = xcb_wait_for_event(self.c);
            self.handle_wait_for_event(ev)
        }
    }

    /// Returns the next event or error from the server without blocking.
    ///
    /// Returns the next event or error from the server, if one is
    /// available. If no event is available, that
    /// might be because an I/O error like connection close occurred while
    /// attempting to read the next event, in which case the connection is
    /// shut down when this function returns.
    pub fn poll_for_event(&self) -> Result<Option<Event>> {
        unsafe {
            let ev = xcb_poll_for_event(self.c);
            self.handle_poll_for_event(ev)
        }
    }

    /// Returns the next event without reading from the connection.
    ///
    /// This is a version of [Connection::poll_for_event] that only examines the
    /// event queue for new events. The function doesn't try to read new
    /// events from the connection if no queued events are found.
    ///
    /// This function is useful for callers that know in advance that all
    /// interesting events have already been read from the connection. For
    /// example, callers might use [Connection::wait_for_reply] and be interested
    /// only of events that preceded a specific reply.
    pub fn poll_for_queued_event(&self) -> ProtocolResult<Option<Event>> {
        unsafe {
            let ev = xcb_poll_for_queued_event(self.c);
            if ev.is_null() {
                Ok(None)
            } else if is_error(ev) {
                Err(error::resolve_error(ev as *mut _, &self.ext_data))
            } else {
                Ok(Some(event::resolve_event(ev, &self.ext_data)))
            }
        }
    }

    /// Start listening for a special event.
    ///
    /// Effectively creates an internal special queue for this event
    /// XGE events are only defined in the `xinput` and `present` extensions
    #[cfg(any(feature = "xinput", feature = "present"))]
    pub fn register_for_special_xge<XGE: GeEvent>(&self) -> SpecialEventId {
        unsafe {
            let ext: *mut xcb_extension_t = match XGE::EXTENSION {
                #[cfg(feature = "xinput")]
                Extension::Input => &mut xinput::FFI_EXT as *mut _,
                #[cfg(feature = "present")]
                Extension::Present => &mut present::FFI_EXT as *mut _,
                _ => unreachable!("only Input and Present have XGE events"),
            };

            let mut stamp: Timestamp = 0;

            let raw = xcb_register_for_special_xge(self.c, ext, XGE::NUMBER, &mut stamp as *mut _);

            SpecialEventId { raw, stamp }
        }
    }

    /// Stop listening to a special event
    #[cfg(any(feature = "xinput", feature = "present"))]
    pub fn unregister_for_special_xge(&self, se: SpecialEventId) {
        unsafe {
            xcb_unregister_for_special_xge(self.c, se.raw);
        }
    }

    /// Returns the next event from a special queue, blocking until one arrives
    #[cfg(any(feature = "xinput", feature = "present"))]
    pub fn wait_for_special_event(&self, se: SpecialEventId) -> Result<Event> {
        unsafe {
            let ev = xcb_wait_for_special_event(self.c, se.raw);
            self.handle_wait_for_event(ev)
        }
    }

    /// Returns the next event from a special queue
    #[cfg(any(feature = "xinput", feature = "present"))]
    pub fn poll_for_special_event(&self, se: SpecialEventId) -> Result<Option<Event>> {
        unsafe {
            let ev = xcb_poll_for_special_event(self.c, se.raw);
            self.handle_poll_for_event(ev)
        }
    }

    /// Discards the reply for a request.
    ///
    /// Discards the reply for a request. Additionally, any error generated
    /// by the request is also discarded (unless it was an _unchecked request
    /// and the error has already arrived).
    ///
    /// This function will not block even if the reply is not yet available.
    fn discard_reply<C: Cookie>(&self, cookie: C) {
        unsafe {
            xcb_discard_reply64(self.c, cookie.sequence());
        }
    }

    /// Access the data returned by the server.
    ///
    /// Accessor for the data returned by the server when the connection
    /// was initialized. This data includes
    /// - the server's required format for images,
    /// - a list of available visuals,
    /// - a list of available screens,
    /// - the server's maximum request length (in the absence of the
    /// BIG-REQUESTS extension),
    /// - and other assorted information.
    ///
    /// See the X protocol specification for more details.
    pub fn get_setup(&self) -> &Setup {
        unsafe {
            let ptr = xcb_get_setup(self.c);
            let len = Setup::compute_wire_len(ptr, ());
            Setup::from_data(slice::from_raw_parts(ptr, len))
        }
    }

    /// Test whether the connection has shut down due to a fatal error.
    ///
    /// Some errors that occur in the context of a connection
    /// are unrecoverable. When such an error occurs, the
    /// connection is shut down and further operations on the
    /// connection have no effect.
    pub fn has_error(&self) -> ConnResult<()> {
        unsafe { check_connection_error(self.c) }
    }

    /// Send a request to the X server.
    ///
    /// This function never blocks. A cookie is returned to keep track of the request.
    /// If the request expect a reply, the cookie can be used to retrieve the reply
    ///
    /// # Example
    /// ```no_run
    /// # use xcb::x;
    /// # fn main() -> xcb::Result<()> {
    /// #   let (conn, screen_num) = xcb::Connection::connect(None)?;
    /// #   let setup = conn.get_setup();
    /// #   let screen = setup.roots().nth(screen_num as usize).unwrap();
    /// #   let window: x::Window = conn.generate_id();
    ///     // Example of void request.
    ///     // Error (if any) will be sent to the event loop (see `wait_for_event`).
    ///     // In this case, the cookie can be discarded.
    ///     conn.send_request(&x::CreateWindow {
    ///         depth: x::COPY_FROM_PARENT as u8,
    ///         wid: window,
    ///         parent: screen.root(),
    ///         x: 0,
    ///         y: 0,
    ///         width: 150,
    ///         height: 150,
    ///         border_width: 10,
    ///         class: x::WindowClass::InputOutput,
    ///         visual: screen.root_visual(),
    ///         value_list: &[
    ///             x::Cw::BackPixel(screen.white_pixel()),
    ///             x::Cw::EventMask(x::EventMask::EXPOSURE | x::EventMask::KEY_PRESS),
    ///         ],
    ///     });
    ///
    ///     // Example of request with reply. The error (if any) is obtained with the reply.
    ///     let cookie = conn.send_request(&x::InternAtom {
    ///         only_if_exists: true,
    ///         name: b"WM_PROTOCOLS",
    ///     });
    ///     let wm_protocols_atom: x::Atom = conn
    ///             .wait_for_reply(cookie)?
    ///             .atom();
    /// #   Ok(())
    /// # }
    /// ```
    pub fn send_request<R>(&self, req: &R) -> R::Cookie
    where
        R: Request,
    {
        unsafe { R::Cookie::from_sequence(req.raw_request(self, !R::IS_VOID)) }
    }

    /// Send a checked request to the X server.
    ///
    /// Checked requests do not expect a reply, but the returned cookie can be used to check for
    /// errors using `Connection::check_request`.
    ///
    /// # Example
    /// ```no_run
    /// # use xcb::x;
    /// # fn main() -> xcb::Result<()> {
    /// #   let (conn, screen_num) = xcb::Connection::connect(None)?;
    /// #   let window: x::Window = conn.generate_id();
    ///     let cookie = conn.send_request_checked(&x::MapWindow { window });
    ///     conn.check_request(cookie)?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn send_request_checked<R>(&self, req: &R) -> VoidCookieChecked
    where
        R: RequestWithoutReply,
    {
        unsafe { VoidCookieChecked::from_sequence(req.raw_request(self, true)) }
    }

    /// Send an unchecked request to the X server.
    ///
    /// Unchecked requests expect a reply that is to be retrieved by [Connection::wait_for_reply_unchecked].
    /// Unchecked means that the error is not checked when the reply is fetched. Instead, the error will
    /// be sent to the event loop
    ///
    /// # Example
    /// ```no_run
    /// # use xcb::x;
    /// # fn main() -> xcb::Result<()> {
    /// #   let (conn, screen_num) = xcb::Connection::connect(None)?;
    ///     let cookie = conn.send_request_unchecked(&x::InternAtom {
    ///         only_if_exists: true,
    ///         name: b"WM_PROTOCOLS",
    ///     });
    ///     let wm_protocols_atom: Option<x::Atom> = conn
    ///             .wait_for_reply_unchecked(cookie)?
    ///             .map(|rep| rep.atom());
    /// #   Ok(())
    /// # }
    /// ```
    pub fn send_request_unchecked<R>(&self, req: &R) -> R::CookieUnchecked
    where
        R: RequestWithReply,
    {
        unsafe { R::CookieUnchecked::from_sequence(req.raw_request(self, false)) }
    }

    /// Check a checked request for errors.
    ///
    /// The cookie supplied to this function must have resulted
    /// from a call to [Connection::send_request_checked].  This function will block
    /// until one of two conditions happens.  If an error is received, it will be
    /// returned.  If a reply to a subsequent request has already arrived, no error
    /// can arrive for this request, so this function will return `Ok(())`.
    ///
    /// Note that this function will perform a sync if needed to ensure that the
    /// sequence number will advance beyond that provided in cookie; this is a
    /// convenience to avoid races in determining whether the sync is needed.
    ///
    /// # Example
    /// ```no_run
    /// # use xcb::x;
    /// # fn main() -> xcb::Result<()> {
    /// #   let (conn, screen_num) = xcb::Connection::connect(None)?;
    /// #   let window: x::Window = conn.generate_id();
    ///     conn.check_request(conn.send_request_checked(&x::MapWindow { window }))?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn check_request(&self, cookie: VoidCookieChecked) -> ProtocolResult<()> {
        let cookie = xcb_void_cookie_t {
            seq: cookie.sequence() as u32,
        };
        let error = unsafe { xcb_request_check(self.c, cookie) };
        if error.is_null() {
            Ok(())
        } else {
            unsafe {
                let res = error::resolve_error(error, &self.ext_data);
                Err(res)
            }
        }
    }

    /// Get the reply of a previous request, or an error if one occured.
    ///
    /// # Example
    /// ```no_run
    /// # use xcb::x;
    /// # fn main() -> xcb::Result<()> {
    /// #   let (conn, screen_num) = xcb::Connection::connect(None)?;
    ///     let cookie = conn.send_request(&x::InternAtom {
    ///         only_if_exists: true,
    ///         name: b"WM_PROTOCOLS",
    ///     });
    ///     let wm_protocols_atom: x::Atom = conn
    ///             .wait_for_reply(cookie)?
    ///             .atom();
    /// #   Ok(())
    /// # }
    /// ```
    pub fn wait_for_reply<C>(&self, cookie: C) -> Result<C::Reply>
    where
        C: CookieWithReplyChecked,
    {
        unsafe {
            let mut error: *mut xcb_generic_error_t = std::ptr::null_mut();
            let reply = xcb_wait_for_reply64(self.c, cookie.sequence(), &mut error as *mut _);
            match (reply.is_null(), error.is_null()) {
                (true, true) => {
                    self.has_error()?;
                    unreachable!("xcb_wait_for_reply64 returned null without I/O error");
                }
                (true, false) => {
                    let error = error::resolve_error(error, &self.ext_data);
                    Err(error.into())
                }
                (false, true) => Ok(C::Reply::from_raw(reply as *const u8)),
                (false, false) => unreachable!("xcb_wait_for_reply64 returned two pointers"),
            }
        }
    }

    /// Get the reply of a previous unchecked request.
    ///
    /// If an error occured, `None` is returned and the error will be delivered to the event loop.
    ///
    /// # Example
    /// ```no_run
    /// # use xcb::x;
    /// # fn main() -> xcb::Result<()> {
    /// #   let (conn, screen_num) = xcb::Connection::connect(None)?;
    ///     let cookie = conn.send_request_unchecked(&x::InternAtom {
    ///         only_if_exists: true,
    ///         name: b"WM_PROTOCOLS",
    ///     });
    ///     let wm_protocols_atom: Option<x::Atom> = conn
    ///             .wait_for_reply_unchecked(cookie)?  // connection error may happen
    ///             .map(|rep| rep.atom());
    /// #   Ok(())
    /// # }
    /// ```
    pub fn wait_for_reply_unchecked<C>(&self, cookie: C) -> ConnResult<Option<C::Reply>>
    where
        C: CookieWithReplyUnchecked,
    {
        unsafe {
            let reply = xcb_wait_for_reply64(self.c, cookie.sequence(), ptr::null_mut());
            if reply.is_null() {
                self.has_error()?;
                Ok(None)
            } else {
                Ok(Some(C::Reply::from_raw(reply as *const u8)))
            }
        }
    }

    /// Obtain number of bytes read from the connection.
    ///
    /// Returns cumulative number of bytes received from the connection.
    ///
    /// This retrieves the total number of bytes read from this connection,
    /// to be used for diagnostic/monitoring/informative purposes.
    pub fn total_read(&self) -> usize {
        unsafe { xcb_total_read(self.c) as usize }
    }

    /// Obtain number of bytes written to the connection.
    ///
    /// Returns cumulative number of bytes sent to the connection.
    ///
    /// This retrieves the total number of bytes written to this connection,
    /// to be used for diagnostic/monitoring/informative purposes.
    pub fn total_written(&self) -> usize {
        unsafe { xcb_total_written(self.c) as usize }
    }
}

impl AsRawFd for Connection {
    fn as_raw_fd(&self) -> RawFd {
        unsafe { xcb_get_file_descriptor(self.c) }
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        #[cfg(feature = "debug_atom_names")]
        if self.dbg_atom_names {
            unsafe {
                dan::DAN_CONN = ptr::null_mut();
            }
        }

        #[cfg(not(feature = "xlib_xcb"))]
        unsafe {
            xcb_disconnect(self.c);
        }

        #[cfg(feature = "xlib_xcb")]
        unsafe {
            if self.dpy.is_null() {
                xcb_disconnect(self.c);
            } else {
                xlib::XCloseDisplay(self.dpy);
            }
        }
    }
}

#[cfg(feature = "debug_atom_names")]
mod dan {
    use super::{Connection, Xid};
    use crate::ffi::base::xcb_connection_t;
    use crate::x;

    use std::fmt;
    use std::mem;
    use std::ptr;
    use std::str;

    pub(crate) static mut DAN_CONN: *mut xcb_connection_t = ptr::null_mut();

    impl fmt::Debug for x::Atom {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            let mut write = |name: &str| -> fmt::Result {
                f.write_fmt(format_args!("Atom(\"{}\" ; {})", name, self.resource_id()))
            };
            if let Some(name) = x::predefined_atom_name(*self) {
                write(name)
            } else {
                let conn = unsafe { Connection::from_raw_conn(DAN_CONN) };

                let cookie = conn.send_request(&x::GetAtomName { atom: *self });
                let reply = conn.wait_for_reply(cookie).map_err(|err| {
                    eprintln!(
                        "Error during fmt::Debug of x::Atom (fetching atom name): {:#?}",
                        err
                    );
                    fmt::Error
                })?;

                let name = reply.name().to_utf8();
                write(&name)?;

                mem::forget(conn);
                Ok(())
            }
        }
    }
}

unsafe fn check_connection_error(conn: *mut xcb_connection_t) -> ConnResult<()> {
    match xcb_connection_has_error(conn) {
        0 => Ok(()),
        XCB_CONN_ERROR => Err(ConnError::Connection),
        XCB_CONN_CLOSED_EXT_NOTSUPPORTED => Err(ConnError::ClosedExtNotSupported),
        XCB_CONN_CLOSED_MEM_INSUFFICIENT => Err(ConnError::ClosedMemInsufficient),
        XCB_CONN_CLOSED_REQ_LEN_EXCEED => Err(ConnError::ClosedReqLenExceed),
        XCB_CONN_CLOSED_PARSE_ERR => Err(ConnError::ClosedParseErr),
        XCB_CONN_CLOSED_INVALID_SCREEN => Err(ConnError::ClosedInvalidScreen),
        _ => {
            log::warn!("XCB: unexpected error code from xcb_connection_has_error");
            log::warn!("XCB: Default to ConnError::Connection");
            Err(ConnError::Connection)
        }
    }
}

unsafe fn is_error(ev: *mut xcb_generic_event_t) -> bool {
    debug_assert!(!ev.is_null());
    (*ev).response_type == 0
}

bitflags! {
    pub(crate) struct RequestFlags: u32 {
        const NONE = 0;
        const CHECKED = 1;
        const RAW = 2;
        const DISCARD_REPLY = 4;
        const REPLY_FDS = 8;
    }
}

/// Compute the necessary padding after `base` to have `align` alignment
pub(crate) fn align_pad(base: usize, align: usize) -> usize {
    debug_assert!(align.is_power_of_two(), "`align` must be a power of two");

    let base = base as isize;
    let align = align as isize;
    (-base & (align - 1)) as usize
}

#[test]
fn test_align_pad() {
    // align 1
    assert_eq!(align_pad(0, 1), 0);
    assert_eq!(align_pad(1234, 1), 0);
    assert_eq!(align_pad(1235, 1), 0);
    // align 2
    assert_eq!(align_pad(0, 2), 0);
    assert_eq!(align_pad(1233, 2), 1);
    assert_eq!(align_pad(1234, 2), 0);
    // align 4
    assert_eq!(align_pad(0, 4), 0);
    assert_eq!(align_pad(12, 4), 0);
    assert_eq!(align_pad(13, 4), 3);
    assert_eq!(align_pad(14, 4), 2);
    assert_eq!(align_pad(15, 4), 1);
    assert_eq!(align_pad(16, 4), 0);
}