-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathlib.rs
More file actions
1134 lines (975 loc) · 32.8 KB
/
Copy pathlib.rs
File metadata and controls
1134 lines (975 loc) · 32.8 KB
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
#![deny(
clippy::print_stderr,
clippy::print_stdout,
clippy::dbg_macro,
clippy::exit,
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing,
clippy::string_slice
)]
use std::error::Error;
use std::mem;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;
use tiny_skia::{
Color, FillRule, Mask, Path, PathBuilder, Pixmap, PixmapMut, PixmapPaint, Point, Rect,
Transform,
};
use smithay_client_toolkit::reexports::client::backend::ObjectId;
use smithay_client_toolkit::reexports::client::protocol::wl_shm;
use smithay_client_toolkit::reexports::client::protocol::wl_surface::WlSurface;
use smithay_client_toolkit::reexports::client::{Proxy, QueueHandle};
use smithay_client_toolkit::reexports::csd_frame::{
CursorIcon, DecorationsFrame, FrameAction, FrameClick, WindowManagerCapabilities, WindowState,
};
use smithay_client_toolkit::compositor::{CompositorHandler, CompositorState, Region, SurfaceData};
use smithay_client_toolkit::output::OutputHandler;
use smithay_client_toolkit::shell::WaylandSurface;
use smithay_client_toolkit::shm::{slot::SlotPool, Shm};
use smithay_client_toolkit::subcompositor::SubcompositorState;
mod buttons;
mod config;
mod parts;
mod pointer;
mod shadow;
pub mod theme;
mod title;
mod wl_typed;
use crate::parts::{LayoutConfig, PartId};
use crate::theme::{ColorMap, ColorTheme, CORNER_RADIUS, HEADER_SIZE, RESIZE_HANDLE_CORNER_SIZE};
use buttons::Buttons;
use config::get_button_layout_config;
use parts::DecorationParts;
use pointer::{Location, MouseState};
use shadow::Shadow;
use title::TitleText;
use wl_typed::WlTyped;
/// XXX this is not result, so `must_use` when needed.
type SkiaResult = Option<()>;
/// A simple set of decorations
#[derive(Debug)]
pub struct AdwaitaFrame<State> {
/// The base surface used to create the window.
base_surface: WlTyped<WlSurface, SurfaceData<()>>,
compositor: Arc<CompositorState>,
/// Subcompositor to create/drop subsurfaces ondemand.
subcompositor: Arc<SubcompositorState>,
/// Queue handle to perform object creation.
queue_handle: QueueHandle<State>,
/// The drawable decorations, `None` when hidden.
decorations: Option<DecorationParts>,
/// Memory pool to allocate the buffers for the decorations.
pool: SlotPool,
/// Whether the frame should be redrawn.
dirty: bool,
/// Whether the drawing should be synced with the main surface.
should_sync: bool,
/// Scale factor used for the surface.
scale_factor: u32,
/// Whether the frame is resizable.
resizable: bool,
buttons: Buttons,
state: WindowState,
wm_capabilities: WindowManagerCapabilities,
mouse: MouseState,
theme: ColorTheme,
title: Option<String>,
title_text: Option<TitleText>,
shadow: Shadow,
/// Draw decorations but without the titlebar
hide_titlebar: bool,
hide_border: bool,
width: NonZeroU32,
height: NonZeroU32,
}
impl<State> AdwaitaFrame<State>
where
State: CompositorHandler + OutputHandler + 'static,
{
pub fn new(
base_surface: &impl WaylandSurface,
shm: &Shm,
compositor: Arc<CompositorState>,
subcompositor: Arc<SubcompositorState>,
queue_handle: QueueHandle<State>,
frame_config: FrameConfig,
) -> Result<Self, Box<dyn Error>> {
let base_surface = WlTyped::wrap::<State>(base_surface.wl_surface().clone());
let pool = SlotPool::new(1, shm)?;
let decorations = Some(DecorationParts::new(
&base_surface,
&subcompositor,
&queue_handle,
));
let theme = frame_config.theme;
Ok(AdwaitaFrame {
base_surface,
decorations,
pool,
compositor,
subcompositor,
queue_handle,
dirty: true,
scale_factor: 1,
should_sync: true,
title: None,
title_text: TitleText::new(theme.active.font_color),
theme,
buttons: Buttons::new(get_button_layout_config()),
mouse: Default::default(),
state: WindowState::empty(),
wm_capabilities: WindowManagerCapabilities::all(),
resizable: true,
shadow: Shadow::default(),
hide_titlebar: frame_config.hide_titlebar,
hide_border: frame_config.hide_border,
width: NonZeroU32::MIN,
height: NonZeroU32::MIN,
})
}
/// Update the current frame config.
pub fn set_config(&mut self, config: FrameConfig) {
self.theme = config.theme;
self.dirty = true;
if self.hide_titlebar != config.hide_titlebar || self.hide_border != config.hide_border {
self.hide_titlebar = config.hide_titlebar;
self.hide_border = config.hide_border;
let layout_config = self.layout_config();
if let Some(decorations) = self.decorations.as_mut() {
decorations.relayout(layout_config);
}
}
}
fn precise_location(
&self,
location: Location,
decoration: &DecorationParts,
x: f64,
y: f64,
) -> Location {
let header_width = decoration.header().surface_rect.width;
let side_height = decoration.side_height();
let edge_size = theme::edge_size(self.hide_border);
let left_corner_x = edge_size + RESIZE_HANDLE_CORNER_SIZE;
let right_corner_x = (header_width + edge_size).saturating_sub(RESIZE_HANDLE_CORNER_SIZE);
let top_corner_y = RESIZE_HANDLE_CORNER_SIZE;
let bottom_corner_y = side_height.saturating_sub(RESIZE_HANDLE_CORNER_SIZE);
match location {
Location::Head | Location::Button(_) => self.buttons.find_button(x, y),
Location::Top | Location::TopLeft | Location::TopRight => {
if x <= f64::from(left_corner_x) {
Location::TopLeft
} else if x >= f64::from(right_corner_x) {
Location::TopRight
} else {
Location::Top
}
}
Location::Bottom | Location::BottomLeft | Location::BottomRight => {
if x <= f64::from(left_corner_x) {
Location::BottomLeft
} else if x >= f64::from(right_corner_x) {
Location::BottomRight
} else {
Location::Bottom
}
}
Location::Left => {
if y <= f64::from(top_corner_y) {
Location::TopLeft
} else if y >= f64::from(bottom_corner_y) {
Location::BottomLeft
} else {
Location::Left
}
}
Location::Right => {
if y <= f64::from(top_corner_y) {
Location::TopRight
} else if y >= f64::from(bottom_corner_y) {
Location::BottomRight
} else {
Location::Right
}
}
other => other,
}
}
fn layout_config(&self) -> LayoutConfig {
LayoutConfig {
width: self.width.get(),
height: self.height.get(),
hide_titlebar: self.hide_titlebar,
hide_border: self.hide_border,
hide_edges: self.state.contains(WindowState::MAXIMIZED),
}
}
fn redraw_inner(&mut self) -> Option<bool> {
let layout_config = self.layout_config();
let decorations = self.decorations.as_mut()?;
// Reset the dirty bit.
self.dirty = false;
let should_sync = mem::take(&mut self.should_sync);
// Don't draw decorations if the frame is fullscreened.
if self.state.contains(WindowState::FULLSCREEN) {
decorations.hide();
return Some(true);
} else {
decorations.show();
}
if layout_config.hide_titlebar {
decorations.hide_titlebar();
}
if layout_config.hide_edges {
// Don't draw the borders and shadows.
decorations.hide_edges();
}
let colors = self
.theme
.for_state(self.state.contains(WindowState::ACTIVATED));
decorations.relayout(layout_config);
if let Some(title_text) = self.title_text.as_mut() {
title_text.update_scale(self.scale_factor);
title_text.update_color(colors.font_color);
}
// Draw the borders.
for (idx, part) in decorations.parts().filter(|(_, part)| !part.hide) {
let scale = self.scale_factor;
let mut rect = part.surface_rect;
rect.width *= scale;
rect.height *= scale;
let (buffer, canvas) = match self.pool.create_buffer(
rect.width as i32,
rect.height as i32,
rect.width as i32 * 4,
wl_shm::Format::Argb8888,
) {
Ok((buffer, canvas)) => (buffer, canvas),
Err(_) => continue,
};
// Create the pixmap and fill with transparent color.
let mut pixmap = PixmapMut::from_bytes(canvas, rect.width, rect.height)?;
// Fill everything with transparent background, since we draw rounded corners and
// do invisible borders to enlarge the input zone.
pixmap.fill(Color::TRANSPARENT);
draw_part(
idx,
rect,
&mut pixmap,
self.title_text.as_ref().map(|t| t.pixmap()).unwrap_or(None),
scale,
self.resizable,
&self.state,
colors,
&self.buttons,
self.mouse.location,
self.hide_border,
self.hide_titlebar,
&mut self.shadow,
);
// Debug fill all subsurfaces with solid colors
if false {
match idx {
PartId::Top => {
pixmap.fill(Color::from_rgba8(255, 0, 0, 255));
}
PartId::Left => {
pixmap.fill(Color::from_rgba8(0, 0, 255, 255));
}
PartId::Right => {
pixmap.fill(Color::from_rgba8(0, 0, 255, 255));
}
PartId::Bottom => {
pixmap.fill(Color::from_rgba8(255, 0, 0, 255));
}
PartId::Header => {
pixmap.fill(Color::from_rgba8(0, 255, 255, 255));
}
};
}
if should_sync {
part.subsurface.set_sync();
} else {
part.subsurface.set_desync();
}
part.surface.set_buffer_scale(scale as i32);
part.subsurface.set_position(rect.x, rect.y);
buffer.attach_to(&part.surface).ok()?;
if part.surface.version() >= 4 {
part.surface.damage_buffer(0, 0, i32::MAX, i32::MAX);
} else {
part.surface.damage(0, 0, i32::MAX, i32::MAX);
}
if let Some(input_rect) = part.input_rect {
let input_region = Region::new(&*self.compositor).ok()?;
input_region.add(
input_rect.x,
input_rect.y,
input_rect.width as i32,
input_rect.height as i32,
);
part.surface
.set_input_region(Some(input_region.wl_region()));
}
part.surface.commit();
}
Some(should_sync)
}
}
impl<State> DecorationsFrame for AdwaitaFrame<State>
where
State: CompositorHandler + OutputHandler + 'static,
{
fn update_state(&mut self, state: WindowState) {
let difference = self.state.symmetric_difference(state);
self.state = state;
self.dirty |= difference.intersects(
WindowState::ACTIVATED
| WindowState::FULLSCREEN
| WindowState::MAXIMIZED
| WindowState::TILED,
);
}
fn update_wm_capabilities(&mut self, wm_capabilities: WindowManagerCapabilities) {
self.dirty |= self.wm_capabilities != wm_capabilities;
self.wm_capabilities = wm_capabilities;
self.buttons.update_wm_capabilities(wm_capabilities);
}
fn set_hidden(&mut self, hidden: bool) {
if hidden {
self.dirty = false;
let _ = self.pool.resize(1);
self.decorations = None;
} else if self.decorations.is_none() {
self.decorations = Some(DecorationParts::new(
&self.base_surface,
&self.subcompositor,
&self.queue_handle,
));
self.dirty = true;
self.should_sync = true;
}
}
fn set_resizable(&mut self, resizable: bool) {
self.dirty |= self.resizable != resizable;
self.resizable = resizable;
}
fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) {
self.width = width;
self.height = height;
let layout_config = self.layout_config();
let Some(decorations) = self.decorations.as_mut() else {
log::error!("trying to resize the hidden frame.");
return;
};
decorations.relayout(layout_config);
self.buttons
.arrange(width.get(), get_margin_h_lp(&self.state, self.hide_border));
self.dirty = true;
self.should_sync = true;
}
fn draw(&mut self) -> bool {
self.redraw_inner().unwrap_or(true)
}
fn subtract_borders(
&self,
width: NonZeroU32,
height: NonZeroU32,
) -> (Option<NonZeroU32>, Option<NonZeroU32>) {
if self.decorations.is_none()
|| self.state.contains(WindowState::FULLSCREEN)
|| self.hide_titlebar
{
(Some(width), Some(height))
} else {
(
Some(width),
NonZeroU32::new(height.get().saturating_sub(HEADER_SIZE)),
)
}
}
fn add_borders(&self, width: u32, height: u32) -> (u32, u32) {
if self.decorations.is_none()
|| self.state.contains(WindowState::FULLSCREEN)
|| self.hide_titlebar
{
(width, height)
} else {
(width, height + HEADER_SIZE)
}
}
fn location(&self) -> (i32, i32) {
if self.decorations.is_none()
|| self.state.contains(WindowState::FULLSCREEN)
|| self.hide_titlebar
{
(0, 0)
} else {
(0, -(HEADER_SIZE as i32))
}
}
fn set_title(&mut self, title: impl Into<String>) {
let new_title = title.into();
if let Some(title_text) = self.title_text.as_mut() {
title_text.update_title(new_title.clone());
}
self.title = Some(new_title);
self.dirty = true;
}
fn on_click(
&mut self,
timestamp: Duration,
click: FrameClick,
pressed: bool,
) -> Option<FrameAction> {
match click {
FrameClick::Normal => self.mouse.click(
timestamp,
pressed,
self.resizable,
&self.state,
&self.wm_capabilities,
),
FrameClick::Alternate => {
self.mouse
.alternate_click(pressed, &self.wm_capabilities, self.hide_border)
}
_ => None,
}
}
fn set_scaling_factor(&mut self, scale_factor: f64) {
// NOTE: Clamp it just in case to some ok-ish range.
self.scale_factor = scale_factor.clamp(0.1, 64.).ceil() as u32;
self.dirty = true;
self.should_sync = true;
}
fn click_point_moved(
&mut self,
_timestamp: Duration,
surface: &ObjectId,
x: f64,
y: f64,
) -> Option<CursorIcon> {
let decorations = self.decorations.as_ref()?;
let location = decorations.find_surface(surface);
if location == Location::None {
return None;
}
let old_location = self.mouse.location;
let location = self.precise_location(location, decorations, x, y);
let new_cursor = self.mouse.moved(location, x, y, self.resizable);
// Set dirty if we moved the cursor between the buttons.
self.dirty |= (matches!(old_location, Location::Button(_))
|| matches!(self.mouse.location, Location::Button(_)))
&& old_location != self.mouse.location;
Some(new_cursor)
}
fn click_point_left(&mut self) {
self.mouse.left()
}
fn is_dirty(&self) -> bool {
self.dirty
}
fn is_hidden(&self) -> bool {
self.decorations.is_none()
}
}
/// The configuration for the [`AdwaitaFrame`] frame.
#[derive(Debug, Clone)]
pub struct FrameConfig {
pub theme: ColorTheme,
/// Draw decorations but without the titlebar
pub hide_titlebar: bool,
/// Draw decorations but without the window border
pub hide_border: bool,
}
impl FrameConfig {
/// Create the new configuration with the given `theme`.
pub fn new(theme: ColorTheme) -> Self {
Self {
theme,
hide_titlebar: false,
hide_border: false,
}
}
/// This is equivalent of calling `FrameConfig::new(ColorTheme::auto())`.
///
/// For details see [`ColorTheme::auto`].
pub fn auto() -> Self {
Self::new(ColorTheme::auto())
}
/// This is equivalent of calling `FrameConfig::new(ColorTheme::light())`.
///
/// For details see [`ColorTheme::light`].
pub fn light() -> Self {
Self::new(ColorTheme::light())
}
/// This is equivalent of calling `FrameConfig::new(ColorTheme::dark())`.
///
/// For details see [`ColorTheme::dark`].
pub fn dark() -> Self {
Self::new(ColorTheme::dark())
}
/// Draw decorations but without the titlebar
pub fn hide_titlebar(mut self, hide: bool) -> Self {
self.hide_titlebar = hide;
self
}
/// Draw decorations but without the window border
pub fn hide_border(mut self, hide: bool) -> Self {
self.hide_border = hide;
self
}
}
#[allow(clippy::too_many_arguments)]
fn draw_part(
part_id: PartId,
rect: parts::Rect,
pixmap: &mut PixmapMut,
text_pixmap: Option<&Pixmap>,
scale: u32,
resizable: bool,
state: &WindowState,
colors: &ColorMap,
buttons: &Buttons,
mouse: Location,
hide_border: bool,
hide_titlebar: bool,
shadow: &mut Shadow,
) {
if !state.intersects(WindowState::TILED) {
shadow.draw(
pixmap,
scale,
state.contains(WindowState::ACTIVATED),
part_id,
hide_border,
);
}
let border_paint = colors.border_paint();
let border_size = theme::border_size(hide_border);
let border_size = border_size * scale;
// XXX we do all the math using integral types and then convert to f32 in the
// end to ensure that result is finite.
let border_rect = match part_id {
PartId::Header => {
return draw_headerbar(
pixmap,
text_pixmap,
scale as f32,
resizable,
state,
colors,
buttons,
mouse,
hide_border,
);
}
PartId::Left => {
let x = (rect.x.unsigned_abs() * scale) - border_size;
let y = rect.y.unsigned_abs() * scale;
Rect::from_xywh(
x as f32,
y as f32,
border_size as f32,
(rect.height - y) as f32,
)
}
PartId::Right => {
let y = rect.y.unsigned_abs() * scale;
Rect::from_xywh(0., y as f32, border_size as f32, (rect.height - y) as f32)
}
// We draw small visible border only bellow the window surface, no need to
// handle `TOP`.
PartId::Bottom => {
let x = (rect.x.unsigned_abs() * scale) - border_size;
Rect::from_xywh(
x as f32,
0.,
(rect.width - 2 * x) as f32,
border_size as f32,
)
}
// Unless titlebar is disabled
PartId::Top if hide_titlebar => {
let x = rect.x.unsigned_abs() * scale;
let x = x.saturating_sub(border_size);
let y = rect.y.unsigned_abs() * scale;
let y = y.saturating_sub(border_size);
Rect::from_xywh(
x as f32,
y as f32,
(rect.width - 2 * x) as f32,
border_size as f32,
)
}
PartId::Top => None,
};
// Fill the visible border, if present.
if let Some(border_rect) = border_rect {
pixmap.fill_rect(border_rect, &border_paint, Transform::identity(), None);
}
}
#[allow(clippy::too_many_arguments)]
fn draw_headerbar(
pixmap: &mut PixmapMut,
text_pixmap: Option<&Pixmap>,
scale: f32,
resizable: bool,
state: &WindowState,
colors: &ColorMap,
buttons: &Buttons,
mouse: Location,
hider_border: bool,
) {
let _ = draw_headerbar_bg(pixmap, scale, colors, state);
// Horizontal margin.
let margin_h = get_margin_h_lp(state, hider_border) * 2.0;
let canvas_w = pixmap.width() as f32;
let canvas_h = pixmap.height() as f32;
let header_w = canvas_w - margin_h * 2.0;
let header_h = canvas_h;
if let Some(text_pixmap) = text_pixmap {
const TEXT_OFFSET: f32 = 10.;
let offset_x = TEXT_OFFSET * scale;
let text_w = text_pixmap.width() as f32;
let text_h = text_pixmap.height() as f32;
let x = margin_h + header_w / 2. - text_w / 2.;
let y = header_h / 2. - text_h / 2.;
let left_buttons_end_x = buttons.left_buttons_end_x().unwrap_or(0.0) * scale;
let right_buttons_start_x =
buttons.right_buttons_start_x().unwrap_or(header_w / scale) * scale;
{
// We have enough space to center text
let (x, y, text_canvas_start_x) = if (x + text_w < right_buttons_start_x - offset_x)
&& (x > left_buttons_end_x + offset_x)
{
let text_canvas_start_x = x;
(x, y, text_canvas_start_x)
} else {
let x = left_buttons_end_x + offset_x;
let text_canvas_start_x = left_buttons_end_x + offset_x;
(x, y, text_canvas_start_x)
};
let text_canvas_end_x = right_buttons_start_x - x - offset_x;
// Ensure that text start within the bounds.
let x = x.max(margin_h + offset_x);
if let Some(clip) =
Rect::from_xywh(text_canvas_start_x, 0., text_canvas_end_x, canvas_h)
{
if let Some(mut mask) = Mask::new(canvas_w as u32, canvas_h as u32) {
mask.fill_path(
&PathBuilder::from_rect(clip),
FillRule::Winding,
false,
Transform::identity(),
);
pixmap.draw_pixmap(
x.round() as i32,
y as i32,
text_pixmap.as_ref(),
&PixmapPaint::default(),
Transform::identity(),
Some(&mask),
);
} else {
log::error!(
"Invalid mask width and height: w: {}, h: {}",
canvas_w as u32,
canvas_h as u32
);
}
}
}
}
// Draw the buttons.
buttons.draw(
margin_h, header_w, scale, colors, mouse, pixmap, resizable, state,
);
}
#[must_use]
fn draw_headerbar_bg(
pixmap: &mut PixmapMut,
scale: f32,
colors: &ColorMap,
state: &WindowState,
) -> SkiaResult {
let w = pixmap.width() as f32;
let h = pixmap.height() as f32;
let radius = if state.intersects(WindowState::MAXIMIZED | WindowState::TILED) {
0.
} else {
CORNER_RADIUS as f32 * scale
};
let bg = rounded_headerbar_shape(0., 0., w, h, radius)?;
pixmap.fill_path(
&bg,
&colors.headerbar_paint(),
FillRule::Winding,
Transform::identity(),
None,
);
pixmap.fill_rect(
Rect::from_xywh(0., h - 1., w, h)?,
&colors.border_paint(),
Transform::identity(),
None,
);
Some(())
}
fn rounded_headerbar_shape(x: f32, y: f32, width: f32, height: f32, radius: f32) -> Option<Path> {
// https://stackoverflow.com/a/27863181
let cubic_bezier_circle = 0.552_284_8 * radius;
let mut pb = PathBuilder::new();
let mut cursor = Point::from_xy(x, y);
// !!!
// This code is heavily "inspired" by https://gitlab.com/snakedye/snui/
// So technically it should be licensed under MPL-2.0, sorry about that 🥺 👉👈
// !!!
// Positioning the cursor
cursor.y += radius;
pb.move_to(cursor.x, cursor.y);
// Drawing the outline
let next = Point::from_xy(cursor.x + radius, cursor.y - radius);
pb.cubic_to(
cursor.x,
cursor.y - cubic_bezier_circle,
next.x - cubic_bezier_circle,
next.y,
next.x,
next.y,
);
cursor = next;
pb.line_to(
{
cursor.x = x + width - radius;
cursor.x
},
cursor.y,
);
let next = Point::from_xy(cursor.x + radius, cursor.y + radius);
pb.cubic_to(
cursor.x + cubic_bezier_circle,
cursor.y,
next.x,
next.y - cubic_bezier_circle,
next.x,
next.y,
);
cursor = next;
pb.line_to(cursor.x, {
cursor.y = y + height;
cursor.y
});
pb.line_to(
{
cursor.x = x;
cursor.x
},
cursor.y,
);
pb.close();
pb.finish()
}
// returns horizontal margin, logical points
fn get_margin_h_lp(state: &WindowState, hider_border: bool) -> f32 {
if state.intersects(WindowState::MAXIMIZED | WindowState::TILED) {
0.0
} else {
theme::border_size(hider_border) as f32
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::indexing_slicing, clippy::panic)]
use tiny_skia::{Paint, Shader};
use crate::parts::PartLayout;
use super::*;
pub mod utils {
use tiny_skia::Pixmap;
#[track_caller]
pub fn png_check(expected_path: &str, got_path: &str, got: &[u8]) {
std::fs::write(got_path, got).unwrap();
let expected = Pixmap::load_png(expected_path).unwrap();
let got = Pixmap::load_png(got_path).unwrap();
if expected != got {
panic!("Mismatch in the file: {got_path} != {expected_path}");
}
}
}
fn expected_file_path(name: &str) -> String {
format!("./tests/parts/{name}.expected.png")
}
fn got_file_path(name: &str) -> String {
format!("./tests/parts/{name}.got.png")
}
#[track_caller]
fn png_check(name: &str, got: &[u8]) {
utils::png_check(&expected_file_path(name), &got_file_path(name), got);
}
#[allow(unused)]
#[track_caller]
fn png_update_expected(name: &str, got: &[u8]) {
std::fs::write(expected_file_path(name), got).unwrap();
}
fn test_layout_config() -> LayoutConfig {
LayoutConfig {
width: 200,
height: 200,
hide_titlebar: false,
hide_border: false,
hide_edges: false,
}
}
fn draw_test_part(layout_config: LayoutConfig, part_id: PartId) -> Pixmap {
draw_test_part_with_scale(layout_config, part_id, 1)
}
fn draw_test_part_with_scale(
layout_config: LayoutConfig,
part_id: PartId,
scale: u32,
) -> Pixmap {
let layout = PartLayout::calc(layout_config);
let mut rect = layout[part_id as usize].surface_rect;
// TODO: Scaling should't be done in the test
rect.width *= scale;
rect.height *= scale;
let mut pixmap = Pixmap::new(rect.width, rect.height).unwrap();
let theme = ColorTheme::dark();
let colors = theme.for_state(true);
let buttons = Buttons::new(None);
let mut shadow = Shadow::default();
draw_part(
part_id,
rect,
&mut pixmap.as_mut(),
None,
scale,
true,
&WindowState::ACTIVATED,
colors,
&buttons,
Location::None,
layout_config.hide_border,
layout_config.hide_titlebar,
&mut shadow,
);