smithay-client-toolkit 0.12.3

Toolkit for making client wayland applications.
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
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
use std::cell::RefCell;
use std::cmp::max;
use std::rc::Rc;

use andrew::line;
use andrew::shapes::rectangle;
use andrew::text;
use andrew::text::fontconfig;
use andrew::{Canvas, Endian};

use wayland_client::protocol::{
    wl_compositor, wl_pointer, wl_seat, wl_shm, wl_subcompositor, wl_subsurface, wl_surface,
};
use wayland_client::{Attached, DispatchData};

use log::error;

use super::{
    ARGBColor, ButtonColorSpec, ButtonState, ColorSpec, Frame, FrameRequest, State, WindowState,
};
use crate::seat::pointer::{ThemeManager, ThemeSpec, ThemedPointer};
use crate::shm::DoubleMemPool;

/*
 * Drawing theme definitions
 */

const BORDER_SIZE: u32 = 12;
const HEADER_SIZE: u32 = 30;

/// Configuration for ConceptFrame
#[derive(Clone, Debug)]
pub struct ConceptConfig {
    /// The primary color of the titlebar
    pub primary_color: ColorSpec,
    /// Secondary color of the theme
    ///
    /// Used for the division line between the titlebar and the content
    pub secondary_color: ColorSpec,
    /// Parameters of the "Close" (or "x") button
    ///
    /// (icon color, button color)
    ///
    /// if `None` the button will not be drawn
    pub close_button: Option<(ButtonColorSpec, ButtonColorSpec)>,
    /// Parameters of the "Maximize" (or "^") button
    ///
    /// (icon color, button color)
    ///
    /// if `None` the button will not be drawn
    pub maximize_button: Option<(ButtonColorSpec, ButtonColorSpec)>,
    /// Parameters of the "Minimize" (or "v") button
    ///
    /// (icon color, button color)
    ///
    /// if `None` the button will not be drawn
    pub minimize_button: Option<(ButtonColorSpec, ButtonColorSpec)>,
    /// Font configuration for the titlebar
    ///
    /// Font name and size. If set to `None`, the title is not drawn.
    pub title_font: Option<(String, f32)>,
    /// Color for drawing the title text
    pub title_color: ColorSpec,
}

impl Default for ConceptConfig {
    fn default() -> ConceptConfig {
        let icon_spec = ButtonColorSpec {
            idle: ColorSpec::identical([0xFF, 0x1E, 0x1E, 0x1E].into()),
            hovered: ColorSpec::identical([0xFF, 0x1E, 0x1E, 0x1E].into()),
            disabled: ColorSpec::invisible(),
        };

        ConceptConfig {
            primary_color: ColorSpec {
                active: [0xFF, 0xE6, 0xE6, 0xE6].into(),
                inactive: [0xFF, 0xDC, 0xDC, 0xDC].into(),
            },
            secondary_color: ColorSpec {
                active: [0xFF, 0x1E, 0x1E, 0x1E].into(),
                inactive: [0xFF, 0x78, 0x78, 0x78].into(),
            },
            close_button: Some((
                // icon
                icon_spec,
                // button background
                ButtonColorSpec {
                    idle: ColorSpec::invisible(),
                    hovered: ColorSpec::identical([0xFF, 0xD9, 0x43, 0x52].into()),
                    disabled: ColorSpec::invisible(),
                },
            )),
            maximize_button: Some((
                // icon
                icon_spec,
                // button background
                ButtonColorSpec {
                    idle: ColorSpec::invisible(),
                    hovered: ColorSpec::identical([0xFF, 0x2D, 0xCB, 0x70].into()),
                    disabled: ColorSpec::invisible(),
                },
            )),
            minimize_button: Some((
                // icon
                icon_spec,
                // button background
                ButtonColorSpec {
                    idle: ColorSpec::invisible(),
                    hovered: ColorSpec::identical([0xFF, 0x3C, 0xAD, 0xE8].into()),
                    disabled: ColorSpec::invisible(),
                },
            )),
            title_font: Some(("sans".into(), 17.0)),
            title_color: ColorSpec::identical([0xFF, 0x00, 0x00, 0x00].into()),
        }
    }
}

/*
 * Utilities
 */

const HEAD: usize = 0;
const TOP: usize = 1;
const BOTTOM: usize = 2;
const LEFT: usize = 3;
const RIGHT: usize = 4;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Location {
    None,
    Head,
    Top,
    TopRight,
    Right,
    BottomRight,
    Bottom,
    BottomLeft,
    Left,
    TopLeft,
    Button(UIButton),
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum UIButton {
    Minimize,
    Maximize,
    Close,
}

struct Part {
    surface: wl_surface::WlSurface,
    subsurface: wl_subsurface::WlSubsurface,
}

impl Part {
    fn new(
        parent: &wl_surface::WlSurface,
        compositor: &Attached<wl_compositor::WlCompositor>,
        subcompositor: &Attached<wl_subcompositor::WlSubcompositor>,
        inner: Option<Rc<RefCell<Inner>>>,
    ) -> Part {
        let surface = if let Some(inner) = inner {
            crate::surface::setup_surface(
                compositor.create_surface(),
                Some(move |dpi, surface: wl_surface::WlSurface, ddata: DispatchData| {
                    surface.set_buffer_scale(dpi);
                    surface.commit();
                    (&mut inner.borrow_mut().implem)(FrameRequest::Refresh, 0, ddata);
                }),
            )
        } else {
            crate::surface::setup_surface(
                compositor.create_surface(),
                Some(move |dpi, surface: wl_surface::WlSurface, _ddata: DispatchData| {
                    surface.set_buffer_scale(dpi);
                    surface.commit();
                }),
            )
        };

        let surface = surface.detach();

        let subsurface = subcompositor.get_subsurface(&surface, parent);

        Part { surface, subsurface: subsurface.detach() }
    }
}

impl Drop for Part {
    fn drop(&mut self) {
        self.subsurface.destroy();
        self.surface.destroy();
    }
}

struct PointerUserData {
    location: Location,
    position: (f64, f64),
    seat: wl_seat::WlSeat,
}

/*
 * The core frame
 */

struct Inner {
    parts: Vec<Part>,
    size: (u32, u32),
    resizable: bool,
    theme_over_surface: bool,
    implem: Box<dyn FnMut(FrameRequest, u32, DispatchData)>,
    maximized: bool,
    fullscreened: bool,
    buttons: (bool, bool, bool),
}

impl Inner {
    fn find_surface(&self, surface: &wl_surface::WlSurface) -> Location {
        if self.parts.is_empty() {
            return Location::None;
        }

        if surface.as_ref().equals(self.parts[HEAD].surface.as_ref()) {
            Location::Head
        } else if surface.as_ref().equals(self.parts[TOP].surface.as_ref()) {
            Location::Top
        } else if surface.as_ref().equals(self.parts[BOTTOM].surface.as_ref()) {
            Location::Bottom
        } else if surface.as_ref().equals(self.parts[LEFT].surface.as_ref()) {
            Location::Left
        } else if surface.as_ref().equals(self.parts[RIGHT].surface.as_ref()) {
            Location::Right
        } else {
            Location::None
        }
    }
}

fn precise_location(
    old: Location,
    width: u32,
    x: f64,
    y: f64,
    buttons: (bool, bool, bool),
) -> Location {
    match old {
        Location::Head | Location::Button(_) => find_button(x, y, width, buttons),

        Location::Top | Location::TopLeft | Location::TopRight => {
            if x <= f64::from(BORDER_SIZE) {
                Location::TopLeft
            } else if x >= f64::from(width + BORDER_SIZE) {
                Location::TopRight
            } else {
                Location::Top
            }
        }

        Location::Bottom | Location::BottomLeft | Location::BottomRight => {
            if x <= f64::from(BORDER_SIZE) {
                Location::BottomLeft
            } else if x >= f64::from(width + BORDER_SIZE) {
                Location::BottomRight
            } else {
                Location::Bottom
            }
        }

        other => other,
    }
}

fn find_button(x: f64, y: f64, w: u32, buttons: (bool, bool, bool)) -> Location {
    if (w >= HEADER_SIZE)
        && (x >= f64::from(w - HEADER_SIZE))
        && (x <= f64::from(w))
        && (y <= f64::from(HEADER_SIZE))
        && (y >= f64::from(0))
    {
        // first button
        match buttons {
            (true, _, _) => Location::Button(UIButton::Close),
            (false, true, _) => Location::Button(UIButton::Maximize),
            (false, false, true) => Location::Button(UIButton::Minimize),
            _ => Location::Head,
        }
    } else if (w >= 2 * HEADER_SIZE)
        && (x >= f64::from(w - 2 * HEADER_SIZE))
        && (x <= f64::from(w - HEADER_SIZE))
        && (y <= f64::from(HEADER_SIZE))
        && (y >= f64::from(0))
    {
        // second button
        match buttons {
            (true, true, _) => Location::Button(UIButton::Maximize),
            (false, true, true) => Location::Button(UIButton::Minimize),
            _ => Location::Head,
        }
    } else if (w >= 3 * HEADER_SIZE)
        && (x >= f64::from(w - 3 * HEADER_SIZE))
        && (x <= f64::from(w - 2 * HEADER_SIZE))
        && (y <= f64::from(HEADER_SIZE))
        && (y >= f64::from(0))
    {
        // third button
        match buttons {
            (true, true, true) => Location::Button(UIButton::Minimize),
            _ => Location::Head,
        }
    } else {
        Location::Head
    }
}

/// A clean, modern and stylish set of decorations.
///
/// This class draws clean and modern decorations with
/// buttons inspired by breeze, material hover shade and
/// a white header background.
///
/// `ConceptFrame` is hiding its `ClientSide` decorations
/// in a `Fullscreen` state and brings them back if those are
/// visible when unsetting `Fullscreen` state.
pub struct ConceptFrame {
    base_surface: wl_surface::WlSurface,
    compositor: Attached<wl_compositor::WlCompositor>,
    subcompositor: Attached<wl_subcompositor::WlSubcompositor>,
    inner: Rc<RefCell<Inner>>,
    pools: DoubleMemPool,
    active: WindowState,
    hidden: bool,
    pointers: Vec<ThemedPointer>,
    themer: ThemeManager,
    surface_version: u32,
    config: ConceptConfig,
    title: Option<String>,
    font_data: Option<Result<Vec<u8>, ()>>,
}

impl Frame for ConceptFrame {
    type Error = ::std::io::Error;
    type Config = ConceptConfig;
    fn init(
        base_surface: &wl_surface::WlSurface,
        compositor: &Attached<wl_compositor::WlCompositor>,
        subcompositor: &Attached<wl_subcompositor::WlSubcompositor>,
        shm: &Attached<wl_shm::WlShm>,
        theme_manager: Option<ThemeManager>,
        implementation: Box<dyn FnMut(FrameRequest, u32, DispatchData)>,
    ) -> Result<ConceptFrame, ::std::io::Error> {
        let (themer, theme_over_surface) = if let Some(theme_manager) = theme_manager {
            (theme_manager, false)
        } else {
            (ThemeManager::init(ThemeSpec::System, compositor.clone(), shm.clone()), true)
        };

        let inner = Rc::new(RefCell::new(Inner {
            parts: vec![],
            size: (1, 1),
            resizable: true,
            implem: implementation,
            theme_over_surface,
            maximized: false,
            fullscreened: false,
            buttons: (true, true, true),
        }));

        let my_inner = inner.clone();
        // Send a Refresh request on callback from DoubleMemPool as it will be fired when
        // None was previously returned from `pool()` and the draw was postponed
        let pools = DoubleMemPool::new(shm.clone(), move |ddata| {
            (&mut my_inner.borrow_mut().implem)(FrameRequest::Refresh, 0, ddata);
        })?;

        Ok(ConceptFrame {
            base_surface: base_surface.clone(),
            compositor: compositor.clone(),
            subcompositor: subcompositor.clone(),
            inner,
            pools,
            active: WindowState::Inactive,
            hidden: true,
            pointers: Vec::new(),
            themer,
            surface_version: compositor.as_ref().version(),
            config: ConceptConfig::default(),
            title: None,
            font_data: None,
        })
    }

    fn new_seat(&mut self, seat: &Attached<wl_seat::WlSeat>) {
        use self::wl_pointer::Event;
        let inner = self.inner.clone();
        let pointer = self.themer.theme_pointer_with_impl(
            seat,
            move |event, pointer: ThemedPointer, ddata: DispatchData| {
                let data: &RefCell<PointerUserData> = pointer.as_ref().user_data().get().unwrap();
                let mut data = data.borrow_mut();
                let mut inner = inner.borrow_mut();
                match event {
                    Event::Enter { serial, surface, surface_x, surface_y } => {
                        data.location = precise_location(
                            inner.find_surface(&surface),
                            inner.size.0,
                            surface_x,
                            surface_y,
                            inner.buttons,
                        );
                        data.position = (surface_x, surface_y);
                        change_pointer(&pointer, &inner, data.location, Some(serial))
                    }
                    Event::Leave { serial, .. } => {
                        data.location = Location::None;
                        change_pointer(&pointer, &inner, data.location, Some(serial));
                        (&mut inner.implem)(FrameRequest::Refresh, 0, ddata);
                    }
                    Event::Motion { surface_x, surface_y, .. } => {
                        data.position = (surface_x, surface_y);
                        let newpos = precise_location(
                            data.location,
                            inner.size.0,
                            surface_x,
                            surface_y,
                            inner.buttons,
                        );
                        if newpos != data.location {
                            match (newpos, data.location) {
                                (Location::Button(_), _) | (_, Location::Button(_)) => {
                                    // pointer movement involves a button, request refresh
                                    (&mut inner.implem)(FrameRequest::Refresh, 0, ddata);
                                }
                                _ => (),
                            }
                            // we changed of part of the decoration, pointer image
                            // may need to be changed
                            data.location = newpos;
                            change_pointer(&pointer, &inner, data.location, None)
                        }
                    }
                    Event::Button { serial, button, state, .. } => {
                        if state == wl_pointer::ButtonState::Pressed {
                            let request = match button {
                                // Left mouse button.
                                0x110 => request_for_location_on_lmb(
                                    &data,
                                    inner.maximized,
                                    inner.resizable,
                                ),
                                // Right mouse button.
                                0x111 => request_for_location_on_rmb(&data),
                                _ => None,
                            };

                            if let Some(request) = request {
                                (&mut inner.implem)(request, serial, ddata);
                            }
                        }
                    }
                    _ => {}
                }
            },
        );
        pointer.as_ref().user_data().set(|| {
            RefCell::new(PointerUserData {
                location: Location::None,
                position: (0.0, 0.0),
                seat: seat.detach(),
            })
        });
        self.pointers.push(pointer);
    }

    fn remove_seat(&mut self, seat: &wl_seat::WlSeat) {
        self.pointers.retain(|pointer| {
            let user_data = pointer.as_ref().user_data().get::<RefCell<PointerUserData>>().unwrap();
            let guard = user_data.borrow_mut();
            if &guard.seat == seat {
                pointer.release();
                false
            } else {
                true
            }
        });
    }

    fn set_states(&mut self, states: &[State]) -> bool {
        let mut inner = self.inner.borrow_mut();
        let mut need_redraw = false;

        // Process active.
        let new_active = if states.contains(&State::Activated) {
            WindowState::Active
        } else {
            WindowState::Inactive
        };
        need_redraw |= new_active != self.active;
        self.active = new_active;

        // Process maximized.
        let new_maximized = states.contains(&State::Maximized);
        need_redraw |= new_maximized != inner.maximized;
        inner.maximized = new_maximized;

        // Process fullscreened.
        let new_fullscreened = states.contains(&State::Fullscreen);
        need_redraw |= new_fullscreened != inner.fullscreened;
        inner.fullscreened = new_fullscreened;

        need_redraw
    }

    fn set_hidden(&mut self, hidden: bool) {
        self.hidden = hidden;
        let mut inner = self.inner.borrow_mut();
        if !self.hidden {
            if inner.parts.is_empty() {
                inner.parts = vec![
                    Part::new(
                        &self.base_surface,
                        &self.compositor,
                        &self.subcompositor,
                        Some(Rc::clone(&self.inner)),
                    ),
                    Part::new(&self.base_surface, &self.compositor, &self.subcompositor, None),
                    Part::new(&self.base_surface, &self.compositor, &self.subcompositor, None),
                    Part::new(&self.base_surface, &self.compositor, &self.subcompositor, None),
                    Part::new(&self.base_surface, &self.compositor, &self.subcompositor, None),
                ];
            }
        } else {
            inner.parts.clear();
        }
    }

    fn set_resizable(&mut self, resizable: bool) {
        self.inner.borrow_mut().resizable = resizable;
    }

    fn resize(&mut self, newsize: (u32, u32)) {
        self.inner.borrow_mut().size = newsize;
    }

    fn redraw(&mut self) {
        let inner = self.inner.borrow_mut();

        // Don't draw borders if the frame explicitly hidden or fullscreened.
        if self.hidden || inner.fullscreened {
            // Don't draw the borders.
            for p in inner.parts.iter() {
                p.surface.attach(None, 0, 0);
                p.surface.commit();
            }
            return;
        }

        // `parts` can't be empty here, since the initial state for `self.hidden` is true, and
        // they will be created once `self.hidden` will become `false`.
        let parts = &inner.parts;

        let scales: Vec<u32> = parts
            .iter()
            .map(|part| crate::surface::get_surface_scale_factor(&part.surface) as u32)
            .collect();

        let (width, height) = inner.size;

        // Use header scale for all the thing.
        let header_scale = scales[HEAD];

        let scaled_header_height = HEADER_SIZE * header_scale;
        let scaled_header_width = width * header_scale;

        {
            // grab the current pool
            let pool = match self.pools.pool() {
                Some(pool) => pool,
                None => return,
            };
            let lr_surfaces_scale = max(scales[LEFT], scales[RIGHT]);
            let tp_surfaces_scale = max(scales[TOP], scales[BOTTOM]);

            // resize the pool as appropriate
            let pxcount = (scaled_header_height * scaled_header_width)
                + max(
                    (width + 2 * BORDER_SIZE) * BORDER_SIZE * tp_surfaces_scale * tp_surfaces_scale,
                    (height + HEADER_SIZE) * BORDER_SIZE * lr_surfaces_scale * lr_surfaces_scale,
                );

            pool.resize(4 * pxcount as usize).expect("I/O Error while redrawing the borders");

            // draw the white header bar
            {
                let mmap = pool.mmap();
                {
                    let color = self.config.primary_color.get_for(self.active).into();

                    let mut header_canvas = Canvas::new(
                        &mut mmap
                            [0..scaled_header_height as usize * scaled_header_width as usize * 4],
                        scaled_header_width as usize,
                        scaled_header_height as usize,
                        scaled_header_width as usize * 4,
                        Endian::native(),
                    );
                    header_canvas.clear();

                    let header_bar = rectangle::Rectangle::new(
                        (0, 0),
                        (scaled_header_width as usize, scaled_header_height as usize),
                        None,
                        Some(color),
                    );
                    header_canvas.draw(&header_bar);

                    draw_buttons(
                        &mut header_canvas,
                        width,
                        header_scale,
                        inner.resizable,
                        self.active,
                        &self
                            .pointers
                            .iter()
                            .flat_map(|p| {
                                if p.as_ref().is_alive() {
                                    let data: &RefCell<PointerUserData> =
                                        p.as_ref().user_data().get().unwrap();
                                    Some(data.borrow().location)
                                } else {
                                    None
                                }
                            })
                            .collect::<Vec<Location>>(),
                        &self.config,
                    );
                    if let Some((ref font_face, font_size)) = self.config.title_font {
                        if let Some(title) = self.title.clone() {
                            // If theres no stored font data, find the first ttf regular sans font and
                            // store it
                            if self.font_data.is_none() {
                                let font_bytes = fontconfig::FontConfig::new()
                                    .ok()
                                    .and_then(|font_config| {
                                        font_config.get_regular_family_fonts(&font_face).ok()
                                    })
                                    .and_then(|regular_family_fonts| {
                                        regular_family_fonts
                                            .iter()
                                            .cloned()
                                            .find(|p| p.extension().map_or(false, |e| e == "ttf"))
                                    })
                                    .and_then(|font| std::fs::read(font).ok());
                                match font_bytes {
                                    Some(bytes) => self.font_data = Some(Ok(bytes)),
                                    None => {
                                        error!("No font could be found");
                                        self.font_data = Some(Err(()))
                                    }
                                }
                            }

                            // Create text from stored title and font data
                            if let Some(Ok(ref font_data)) = self.font_data {
                                let title_color = self.config.title_color.get_for(self.active);
                                let mut title_text = text::Text::new(
                                    (
                                        0,
                                        (HEADER_SIZE as usize / 2)
                                            .saturating_sub((font_size / 2.0).ceil() as usize)
                                            * header_scale as usize,
                                    ),
                                    title_color.into(),
                                    font_data,
                                    font_size * header_scale as f32,
                                    1.0,
                                    title,
                                );

                                let mut button_count = 0isize;
                                if self.config.close_button.is_some() {
                                    button_count += 1;
                                }
                                if self.config.maximize_button.is_some() {
                                    button_count += 1;
                                }
                                if self.config.minimize_button.is_some() {
                                    button_count += 1;
                                }

                                let scaled_button_size =
                                    HEADER_SIZE as isize * header_scale as isize;
                                let button_space = button_count * scaled_button_size;
                                let scaled_header_width = width as isize * header_scale as isize;

                                // Check if text is bigger then the available width
                                if (scaled_header_width - button_space)
                                    > (title_text.get_width() as isize + scaled_button_size)
                                {
                                    title_text.pos.0 =
                                        (scaled_header_width - button_space) as usize / 2
                                            - (title_text.get_width() / 2);
                                    header_canvas.draw(&title_text);
                                }
                            }
                        }
                    }
                }

                // For each pixel in borders
                {
                    for b in &mut mmap
                        [scaled_header_height as usize * scaled_header_width as usize * 4..]
                    {
                        *b = 0x00;
                    }
                }
                if let Err(err) = mmap.flush() {
                    error!("Failed to flush frame memory map: {}", err);
                }
            }

            // Create the buffers
            // -> head-subsurface
            let buffer = pool.buffer(
                0,
                scaled_header_width as i32,
                scaled_header_height as i32,
                4 * scaled_header_width as i32,
                wl_shm::Format::Argb8888,
            );
            parts[HEAD].subsurface.set_position(0, -(HEADER_SIZE as i32));
            parts[HEAD].surface.attach(Some(&buffer), 0, 0);
            if self.surface_version >= 4 {
                parts[HEAD].surface.damage_buffer(
                    0,
                    0,
                    scaled_header_width as i32,
                    scaled_header_height as i32,
                );
            } else {
                // surface is old and does not support damage_buffer, so we damage
                // in surface coordinates and hope it is not rescaled
                parts[HEAD].surface.damage(0, 0, width as i32, HEADER_SIZE as i32);
            }
            parts[HEAD].surface.commit();

            // -> top-subsurface
            let buffer = pool.buffer(
                4 * (scaled_header_width * scaled_header_height) as i32,
                ((width + 2 * BORDER_SIZE) * scales[TOP]) as i32,
                (BORDER_SIZE * scales[TOP]) as i32,
                (4 * scales[TOP] * (width + 2 * BORDER_SIZE)) as i32,
                wl_shm::Format::Argb8888,
            );
            parts[TOP]
                .subsurface
                .set_position(-(BORDER_SIZE as i32), -(HEADER_SIZE as i32 + BORDER_SIZE as i32));
            parts[TOP].surface.attach(Some(&buffer), 0, 0);
            if self.surface_version >= 4 {
                parts[TOP].surface.damage_buffer(
                    0,
                    0,
                    ((width + 2 * BORDER_SIZE) * scales[TOP]) as i32,
                    (BORDER_SIZE * scales[TOP]) as i32,
                );
            } else {
                // surface is old and does not support damage_buffer, so we damage
                // in surface coordinates and hope it is not rescaled
                parts[TOP].surface.damage(
                    0,
                    0,
                    (width + 2 * BORDER_SIZE) as i32,
                    BORDER_SIZE as i32,
                );
            }
            parts[TOP].surface.commit();

            // -> bottom-subsurface
            let buffer = pool.buffer(
                4 * (scaled_header_width * scaled_header_height) as i32,
                ((width + 2 * BORDER_SIZE) * scales[BOTTOM]) as i32,
                (BORDER_SIZE * scales[BOTTOM]) as i32,
                (4 * scales[BOTTOM] * (width + 2 * BORDER_SIZE)) as i32,
                wl_shm::Format::Argb8888,
            );
            parts[BOTTOM].subsurface.set_position(-(BORDER_SIZE as i32), height as i32);
            parts[BOTTOM].surface.attach(Some(&buffer), 0, 0);
            if self.surface_version >= 4 {
                parts[BOTTOM].surface.damage_buffer(
                    0,
                    0,
                    ((width + 2 * BORDER_SIZE) * scales[BOTTOM]) as i32,
                    (BORDER_SIZE * scales[BOTTOM]) as i32,
                );
            } else {
                // surface is old and does not support damage_buffer, so we damage
                // in surface coordinates and hope it is not rescaled
                parts[BOTTOM].surface.damage(
                    0,
                    0,
                    (width + 2 * BORDER_SIZE) as i32,
                    BORDER_SIZE as i32,
                );
            }
            parts[BOTTOM].surface.commit();

            // -> left-subsurface
            let buffer = pool.buffer(
                4 * (scaled_header_width * scaled_header_height) as i32,
                (BORDER_SIZE * scales[LEFT]) as i32,
                ((height + HEADER_SIZE) * scales[LEFT]) as i32,
                4 * (BORDER_SIZE * scales[LEFT]) as i32,
                wl_shm::Format::Argb8888,
            );
            parts[LEFT].subsurface.set_position(-(BORDER_SIZE as i32), -(HEADER_SIZE as i32));
            parts[LEFT].surface.attach(Some(&buffer), 0, 0);
            if self.surface_version >= 4 {
                parts[LEFT].surface.damage_buffer(
                    0,
                    0,
                    (BORDER_SIZE * scales[LEFT]) as i32,
                    ((height + HEADER_SIZE) * scales[LEFT]) as i32,
                );
            } else {
                // surface is old and does not support damage_buffer, so we damage
                // in surface coordinates and hope it is not rescaled
                parts[LEFT].surface.damage(0, 0, BORDER_SIZE as i32, (height + HEADER_SIZE) as i32);
            }
            parts[LEFT].surface.commit();

            // -> right-subsurface
            let buffer = pool.buffer(
                4 * (scaled_header_width * scaled_header_height) as i32,
                (BORDER_SIZE * scales[RIGHT]) as i32,
                ((height + HEADER_SIZE) * scales[RIGHT]) as i32,
                4 * (BORDER_SIZE * scales[RIGHT]) as i32,
                wl_shm::Format::Argb8888,
            );
            parts[RIGHT].subsurface.set_position(width as i32, -(HEADER_SIZE as i32));
            parts[RIGHT].surface.attach(Some(&buffer), 0, 0);
            if self.surface_version >= 4 {
                parts[RIGHT].surface.damage_buffer(
                    0,
                    0,
                    (BORDER_SIZE * scales[RIGHT]) as i32,
                    ((height + HEADER_SIZE) * scales[RIGHT]) as i32,
                );
            } else {
                // surface is old and does not support damage_buffer, so we damage
                // in surface coordinates and hope it is not rescaled
                parts[RIGHT].surface.damage(
                    0,
                    0,
                    BORDER_SIZE as i32,
                    (height + HEADER_SIZE) as i32,
                );
            }
            parts[RIGHT].surface.commit();
        }
    }

    fn subtract_borders(&self, width: i32, height: i32) -> (i32, i32) {
        if self.hidden || self.inner.borrow().fullscreened {
            (width, height)
        } else {
            (width, height - HEADER_SIZE as i32)
        }
    }

    fn add_borders(&self, width: i32, height: i32) -> (i32, i32) {
        if self.hidden || self.inner.borrow().fullscreened {
            (width, height)
        } else {
            (width, height + HEADER_SIZE as i32)
        }
    }

    fn location(&self) -> (i32, i32) {
        if self.hidden || self.inner.borrow().fullscreened {
            (0, 0)
        } else {
            (0, -(HEADER_SIZE as i32))
        }
    }

    fn set_config(&mut self, config: ConceptConfig) {
        self.config = config;
        let mut inner = self.inner.borrow_mut();
        inner.buttons = (
            self.config.close_button.is_some(),
            self.config.maximize_button.is_some(),
            self.config.minimize_button.is_some(),
        );
    }

    fn set_title(&mut self, title: String) {
        self.title = Some(title);
    }
}

impl Drop for ConceptFrame {
    fn drop(&mut self) {
        for ptr in self.pointers.drain(..) {
            if ptr.as_ref().version() >= 3 {
                ptr.release();
            }
        }
    }
}

fn change_pointer(pointer: &ThemedPointer, inner: &Inner, location: Location, serial: Option<u32>) {
    // Prevent theming of the surface if it was requested.
    if !inner.theme_over_surface && location == Location::None {
        return;
    }

    let name = match location {
        // If we can't resize a frame we shouldn't show resize cursors.
        _ if !inner.resizable => "left_ptr",
        Location::Top => "top_side",
        Location::TopRight => "top_right_corner",
        Location::Right => "right_side",
        Location::BottomRight => "bottom_right_corner",
        Location::Bottom => "bottom_side",
        Location::BottomLeft => "bottom_left_corner",
        Location::Left => "left_side",
        Location::TopLeft => "top_left_corner",
        _ => "left_ptr",
    };

    if pointer.set_cursor(name, serial).is_err() {
        error!("Failed to set cursor");
    }
}

fn request_for_location_on_lmb(
    pointer_data: &PointerUserData,
    maximized: bool,
    resizable: bool,
) -> Option<FrameRequest> {
    use wayland_protocols::xdg_shell::client::xdg_toplevel::ResizeEdge;
    match pointer_data.location {
        Location::Top if resizable => {
            Some(FrameRequest::Resize(pointer_data.seat.clone(), ResizeEdge::Top))
        }
        Location::TopLeft if resizable => {
            Some(FrameRequest::Resize(pointer_data.seat.clone(), ResizeEdge::TopLeft))
        }
        Location::Left if resizable => {
            Some(FrameRequest::Resize(pointer_data.seat.clone(), ResizeEdge::Left))
        }
        Location::BottomLeft if resizable => {
            Some(FrameRequest::Resize(pointer_data.seat.clone(), ResizeEdge::BottomLeft))
        }
        Location::Bottom if resizable => {
            Some(FrameRequest::Resize(pointer_data.seat.clone(), ResizeEdge::Bottom))
        }
        Location::BottomRight if resizable => {
            Some(FrameRequest::Resize(pointer_data.seat.clone(), ResizeEdge::BottomRight))
        }
        Location::Right if resizable => {
            Some(FrameRequest::Resize(pointer_data.seat.clone(), ResizeEdge::Right))
        }
        Location::TopRight if resizable => {
            Some(FrameRequest::Resize(pointer_data.seat.clone(), ResizeEdge::TopRight))
        }
        Location::Head => Some(FrameRequest::Move(pointer_data.seat.clone())),
        Location::Button(UIButton::Close) => Some(FrameRequest::Close),
        Location::Button(UIButton::Maximize) => {
            if maximized {
                Some(FrameRequest::UnMaximize)
            } else {
                Some(FrameRequest::Maximize)
            }
        }
        Location::Button(UIButton::Minimize) => Some(FrameRequest::Minimize),
        _ => None,
    }
}

fn request_for_location_on_rmb(pointer_data: &PointerUserData) -> Option<FrameRequest> {
    match pointer_data.location {
        Location::Head | Location::Button(_) => Some(FrameRequest::ShowMenu(
            pointer_data.seat.clone(),
            pointer_data.position.0 as i32,
            // We must offset it by header size for precise position.
            pointer_data.position.1 as i32 - HEADER_SIZE as i32,
        )),
        _ => None,
    }
}

// average of the two colors, approximately taking into account gamma correction
// result is as transparent as the most transparent color
fn mix_colors(x: ARGBColor, y: ARGBColor) -> ARGBColor {
    #[inline]
    fn gamma_mix(x: u8, y: u8) -> u8 {
        let x = x as f32 / 255.0;
        let y = y as f32 / 255.0;
        let z = ((x * x + y * y) / 2.0).sqrt();
        (z * 255.0) as u8
    }

    ARGBColor {
        a: x.a.min(y.a),
        r: gamma_mix(x.r, y.r),
        g: gamma_mix(x.g, y.g),
        b: gamma_mix(x.b, y.b),
    }
}

fn draw_buttons(
    canvas: &mut Canvas,
    width: u32,
    scale: u32,
    maximizable: bool,
    state: WindowState,
    mouses: &[Location],
    config: &ConceptConfig,
) {
    let scale = scale as usize;

    // Draw seperator between header and window contents
    let line_color = config.secondary_color.get_for(state);
    for i in 1..=scale {
        let y = HEADER_SIZE as usize * scale - i;
        let division_line =
            line::Line::new((0, y), (width as usize * scale, y), line_color.into(), false);
        canvas.draw(&division_line);
    }

    let mut drawn_buttons = 0usize;

    if width >= HEADER_SIZE {
        if let Some((ref icon_config, ref btn_config)) = config.close_button {
            // Draw the close button
            let btn_state = if mouses.iter().any(|&l| l == Location::Button(UIButton::Close)) {
                ButtonState::Hovered
            } else {
                ButtonState::Idle
            };

            let icon_color = icon_config.get_for(btn_state).get_for(state);
            let button_color = btn_config.get_for(btn_state).get_for(state);

            draw_button(canvas, 0, scale, button_color, mix_colors(button_color, line_color));
            draw_icon(canvas, 0, scale, icon_color, Icon::Close);
            drawn_buttons += 1;
        }
    }

    if width as usize >= (drawn_buttons + 1) * HEADER_SIZE as usize {
        if let Some((ref icon_config, ref btn_config)) = config.maximize_button {
            let btn_state = if !maximizable {
                ButtonState::Disabled
            } else if mouses.iter().any(|&l| l == Location::Button(UIButton::Maximize)) {
                ButtonState::Hovered
            } else {
                ButtonState::Idle
            };

            let icon_color = icon_config.get_for(btn_state).get_for(state);
            let button_color = btn_config.get_for(btn_state).get_for(state);

            draw_button(
                canvas,
                drawn_buttons * HEADER_SIZE as usize,
                scale,
                button_color,
                mix_colors(button_color, line_color),
            );
            draw_icon(
                canvas,
                drawn_buttons * HEADER_SIZE as usize,
                scale,
                icon_color,
                Icon::Maximize,
            );
            drawn_buttons += 1;
        }
    }

    if width as usize >= (drawn_buttons + 1) * HEADER_SIZE as usize {
        if let Some((ref icon_config, ref btn_config)) = config.minimize_button {
            let btn_state = if mouses.iter().any(|&l| l == Location::Button(UIButton::Minimize)) {
                ButtonState::Hovered
            } else {
                ButtonState::Idle
            };

            let icon_color = icon_config.get_for(btn_state).get_for(state);
            let button_color = btn_config.get_for(btn_state).get_for(state);

            draw_button(
                canvas,
                drawn_buttons * HEADER_SIZE as usize,
                scale,
                button_color,
                mix_colors(button_color, line_color),
            );
            draw_icon(
                canvas,
                drawn_buttons * HEADER_SIZE as usize,
                scale,
                icon_color,
                Icon::Minimize,
            );
        }
    }
}

enum Icon {
    Close,
    Maximize,
    Minimize,
}

fn draw_button(
    canvas: &mut Canvas,
    x_offset: usize,
    scale: usize,
    btn_color: ARGBColor,
    line_color: ARGBColor,
) {
    let h = HEADER_SIZE as usize;
    let x_start = canvas.width / scale - h - x_offset;
    // main square
    canvas.draw(&rectangle::Rectangle::new(
        (x_start * scale, 0),
        (h * scale, (h - 1) * scale),
        None,
        Some(btn_color.into()),
    ));
    // separation line
    canvas.draw(&rectangle::Rectangle::new(
        (x_start * scale, (h - 1) * scale),
        (h * scale, scale),
        None,
        Some(line_color.into()),
    ));
}

fn draw_icon(
    canvas: &mut Canvas,
    x_offset: usize,
    scale: usize,
    icon_color: ARGBColor,
    icon: Icon,
) {
    let h = HEADER_SIZE as usize;
    let cx = canvas.width / scale - h / 2 - x_offset;
    let cy = h / 2;
    let s = scale;

    match icon {
        Icon::Close => {
            // Draw cross to represent the close button
            for i in 0..2 * scale {
                canvas.draw(&line::Line::new(
                    ((cx - 4) * s + i, (cy - 4) * s),
                    ((cx + 4) * s, (cy + 4) * s - i),
                    icon_color.into(),
                    true,
                ));
                canvas.draw(&line::Line::new(
                    ((cx - 4) * s, (cy - 4) * s + i),
                    ((cx + 4) * s - i, (cy + 4) * s),
                    icon_color.into(),
                    true,
                ));
                canvas.draw(&line::Line::new(
                    ((cx + 4) * s - i, (cy - 4) * s),
                    ((cx - 4) * s, (cy + 4) * s - i),
                    icon_color.into(),
                    true,
                ));
                canvas.draw(&line::Line::new(
                    ((cx + 4) * s, (cy - 4) * s + i),
                    ((cx - 4) * s + i, (cy + 4) * s),
                    icon_color.into(),
                    true,
                ));
            }
        }
        Icon::Maximize => {
            for i in 0..3 * scale {
                canvas.draw(&line::Line::new(
                    ((cx - 4) * s - i, (cy + 2) * s),
                    (cx * s, (cy - 2) * s - i),
                    icon_color.into(),
                    true,
                ));
                canvas.draw(&line::Line::new(
                    ((cx + 4) * s + i, (cy + 2) * s),
                    (cx * s, (cy - 2) * s - i),
                    icon_color.into(),
                    true,
                ));
            }
        }
        Icon::Minimize => {
            for i in 0..3 * scale {
                canvas.draw(&line::Line::new(
                    ((cx - 4) * s - i, (cy - 3) * s),
                    (cx * s, (cy + 1) * s + i),
                    icon_color.into(),
                    true,
                ));
                canvas.draw(&line::Line::new(
                    ((cx + 4) * s + i, (cy - 3) * s),
                    (cx * s, (cy + 1) * s + i),
                    icon_color.into(),
                    true,
                ));
            }
        }
    }
}