setroot 0.2.0

A library for setting desktop background image
Documentation
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
#![feature(prelude_import)]
/*!# setroot

A library for setting desktop background image.  It provides methods and types
for a) querying screen’s monitor configuration, b) creating a pixmap which can
be used as a background image and c) changing the root background.

The library serves the purpose similar to applications such as `Esetroot`,
`xsetroot`, `fvwm-root` etc.  Since it communicates directly with the X display
it does not require external applications to accomplish its task.


## Example usage

```rust,ignore
fn set_background() -> Result<(), Error> {
    // Connect to X display server.
    let display = setroot::Display::open()?;
    // Create a pixmap to use as the background.
    let root_pixmap = display.root_pixmap()?;
    // Query monitor configuration of the screen.
    let monitors = display.monitors()?;
    // Iterate over all monitors and draw background for each
    // of them.
    for monitor in monitors {
        // Load an image to fit the monitor.
        let image: image::RgbImage =
            load_image_for_dimension(
                monitor.width, monitor.height)?;
        // Draw the image onto the pixmap.
        root_pixmap.put_image(monitor.x, monitor.y, image)?;
    }
    // Set the background.
    root_pixmap.set_background()?;
    Ok(())
}

fn load_image_for_dimension(
    width: u16,
    height: u16,
) -> Result<image::RgbImage, Error> {
    todo!()
}

enum Error { /* TODO */ }
```


## Features

The crate defines the following Cargo feature:

* `image`, enabled by default, includes dependency on `image` crate and allows
  `image::RgbImage` objects to be passed as arguments to `put_image` function.


## Limitations

The library has currently tho following limitations:

* It does not offer features for resizing images or tiling images.  It is left
  to the user to prepare correctly sized image that can be draw on the root
  pixmap.

* It works with X11 display servers only and requires RandR 1.5+ extension to be
  present.  This covers vast majority of X11 displays but might not work on
  Wayland desktops or in non-Unix-like environments.

* It assumes the X display server uses 24/32-bit True Colour visual, i.e. that
  colours are represented as 32-bit numbers with 8 bits per channel.  This
  should cover *vast* majority of cases and system configurations.
*/
#[macro_use]
extern crate std;
#[prelude_import]
use std::prelude::rust_2024::*;
use xcb::x::Atom;
use xcb::{Xid, XidNew, randr, x};
pub mod err {
    #[non_exhaustive]
    pub enum Error {
        /// XCB error as a result of an X request.
        #[display("{}", _0)]
        #[from(xcb::Error, xcb::ConnError, xcb::ProtocolError)]
        XcbError(xcb::Error),
        /// Unrecognised screen number, i.e. negative or does not match any existing
        /// screen.
        #[display("invalid screen number: {}", _0)]
        BadScreenNumber(i32),
        /// Display server uses unsupported visual.  This library currently supports
        /// only 24 or 32-bit TrueColour visual.
        #[display("unsupported visual class: {}-bit {:?}", _0, _1)]
        UnsupportedVisual(u8, xcb::x::VisualClass),
        /// Failed to locate visual that matches the root visual.
        #[display("could not find root visual: {}", _0)]
        CouldNotFindRootVisual(xcb::x::Visualid),
        /// Image too large.  Image dimensions must fit 16-bit unsigned integer.
        #[display("image {}x{} too large", _0, _1)]
        ImageTooLarge(u32, u32),
        /// The image buffer size does not match image dimensions.
        #[display("buffer {} does not match {}x{} image size", _0, _1, _2)]
        BadBufferSize(usize, u16, u16),
    }
    #[automatically_derived]
    impl ::core::fmt::Debug for Error {
        #[inline]
        fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
            match self {
                Error::XcbError(__self_0) => {
                    ::core::fmt::Formatter::debug_tuple_field1_finish(
                        f,
                        "XcbError",
                        &__self_0,
                    )
                }
                Error::BadScreenNumber(__self_0) => {
                    ::core::fmt::Formatter::debug_tuple_field1_finish(
                        f,
                        "BadScreenNumber",
                        &__self_0,
                    )
                }
                Error::UnsupportedVisual(__self_0, __self_1) => {
                    ::core::fmt::Formatter::debug_tuple_field2_finish(
                        f,
                        "UnsupportedVisual",
                        __self_0,
                        &__self_1,
                    )
                }
                Error::CouldNotFindRootVisual(__self_0) => {
                    ::core::fmt::Formatter::debug_tuple_field1_finish(
                        f,
                        "CouldNotFindRootVisual",
                        &__self_0,
                    )
                }
                Error::ImageTooLarge(__self_0, __self_1) => {
                    ::core::fmt::Formatter::debug_tuple_field2_finish(
                        f,
                        "ImageTooLarge",
                        __self_0,
                        &__self_1,
                    )
                }
                Error::BadBufferSize(__self_0, __self_1, __self_2) => {
                    ::core::fmt::Formatter::debug_tuple_field3_finish(
                        f,
                        "BadBufferSize",
                        __self_0,
                        __self_1,
                        &__self_2,
                    )
                }
            }
        }
    }
    #[allow(unreachable_code)]
    #[automatically_derived]
    impl derive_more::core::fmt::Display for Error {
        fn fmt(
            &self,
            __derive_more_f: &mut derive_more::core::fmt::Formatter<'_>,
        ) -> derive_more::core::fmt::Result {
            match self {
                Self::XcbError(_0) => {
                    derive_more::core::fmt::Display::fmt(_0, __derive_more_f)
                }
                Self::BadScreenNumber(_0) => {
                    __derive_more_f
                        .write_fmt(format_args!("invalid screen number: {0}", _0))
                }
                Self::UnsupportedVisual(_0, _1) => {
                    __derive_more_f
                        .write_fmt(
                            format_args!(
                                "unsupported visual class: {0}-bit {1:?}",
                                _0,
                                _1,
                            ),
                        )
                }
                Self::CouldNotFindRootVisual(_0) => {
                    __derive_more_f
                        .write_fmt(format_args!("could not find root visual: {0}", _0))
                }
                Self::ImageTooLarge(_0, _1) => {
                    __derive_more_f
                        .write_fmt(format_args!("image {0}x{1} too large", _0, _1))
                }
                Self::BadBufferSize(_0, _1, _2) => {
                    __derive_more_f
                        .write_fmt(
                            format_args!(
                                "buffer {0} does not match {1}x{2} image size",
                                _0,
                                _1,
                                _2,
                            ),
                        )
                }
            }
        }
    }
    #[allow(unreachable_code)]
    #[automatically_derived]
    impl derive_more::core::convert::From<xcb::Error> for Error {
        #[inline]
        fn from(value: xcb::Error) -> Self {
            Error::XcbError(
                <xcb::Error as derive_more::core::convert::From<xcb::Error>>::from(value),
            )
        }
    }
    #[allow(unreachable_code)]
    #[automatically_derived]
    impl derive_more::core::convert::From<xcb::ConnError> for Error {
        #[inline]
        fn from(value: xcb::ConnError) -> Self {
            Error::XcbError(
                <xcb::Error as derive_more::core::convert::From<
                    xcb::ConnError,
                >>::from(value),
            )
        }
    }
    #[allow(unreachable_code)]
    #[automatically_derived]
    impl derive_more::core::convert::From<xcb::ProtocolError> for Error {
        #[inline]
        fn from(value: xcb::ProtocolError) -> Self {
            Error::XcbError(
                <xcb::Error as derive_more::core::convert::From<
                    xcb::ProtocolError,
                >>::from(value),
            )
        }
    }
    /// Unrecognised screen number, i.e. negative or does not match any existing
    /// screen.
    #[display("invalid screen number: {}", _0)]
    pub struct BadScreenNumber(pub i32);
    #[automatically_derived]
    impl ::core::fmt::Debug for BadScreenNumber {
        #[inline]
        fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
            ::core::fmt::Formatter::debug_tuple_field1_finish(
                f,
                "BadScreenNumber",
                &&self.0,
            )
        }
    }
    #[allow(unreachable_code)]
    #[automatically_derived]
    impl derive_more::core::fmt::Display for BadScreenNumber {
        fn fmt(
            &self,
            __derive_more_f: &mut derive_more::core::fmt::Formatter<'_>,
        ) -> derive_more::core::fmt::Result {
            let _0 = &self.0;
            __derive_more_f.write_fmt(format_args!("invalid screen number: {0}", _0))
        }
    }
    impl From<BadScreenNumber> for Error {
        fn from(err: BadScreenNumber) -> Error {
            Error::BadScreenNumber(err.0)
        }
    }
}
pub mod img {
    /// Definition of a pixel format used by X display server.
    ///
    /// The pixel format is defined as shift values for red, green and blue subpixel
    /// value.  The colour is represented by a `u32` value whose component channels
    /// are 8-bit values shifted to the left by corresponding shift values.
    ///
    /// Common format for colour is `0x00_RR_GG_BB` which is described as 16, 8 and
    /// 0 shifts for red, green and blue colour components respectively.  Beware
    /// that on little endian systems (so practically on all systems), such colour
    /// is encoded as `[red, green, blue, 0]` bytes in memory.
    #[display("RgbShifts({}, {}, {})", r, g, b)]
    #[debug("{}", self)]
    pub struct RgbShifts {
        /// Bit shift value for red component in `u32` colour description.
        /// Typically 16.
        pub r: u8,
        /// Bit shift value for red component in `u32` colour description.
        /// Typically 8.
        pub g: u8,
        /// Bit shift value for red component in `u32` colour description.
        /// Typically 0.
        pub b: u8,
    }
    #[automatically_derived]
    impl ::core::clone::Clone for RgbShifts {
        #[inline]
        fn clone(&self) -> RgbShifts {
            let _: ::core::clone::AssertParamIsClone<u8>;
            *self
        }
    }
    #[automatically_derived]
    impl ::core::marker::Copy for RgbShifts {}
    #[automatically_derived]
    impl ::core::marker::StructuralPartialEq for RgbShifts {}
    #[automatically_derived]
    impl ::core::cmp::PartialEq for RgbShifts {
        #[inline]
        fn eq(&self, other: &RgbShifts) -> bool {
            self.r == other.r && self.g == other.g && self.b == other.b
        }
    }
    #[automatically_derived]
    impl ::core::cmp::Eq for RgbShifts {
        #[inline]
        #[doc(hidden)]
        #[coverage(off)]
        fn assert_receiver_is_total_eq(&self) -> () {
            let _: ::core::cmp::AssertParamIsEq<u8>;
        }
    }
    #[automatically_derived]
    impl ::core::cmp::PartialOrd for RgbShifts {
        #[inline]
        fn partial_cmp(
            &self,
            other: &RgbShifts,
        ) -> ::core::option::Option<::core::cmp::Ordering> {
            match ::core::cmp::PartialOrd::partial_cmp(&self.r, &other.r) {
                ::core::option::Option::Some(::core::cmp::Ordering::Equal) => {
                    match ::core::cmp::PartialOrd::partial_cmp(&self.g, &other.g) {
                        ::core::option::Option::Some(::core::cmp::Ordering::Equal) => {
                            ::core::cmp::PartialOrd::partial_cmp(&self.b, &other.b)
                        }
                        cmp => cmp,
                    }
                }
                cmp => cmp,
            }
        }
    }
    #[automatically_derived]
    impl ::core::cmp::Ord for RgbShifts {
        #[inline]
        fn cmp(&self, other: &RgbShifts) -> ::core::cmp::Ordering {
            match ::core::cmp::Ord::cmp(&self.r, &other.r) {
                ::core::cmp::Ordering::Equal => {
                    match ::core::cmp::Ord::cmp(&self.g, &other.g) {
                        ::core::cmp::Ordering::Equal => {
                            ::core::cmp::Ord::cmp(&self.b, &other.b)
                        }
                        cmp => cmp,
                    }
                }
                cmp => cmp,
            }
        }
    }
    #[allow(unreachable_code)]
    #[automatically_derived]
    impl derive_more::core::fmt::Display for RgbShifts {
        fn fmt(
            &self,
            __derive_more_f: &mut derive_more::core::fmt::Formatter<'_>,
        ) -> derive_more::core::fmt::Result {
            let r = &self.r;
            let g = &self.g;
            let b = &self.b;
            __derive_more_f.write_fmt(format_args!("RgbShifts({0}, {1}, {2})", r, g, b))
        }
    }
    #[allow(unreachable_code)]
    #[automatically_derived]
    impl derive_more::core::fmt::Debug for RgbShifts {
        #[inline]
        fn fmt(
            &self,
            __derive_more_f: &mut derive_more::core::fmt::Formatter<'_>,
        ) -> derive_more::core::fmt::Result {
            let r = &self.r;
            let g = &self.g;
            let b = &self.b;
            derive_more::core::fmt::Display::fmt(&(self), __derive_more_f)
        }
    }
    /// A type of a single colour component.
    pub trait Subpixel: bytemuck::Pod {
        /// Converts the component value into `u8`.
        fn to_u8(self) -> u8;
    }
    impl RgbShifts {
        /// Constructs a colour representation from red, green and blue components.
        ///
        /// ```
        /// let shifts = setroot::img::RgbShifts { r: 16, g: 8, b: 0 }
        /// assert_eq!(0x00_E7_F8_FF, shifts.from_rgb(0xFF, 0xF8, 0xE7));
        /// ```
        pub fn from_rgb<S: Subpixel>(&self, r: S, g: S, b: S) -> u32 {
            (u32::from(r.to_u8()) << self.r) | (u32::from(g.to_u8()) << self.g)
                | (u32::from(b.to_u8()) << self.b)
        }
        /// Constructs a greyscale colour representation from luma value.
        ///
        /// Due to minor optimisation, it returns slightly different value than
        /// `self.from_rgb(l, l, l)` would.  Specifically, luma is in addition
        /// copied the unused byte of the colour.
        ///
        /// ```
        /// let shifts = setroot::img::RgbShifts { r: 16, g: 8, b: 0 }
        /// assert_eq!(0x00_E7_F8_FF, shifts.from_rgb(0xFF, 0xF8, 0xE7));
        /// ```
        pub fn from_luma<S: Subpixel>(&self, luma: S) -> u32 {
            u32::from(luma.to_u8()) * 0x0101_0101
        }
    }
    impl Subpixel for u8 {
        fn to_u8(self) -> u8 {
            self
        }
    }
    impl Subpixel for u16 {
        fn to_u8(self) -> u8 {
            (self >> 8) as u8
        }
    }
    impl Subpixel for f32 {
        fn to_u8(self) -> u8 {
            if !(self < 1.0) {
                255
            } else if self <= 0.0 {
                0
            } else {
                (self * 255.0).round() as u8
            }
        }
    }
    /// A view of an 24-bit sRGB image backed by a continuous buffer of `[red,
    /// green, blue]` elements.
    pub trait View {
        /// Returns dimensions of the image.
        ///
        /// Note that while the return type is a tuple of 32-bit integers, in
        /// practice each dimension is limited to the range of 16-bit unsigned
        /// integers.  This discrepancy is caused by desire for greater
        /// interoperability with other crates (and `image` crate in particular)
        /// which support larger images.
        fn dimensions(&self) -> (u32, u32);
        /// Returns underlying buffer of the image.
        ///
        /// The length of the returned slice must match the dimensions.
        /// Each pixel is represented as `[red, green, blue]` 3-element arrays.
        ///
        /// Hint: `&[u8]` slice can be converted into `&[[u8; 3]]` slice using
        /// [`bytemuck::try_cast_slice`].
        fn as_rgb(&self) -> &[[u8; 3]];
    }
    impl<T: View> View for &T {
        fn dimensions(&self) -> (u32, u32) {
            (*self).dimensions()
        }
        fn as_rgb(&self) -> &[[u8; 3]] {
            (*self).as_rgb()
        }
    }
    /// An image in sRGB colour space.
    pub struct Ref<'a> {
        /// Width of the image.
        ///
        /// For greater interoperability with other crates (namely `image`), the
        /// value is a 32-bit unsigned integer.  However, in practice, the width
        /// must fit a 16-bit unsigned integer or else [`RootPixmap::put_image`]
        /// will return [`Error::ImageTooLarge`].
        pub width: u32,
        /// Height of the image.
        ///
        /// For greater interoperability with other crates (namely `image`), the
        /// value is a 32-bit unsigned integer.  However, in practice, the height
        /// must fit a 16-bit unsigned integer or else [`RootPixmap::put_image`]
        /// will return [`Error::ImageTooLarge`].
        pub height: u32,
        /// The underlying image buffer of sRGB values.
        ///
        /// If the size doesn’t match dimensions [`RootPixmap::put_image`] will
        /// fail.
        pub data: &'a [[u8; 3]],
    }
    impl<'a> Ref<'a> {
        /// Constructs new image view for image with given dimensions and underlying
        /// raw buffer of sRGB values.
        ///
        /// Returns `None` if the size of the `data` slice does not match the
        /// dimensions, i.e. if `width * height * 3 != data.len()`.
        pub fn new(width: u32, height: u32, data: &'a [u8]) -> Option<Self> {
            let dim = width.try_into().ok().zip(height.try_into().ok());
            dim.and_then(|(w, h): (usize, usize)| w.checked_mul(h))
                .and_then(|area| area.checked_mul(3))
                .is_some_and(|len| len == data.len())
                .then(|| Self {
                    width,
                    height,
                    data: bytemuck::cast_slice(data),
                })
        }
    }
    impl<'a> View for Ref<'a> {
        #[inline]
        fn dimensions(&self) -> (u32, u32) {
            (self.width, self.height)
        }
        #[inline]
        fn as_rgb(&self) -> &'a [[u8; 3]] {
            self.data
        }
    }
    impl View for image::RgbImage {
        #[inline]
        fn dimensions(&self) -> (u32, u32) {
            self.dimensions()
        }
        #[inline]
        fn as_rgb(&self) -> &[[u8; 3]] {
            bytemuck::cast_slice(self.as_raw().as_slice())
        }
    }
}
pub use err::Error;
pub type Result<T = (), E = Error> = core::result::Result<T, E>;
/// Handler for an X11 connection.
pub struct Display {
    conn: xcb::Connection,
    screen_num: i32,
}
impl Display {
    /// Opens connection to X11 display.
    pub fn open() -> Result<Self> {
        let (conn, screen_num) = xcb::Connection::connect(None)?;
        Self::from_xcb(conn, screen_num)
    }
    /// Constructs the object from existing XCB connection.
    pub fn from_xcb(conn: xcb::Connection, screen_num: i32) -> Result<Self> {
        usize::try_from(screen_num)
            .map(|_| Self { conn, screen_num })
            .map_err(|_| Error::BadScreenNumber(screen_num))
    }
    /// Consumes the object and returns the underlying XCB connection.  Returns
    /// a `(conn, screen_num)` pair just as [`xcb::Connection::connect`].
    pub fn into_xcb(self) -> (xcb::Connection, i32) {
        (self.conn, self.screen_num)
    }
    /// Returns reference to the XCB connection.
    pub fn conn(&self) -> &xcb::Connection {
        &self.conn
    }
    /// Returns the default screen number.
    pub fn default_screen_num(&self) -> i32 {
        self.screen_num
    }
    /// Returns the default screen.
    pub fn default_screen(&self) -> Result<&x::Screen, err::BadScreenNumber> {
        self.conn
            .get_setup()
            .roots()
            .nth(self.screen_num as usize)
            .ok_or(err::BadScreenNumber(self.screen_num))
    }
    /// Returns list of active monitors.
    ///
    /// Uses RandR extensions to query the dimensions of the monitors.  Requires
    /// RandR extension version 1.5 or newer to work.
    pub fn monitors(&self) -> Result<Vec<Monitor>> {
        let cookie = self
            .conn
            .send_request(
                &randr::GetMonitors {
                    window: self.default_screen()?.root(),
                    get_active: true,
                },
            );
        Ok(
            self
                .conn
                .wait_for_reply(cookie)?
                .monitors()
                .map(|mon| Monitor {
                    name: self.get_atom_name(mon.name()),
                    primary: mon.primary(),
                    x: mon.x(),
                    y: mon.y(),
                    width: mon.width(),
                    height: mon.height(),
                    width_in_millimeters: mon.width_in_millimeters(),
                    height_in_millimeters: mon.height_in_millimeters(),
                })
                .collect(),
        )
    }
    /// Returns a representation of the root window’s background pixmap.
    ///
    /// The object can be used to draw on the pixmap before finally setting it
    /// as the root window’s pixmap.  It’s dimensions and depth matches the
    /// default screen’s.
    pub fn root_pixmap(&self) -> Result<RootPixmap<'_>> {
        RootPixmap::new(self.conn(), self.default_screen()?)
    }
    /// Returns the name of given atom.
    fn get_atom_name(&self, atom: Atom) -> Option<String> {
        let cookie = self.conn.send_request(&x::GetAtomName { atom });
        let reply = self.conn.wait_for_reply(cookie).ok()?;
        let name = reply.name();
        (name.len() != 0).then(|| name.to_utf8().into_owned())
    }
}
/// Description of a monitor.
pub struct Monitor {
    pub name: Option<String>,
    pub primary: bool,
    pub x: i16,
    pub y: i16,
    pub width: u16,
    pub height: u16,
    pub width_in_millimeters: u32,
    pub height_in_millimeters: u32,
}
#[automatically_derived]
impl ::core::clone::Clone for Monitor {
    #[inline]
    fn clone(&self) -> Monitor {
        Monitor {
            name: ::core::clone::Clone::clone(&self.name),
            primary: ::core::clone::Clone::clone(&self.primary),
            x: ::core::clone::Clone::clone(&self.x),
            y: ::core::clone::Clone::clone(&self.y),
            width: ::core::clone::Clone::clone(&self.width),
            height: ::core::clone::Clone::clone(&self.height),
            width_in_millimeters: ::core::clone::Clone::clone(
                &self.width_in_millimeters,
            ),
            height_in_millimeters: ::core::clone::Clone::clone(
                &self.height_in_millimeters,
            ),
        }
    }
}
#[automatically_derived]
impl ::core::fmt::Debug for Monitor {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ = &[
            "name",
            "primary",
            "x",
            "y",
            "width",
            "height",
            "width_in_millimeters",
            "height_in_millimeters",
        ];
        let values: &[&dyn ::core::fmt::Debug] = &[
            &self.name,
            &self.primary,
            &self.x,
            &self.y,
            &self.width,
            &self.height,
            &self.width_in_millimeters,
            &&self.height_in_millimeters,
        ];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "Monitor", names, values)
    }
}
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for Monitor {}
#[automatically_derived]
impl ::core::cmp::PartialEq for Monitor {
    #[inline]
    fn eq(&self, other: &Monitor) -> bool {
        self.primary == other.primary && self.x == other.x && self.y == other.y
            && self.width == other.width && self.height == other.height
            && self.width_in_millimeters == other.width_in_millimeters
            && self.height_in_millimeters == other.height_in_millimeters
            && self.name == other.name
    }
}
#[automatically_derived]
impl ::core::cmp::Eq for Monitor {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<Option<String>>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<i16>;
        let _: ::core::cmp::AssertParamIsEq<u16>;
        let _: ::core::cmp::AssertParamIsEq<u32>;
    }
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for Monitor {
    #[inline]
    fn partial_cmp(
        &self,
        other: &Monitor,
    ) -> ::core::option::Option<::core::cmp::Ordering> {
        match ::core::cmp::PartialOrd::partial_cmp(&self.name, &other.name) {
            ::core::option::Option::Some(::core::cmp::Ordering::Equal) => {
                match ::core::cmp::PartialOrd::partial_cmp(
                    &self.primary,
                    &other.primary,
                ) {
                    ::core::option::Option::Some(::core::cmp::Ordering::Equal) => {
                        match ::core::cmp::PartialOrd::partial_cmp(&self.x, &other.x) {
                            ::core::option::Option::Some(
                                ::core::cmp::Ordering::Equal,
                            ) => {
                                match ::core::cmp::PartialOrd::partial_cmp(
                                    &self.y,
                                    &other.y,
                                ) {
                                    ::core::option::Option::Some(
                                        ::core::cmp::Ordering::Equal,
                                    ) => {
                                        match ::core::cmp::PartialOrd::partial_cmp(
                                            &self.width,
                                            &other.width,
                                        ) {
                                            ::core::option::Option::Some(
                                                ::core::cmp::Ordering::Equal,
                                            ) => {
                                                match ::core::cmp::PartialOrd::partial_cmp(
                                                    &self.height,
                                                    &other.height,
                                                ) {
                                                    ::core::option::Option::Some(
                                                        ::core::cmp::Ordering::Equal,
                                                    ) => {
                                                        match ::core::cmp::PartialOrd::partial_cmp(
                                                            &self.width_in_millimeters,
                                                            &other.width_in_millimeters,
                                                        ) {
                                                            ::core::option::Option::Some(
                                                                ::core::cmp::Ordering::Equal,
                                                            ) => {
                                                                ::core::cmp::PartialOrd::partial_cmp(
                                                                    &self.height_in_millimeters,
                                                                    &other.height_in_millimeters,
                                                                )
                                                            }
                                                            cmp => cmp,
                                                        }
                                                    }
                                                    cmp => cmp,
                                                }
                                            }
                                            cmp => cmp,
                                        }
                                    }
                                    cmp => cmp,
                                }
                            }
                            cmp => cmp,
                        }
                    }
                    cmp => cmp,
                }
            }
            cmp => cmp,
        }
    }
}
#[automatically_derived]
impl ::core::cmp::Ord for Monitor {
    #[inline]
    fn cmp(&self, other: &Monitor) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.name, &other.name) {
            ::core::cmp::Ordering::Equal => {
                match ::core::cmp::Ord::cmp(&self.primary, &other.primary) {
                    ::core::cmp::Ordering::Equal => {
                        match ::core::cmp::Ord::cmp(&self.x, &other.x) {
                            ::core::cmp::Ordering::Equal => {
                                match ::core::cmp::Ord::cmp(&self.y, &other.y) {
                                    ::core::cmp::Ordering::Equal => {
                                        match ::core::cmp::Ord::cmp(&self.width, &other.width) {
                                            ::core::cmp::Ordering::Equal => {
                                                match ::core::cmp::Ord::cmp(&self.height, &other.height) {
                                                    ::core::cmp::Ordering::Equal => {
                                                        match ::core::cmp::Ord::cmp(
                                                            &self.width_in_millimeters,
                                                            &other.width_in_millimeters,
                                                        ) {
                                                            ::core::cmp::Ordering::Equal => {
                                                                ::core::cmp::Ord::cmp(
                                                                    &self.height_in_millimeters,
                                                                    &other.height_in_millimeters,
                                                                )
                                                            }
                                                            cmp => cmp,
                                                        }
                                                    }
                                                    cmp => cmp,
                                                }
                                            }
                                            cmp => cmp,
                                        }
                                    }
                                    cmp => cmp,
                                }
                            }
                            cmp => cmp,
                        }
                    }
                    cmp => cmp,
                }
            }
            cmp => cmp,
        }
    }
}
/// A pixmap on a root window scaled to cover the entire screen.  Used to put
/// images onto it and eventually set as wallpaper.
pub struct RootPixmap<'a> {
    conn: &'a xcb::Connection,
    screen: &'a x::Screen,
    pixmap: x::Pixmap,
    gc: x::Gcontext,
    rgb_shifts: img::RgbShifts,
}
impl core::ops::Drop for RootPixmap<'_> {
    fn drop(&mut self) {
        self.conn.send_request(&x::FreeGc { gc: self.gc });
        self.conn
            .send_request(
                &x::FreePixmap {
                    pixmap: self.pixmap,
                },
            );
    }
}
impl<'a> RootPixmap<'a> {
    /// Constructs a new pixmap tied to the screen’s root window and sized to
    /// match screen’s dimensions.
    pub fn new(conn: &'a xcb::Connection, scr: &'a x::Screen) -> Result<Self> {
        let rgb_shifts = Self::get_rgb_shifts(scr)?;
        let pixmap = conn.generate_id::<x::Pixmap>();
        conn.send_and_check_request(
            &x::CreatePixmap {
                depth: scr.root_depth(),
                pid: pixmap,
                drawable: x::Drawable::Window(scr.root()),
                width: scr.width_in_pixels(),
                height: scr.height_in_pixels(),
            },
        )?;
        let gc = conn.generate_id::<x::Gcontext>();
        let cookie = conn
            .send_request_checked(
                &x::CreateGc {
                    cid: gc,
                    drawable: x::Drawable::Pixmap(pixmap),
                    value_list: &[],
                },
            );
        conn.check_request(cookie)
            .inspect_err(|_| {
                conn.send_request(&x::FreePixmap { pixmap });
            })?;
        Ok(Self {
            conn,
            screen: scr,
            pixmap,
            gc,
            rgb_shifts,
        })
    }
    /// Checks that visual is one we support and returns R, G and B channel
    /// sifts.
    fn get_rgb_shifts(scr: &'a x::Screen) -> Result<img::RgbShifts> {
        fn get_shift(mask: u32) -> Option<u8> {
            let shift = mask.trailing_zeros();
            ((mask >> shift) == 0xff).then_some(shift as u8)
        }
        let root_depth = scr.root_depth();
        let root_visual = scr.root_visual();
        scr.allowed_depths()
            .filter(|depth| depth.depth() == root_depth)
            .flat_map(|depth| depth.visuals())
            .find(|vis| vis.visual_id() == root_visual)
            .ok_or(Error::CouldNotFindRootVisual(root_visual))
            .and_then(|vis| {
                if vis.class() == x::VisualClass::TrueColor
                    && (root_depth == 24 || root_depth == 32)
                {
                    let shifts = get_shift(vis.red_mask())
                        .zip(get_shift(vis.green_mask()))
                        .zip(get_shift(vis.blue_mask()));
                    if let Some(((r, g), b)) = shifts {
                        return Ok(img::RgbShifts { r, g, b });
                    }
                }
                Err(Error::UnsupportedVisual(root_depth, vis.class()))
            })
    }
    /// Returns RGB shifts which define pixel format used by the X display.
    ///
    /// The shifts allow converting red, green and blue components into `u32`
    /// value that X server expects.
    pub fn rgb_shifts(&self) -> img::RgbShifts {
        self.rgb_shifts
    }
    /// Puts an image at given location on the pixmap.
    ///
    /// The image must be in 24-bit sRGB (that is, 8 bits per subpixel).
    ///
    /// Returns an error if the dimensions of the image are too large (or on
    /// protocol error).
    pub fn put_image(&self, x: i16, y: i16, img: impl img::View) -> Result {
        let (img_width, img_height) = img.dimensions();
        let dim = img_width.try_into().ok().zip(img_height.try_into().ok());
        let (img_width, img_height): (u16, u16) = dim
            .ok_or(Error::ImageTooLarge(img_width, img_height))?;
        let img = img.as_rgb();
        if usize::from(img_width) * usize::from(img_height) == img.len() {
            let data = img
                .iter()
                .map(|&[r, g, b]| self.rgb_shifts.from_rgb(r, g, b))
                .collect::<Vec<u32>>();
            self.put_raw_impl(
                x,
                y,
                img_width,
                img_height,
                bytemuck::must_cast_slice(data.as_slice()),
            )
        } else {
            Err(Error::BadBufferSize(img.len(), img_width, img_height))
        }
    }
    /// Puts an image at given location on the pixmap.
    ///
    /// The image must be in format accepted by the X display server.  This
    /// format is described by the [`img::RgbShifts`] object returned by
    /// [`Self::rgb_shifts`] class.
    ///
    /// Usually, [`Self::put_image`] method is more convenient interface since
    /// it performs all necessary data conversion to generate format acceptable
    /// by the display server.
    #[inline]
    pub fn put_raw(
        &self,
        dst_x: i16,
        dst_y: i16,
        width: u16,
        height: u16,
        data: &[u32],
    ) -> Result {
        if usize::from(width) * usize::from(height) == data.len() {
            let data = bytemuck::must_cast_slice(data);
            self.put_raw_impl(dst_x, dst_y, width, height, data)
        } else {
            Err(Error::BadBufferSize(data.len() * 4, width, height))
        }
    }
    fn put_raw_impl(
        &self,
        dst_x: i16,
        dst_y: i16,
        width: u16,
        height: u16,
        data: &[u8],
    ) -> Result {
        self.conn
            .send_and_check_request(
                &x::PutImage {
                    format: x::ImageFormat::ZPixmap,
                    drawable: x::Drawable::Pixmap(self.pixmap),
                    gc: self.gc,
                    width,
                    height,
                    dst_x,
                    dst_y,
                    left_pad: 0,
                    depth: self.screen.root_depth(),
                    data,
                },
            )
            .map_err(Error::from)
    }
    /// Set the root pixmap as the background of the root window.
    ///
    /// Furthermore, updates `_XROOTPMAP_ID` and `ESETROOT_PMAP_ID` atoms.
    ///
    /// If the method returns an error, the state of the root window is
    /// unspecified.  For example, it’s possible that the atoms were updated
    /// (such that applications using pseudo translucency will use the new
    /// background) but the actual background of the root window has not been
    /// updated.
    ///
    /// Furthermore, the method ignores some errors so long as the back pixmap
    /// of the root window is set.  This may result in redrawing artefacts.
    pub fn set_background(&self) -> Result {
        self.set_root_atoms();
        self.conn.send_request(&x::KillClient { resource: 0 });
        self.conn
            .send_request(
                &x::SetCloseDownMode {
                    mode: x::CloseDown::RetainTemporary,
                },
            );
        self.conn
            .send_and_check_request(
                &x::ChangeWindowAttributes {
                    window: self.screen.root(),
                    value_list: &[x::Cw::BackPixmap(self.pixmap)],
                },
            )?;
        self.conn
            .send_request(
                &x::ClearArea {
                    exposures: false,
                    window: self.screen.root(),
                    x: 0,
                    y: 0,
                    width: self.screen.width_in_pixels(),
                    height: self.screen.height_in_pixels(),
                },
            );
        Ok(())
    }
    /// Updates the atoms holding the root pixmap.
    fn set_root_atoms(&self) {
        let mut killed = None;
        for name in ["_XROOTPMAP_ID", "ESETROOT_PMAP_ID"] {
            let mut intern_request = x::InternAtom {
                only_if_exists: true,
                name: name.as_bytes(),
            };
            let cookie = self.conn.send_request(&intern_request);
            let atom = self
                .conn
                .wait_for_reply(cookie)
                .and_then(|reply| {
                    let atom = reply.atom();
                    if atom.is_none() {
                        intern_request.only_if_exists = false;
                        let cookie = self.conn.send_request(&intern_request);
                        self.conn.wait_for_reply(cookie).map(|reply| reply.atom())
                    } else {
                        self.clean_root_atom(atom, &mut killed);
                        Ok(atom)
                    }
                });
            let atom = match atom {
                Err(_err) => {
                    return;
                }
                Ok(atom) if atom.is_none() => {
                    return;
                }
                Ok(atom) => atom,
            };
            self.conn
                .send_request(
                    &x::ChangeProperty {
                        mode: x::PropMode::Replace,
                        window: self.screen.root(),
                        property: atom,
                        r#type: x::ATOM_PIXMAP,
                        data: &[self.pixmap.resource_id()],
                    },
                );
        }
    }
    /// Cleans up old atoms holding the root pixmap.
    fn clean_root_atom(&self, atom: Atom, prev_killed: &mut Option<u32>) {
        let cookie = self
            .conn
            .send_request(
                &x::GetProperty {
                    delete: false,
                    window: self.screen.root(),
                    property: atom,
                    r#type: x::ATOM_ANY,
                    long_offset: 0,
                    long_length: 1,
                },
            );
        let reply = match self.conn.wait_for_reply(cookie) {
            Ok(reply) => reply,
            Err(_err) => {
                return;
            }
        };
        if reply.r#type() == x::ATOM_PIXMAP && reply.format() == 32
            && reply.length() == 1 && reply.bytes_after() == 0
        {
            let pixmap_id = reply.value::<u32>().first().copied().unwrap_or_default();
            if pixmap_id != 0 && Some(pixmap_id) != *prev_killed {
                let pixmap = unsafe { x::Pixmap::new(pixmap_id) };
                self.conn
                    .send_request(
                        &x::KillClient {
                            resource: pixmap.resource_id(),
                        },
                    );
                *prev_killed = Some(pixmap_id);
            }
        }
    }
}