-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathpanel_space.rs
More file actions
2115 lines (1961 loc) · 80.4 KB
/
panel_space.rs
File metadata and controls
2115 lines (1961 loc) · 80.4 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
use std::{
cell::{Cell, RefCell},
collections::{HashMap, HashSet},
fmt::Debug,
os::{fd::OwnedFd, unix::net::UnixStream},
path::PathBuf,
rc::Rc,
str::FromStr,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use crate::{
iced::elements::{PanelSpaceElement, PopupMappedInternal, background::BackgroundElement},
workspaces_dbus::CosmicWorkspaces,
xdg_shell_wrapper::{
client::handlers::overlap::OverlapNotifyV1,
client_state::{ClientFocus, FocusStatus},
server_state::{ServerFocus, ServerPtrFocus},
shared_state::GlobalState,
space::{
ClientEglDisplay, ClientEglSurface, PanelPopup, PanelSubsurface, SpaceEvent,
Visibility, WrapperPopup, WrapperSpace, WrapperSubsurface,
},
util::smootherstep,
wp_fractional_scaling::FractionalScalingManager,
wp_security_context::SecurityContextManager,
wp_viewporter::ViewporterState,
},
};
use cctk::{
cosmic_protocols::overlap_notify::v1::client::zcosmic_overlap_notification_v1::ZcosmicOverlapNotificationV1,
sctk::shell::wlr_layer::Layer, wayland_client::Connection,
};
use cosmic::iced::id;
use freedesktop_desktop_entry::PathSource;
use launch_pad::process::Process;
use sctk::{
compositor::Region,
output::OutputInfo,
reexports::{
calloop,
client::{
Proxy, QueueHandle,
protocol::{wl_display::WlDisplay, wl_output as c_wl_output},
},
},
shell::{
WaylandSurface,
wlr_layer::{LayerSurface, LayerSurfaceConfigure},
xdg::XdgPositioner,
},
subcompositor::SubcompositorState,
};
use smithay::{
backend::{
egl::{
EGLContext,
context::{GlAttributes, PixelFormatRequirements},
display::EGLDisplay,
ffi::egl::SwapInterval,
surface::EGLSurface,
},
renderer::{Bind, damage::OutputDamageTracker, gles::GlesRenderer},
},
desktop::{PopupManager, Space, utils::bbox_from_surface_tree},
output::Output,
reexports::{
wayland_protocols::xdg::shell::client::xdg_positioner::{Anchor, Gravity},
wayland_server::{Client, DisplayHandle, Resource, backend::ClientId},
},
utils::{Logical, Rectangle, Size},
wayland::{
compositor::with_states,
fractional_scale::with_fractional_scale,
seat::WaylandFocus,
shell::xdg::{PopupSurface, PositionerState, ToplevelSurface},
},
};
use tokio::sync::{mpsc, oneshot};
use tracing::{error, info};
use wayland_egl::WlEglSurface;
use wayland_protocols::{
wp::{
fractional_scale::v1::client::wp_fractional_scale_v1::WpFractionalScaleV1,
security_context::v1::client::wp_security_context_v1::WpSecurityContextV1,
viewporter::client::wp_viewport::WpViewport,
},
xdg::shell::client::xdg_positioner::ConstraintAdjustment,
};
use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_shell_v1;
use cosmic_panel_config::{CosmicPanelBackground, CosmicPanelConfig, PanelAnchor};
use crate::{PanelCalloopMsg, iced::elements::CosmicMappedInternal};
use super::{Spacer, layout::OverflowSection};
pub enum AppletMsg {
NewProcess(String, Process),
NewNotificationsProcess(String, Process, Vec<(String, String)>, Vec<OwnedFd>),
NeedNewNotificationFd(oneshot::Sender<OwnedFd>),
ClientSocketPair(ClientId),
Cleanup(String),
}
impl Debug for AppletMsg {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NewProcess(arg0, _) => f.debug_tuple("NewProcess").field(arg0).finish(),
Self::NewNotificationsProcess(arg0, _, arg2, arg3) => f
.debug_tuple("NewNotificationsProcess")
.field(arg0)
.field(arg2)
.field(arg3)
.finish(),
Self::NeedNewNotificationFd(arg0) => {
f.debug_tuple("NeedNewNotificationFd").field(arg0).finish()
},
Self::ClientSocketPair(arg0) => f.debug_tuple("ClientSocketPair").field(arg0).finish(),
Self::Cleanup(arg0) => f.debug_tuple("Cleanup").field(arg0).finish(),
}
}
}
pub type Clients = Arc<Mutex<Vec<PanelClient>>>;
#[derive(Debug)]
pub struct PanelClient {
pub name: String,
pub path: Option<PathBuf>,
pub client: Option<Client>,
pub stream: Option<UnixStream>,
pub security_ctx: Option<WpSecurityContextV1>,
pub exec: Option<String>,
pub minimize_priority: Option<u32>,
pub requests_wayland_display: Option<bool>,
pub is_notification_applet: Option<bool>,
pub shrink_priority: Option<u32>,
pub shrink_min_size: Option<ClientShrinkSize>,
pub padding_shrinkable: bool,
/// If there is an existing popup, this applet with be pressed when hovered.
pub auto_popup_hover_press: Option<AppletAutoClickAnchor>,
}
#[derive(Debug, Clone, Copy)]
pub enum ClientShrinkSize {
AppletUnit(u32),
Pixel(u32),
}
impl ClientShrinkSize {
pub fn to_pixels(&self, applet_size: u32) -> u32 {
match self {
// TODO get spacing / padding from the theme or panel config?
Self::AppletUnit(units) => 4 + applet_size * units + 4 * units.saturating_sub(1),
Self::Pixel(pixels) => *pixels,
}
}
}
#[derive(Debug, Default, Clone, Copy)]
pub enum AppletAutoClickAnchor {
#[default]
Auto,
Left,
Right,
Top,
Bottom,
Center,
Start,
End,
}
impl FromStr for AppletAutoClickAnchor {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"left" => Ok(Self::Left),
"right" => Ok(Self::Right),
"top" => Ok(Self::Top),
"bottom" => Ok(Self::Bottom),
"center" => Ok(Self::Center),
"start" => Ok(Self::Start),
"end" => Ok(Self::End),
_ => Err(()),
}
}
}
impl PanelClient {
pub fn new(
name: String,
path: Option<PathBuf>,
client: Client,
stream: Option<UnixStream>,
) -> Self {
Self {
name,
path,
client: Some(client),
stream,
security_ctx: None,
exec: None,
minimize_priority: None,
requests_wayland_display: None,
is_notification_applet: None,
auto_popup_hover_press: None,
padding_shrinkable: false,
shrink_priority: None,
shrink_min_size: None,
}
}
pub fn is_flatpak(&self) -> bool {
let Some(path) = self.path.as_ref() else {
return false;
};
matches!(PathSource::guess_from(path), PathSource::SystemFlatpak | PathSource::LocalFlatpak)
}
}
impl Drop for PanelClient {
fn drop(&mut self) {
if let Some(stream) = self.stream.take() {
let _ = stream.shutdown(std::net::Shutdown::Both);
}
if let Some(security_ctx) = self.security_ctx.take() {
security_ctx.destroy();
}
}
}
#[derive(Debug, Clone)]
pub struct AnimatableState {
bg_color: [f32; 4],
border_radius: u32,
pub expanded: f32,
gap: u16,
}
#[derive(Debug, Clone)]
pub struct AnimateState {
start: AnimatableState,
end: AnimatableState,
pub cur: AnimatableState,
started_at: Instant,
progress: f32,
duration: Duration,
}
#[derive(Debug, Clone)]
pub struct PanelColors {
pub theme: cosmic::Theme,
pub color_override: Option<[f32; 4]>,
}
impl PanelColors {
pub fn new(theme: cosmic::Theme) -> Self {
Self { theme, color_override: None }
}
pub fn with_color_override(mut self, color_override: Option<[f32; 4]>) -> Self {
self.color_override = color_override;
self
}
pub fn bg_color(&self, alpha: f32) -> [f32; 4] {
self.color_override.unwrap_or_else(|| {
let c = self.theme.cosmic().bg_color();
[c.red, c.green, c.blue, alpha]
})
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
pub struct HoverTrack {
pub hover_id: Option<HoverId>,
pub generation: u32,
}
impl HoverTrack {
pub fn set_hover_id(&mut self, hover_id: Option<HoverId>) {
self.hover_id = hover_id;
self.generation += 1;
}
}
// first check if the motion is on a popup's client surface
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum HoverId {
Client(ClientId),
Overflow(id::Id),
}
#[derive(Debug)]
pub struct PanelSharedState {
pub c_focused_surface: Rc<RefCell<ClientFocus>>,
pub c_hovered_surface: Rc<RefCell<ClientFocus>>,
pub applet_tx: mpsc::Sender<AppletMsg>,
pub security_context_manager: RefCell<Option<SecurityContextManager>>,
pub cosmic_workspaces: Option<CosmicWorkspaces>,
pub panel_tx: calloop::channel::Sender<PanelCalloopMsg>,
pub loop_handle: calloop::LoopHandle<'static, GlobalState>,
pub workspaces_shown: Cell<bool>,
}
// space for the cosmic panel
#[derive(Debug)]
pub struct PanelSpace {
// XXX implicitly drops egl_surface first to avoid segfault
pub egl_surface: Option<EGLSurface>,
pub c_display: Option<WlDisplay>,
pub config: CosmicPanelConfig,
pub space: Space<CosmicMappedInternal>,
pub unmapped_windows: Vec<CosmicMappedInternal>,
pub damage_tracked_renderer: Option<OutputDamageTracker>,
pub clients_left: Clients,
pub clients_center: Clients,
pub clients_right: Clients,
pub overflow_left: Space<PopupMappedInternal>,
pub overflow_center: Space<PopupMappedInternal>,
pub overflow_right: Space<PopupMappedInternal>,
pub last_dirty: Option<Instant>,
// pending size of the panel
pub pending_dimensions: Option<Size<i32, Logical>>,
// suggested length of the panel
pub suggested_length: Option<u32>,
// size of the panel
pub actual_size: Size<i32, Logical>,
/// dimensions of the layer surface
/// this will be the same as the output size on the major axis of the panel
pub dimensions: Size<i32, Logical>,
// Logical size of the panel, with the applied animation state
pub container_length: i32,
pub is_dirty: bool,
pub space_event: Rc<Cell<Option<SpaceEvent>>>,
pub s_focused_surface: ServerFocus,
pub s_hovered_surface: ServerPtrFocus,
pub visibility: Visibility,
pub transitioning: bool,
pub output: Option<(c_wl_output::WlOutput, Output, OutputInfo)>,
pub s_display: Option<DisplayHandle>,
pub layer: Option<LayerSurface>,
pub layer_fractional_scale: Option<WpFractionalScaleV1>,
pub layer_viewport: Option<WpViewport>,
pub popups: Vec<WrapperPopup>,
pub subsurfaces: Vec<WrapperSubsurface>,
pub start_instant: Instant,
pub colors: PanelColors,
pub input_region: Option<Region>,
pub has_frame: bool,
pub scale: f64,
pub animate_state: Option<AnimateState>,
pub maximized: bool,
pub minimize_applet_rect: Rectangle<i32, Logical>,
pub scale_change_retries: u32,
/// Extra gap for stacked panels. Logical coordinate space.
pub additional_gap: i32,
/// Target gap for the panel on its anchored edge. Logical coordinate space.
pub anchor_gap: i32,
pub left_overflow_button_id: id::Id,
pub center_overflow_button_id: id::Id,
pub right_overflow_button_id: id::Id,
pub left_overflow_popup_id: id::Id,
pub center_overflow_popup_id: id::Id,
pub right_overflow_popup_id: id::Id,
pub overflow_popup: Option<(PanelPopup, OverflowSection)>,
pub remap_attempts: u32,
pub background_element: Option<BackgroundElement>,
pub is_background_dirty: bool,
pub last_minimize_update: Instant,
pub(crate) minimized_toplevels: HashSet<wayland_backend::client::ObjectId>,
pub(crate) toplevel_overlaps: HashSet<wayland_backend::client::ObjectId>,
pub(crate) layer_overlaps: HashMap<String, smithay::utils::Rectangle<i32, Logical>>,
pub(crate) logical_layer_start_overlap: i32,
pub(crate) logical_layer_end_overlap: i32,
pub(crate) notification_subscription: Option<ZcosmicOverlapNotificationV1>,
pub(crate) overlap_notify: Option<OverlapNotifyV1>,
pub(crate) hover_track: HoverTrack,
pub(crate) start_show_instant: Rc<RefCell<Option<Instant>>>,
pub shared: Rc<PanelSharedState>,
}
impl PanelSpace {
/// create a new space for the cosmic panel
pub fn new(
config: CosmicPanelConfig,
shared: &Rc<PanelSharedState>,
theme: cosmic::Theme,
s_display: DisplayHandle,
conn: &Connection,
) -> Self {
let name = format!("{}-{}", config.name, config.output);
let visibility =
if config.autohide.is_some() { Visibility::Hidden } else { Visibility::Visible };
Self {
config,
shared: shared.clone(),
space: Space::default(),
unmapped_windows: Vec::new(),
overflow_left: Space::default(),
overflow_center: Space::default(),
overflow_right: Space::default(),
clients_left: Default::default(),
clients_center: Default::default(),
clients_right: Default::default(),
last_dirty: Default::default(),
pending_dimensions: Default::default(),
space_event: Default::default(),
dimensions: Default::default(),
suggested_length: None,
output: Default::default(),
s_display: Some(s_display.clone()),
c_display: Some(conn.display().clone()),
layer: Default::default(),
layer_fractional_scale: Default::default(),
layer_viewport: Default::default(),
egl_surface: Default::default(),
popups: Default::default(),
subsurfaces: Default::default(),
visibility,
start_instant: Instant::now(),
s_focused_surface: Default::default(),
s_hovered_surface: Default::default(),
colors: PanelColors::new(theme),
actual_size: (0, 0).into(),
input_region: None,
damage_tracked_renderer: None,
is_dirty: false,
has_frame: true,
scale: 1.0,
animate_state: None,
maximized: false,
minimize_applet_rect: Default::default(),
container_length: 0,
scale_change_retries: 0,
additional_gap: 0,
left_overflow_button_id: id::Id::new(format!("{}-left-overflow-button", name)),
center_overflow_button_id: id::Id::new(format!("{}-center-overflow-button", name)),
right_overflow_button_id: id::Id::new(format!("{}-right-overflow-button", name)),
left_overflow_popup_id: id::Id::new(format!("{}-left-overflow-popup", name)),
center_overflow_popup_id: id::Id::new(format!("{}-center-overflow-popup", name)),
right_overflow_popup_id: id::Id::new(format!("{}-right-overflow-popup", name)),
overflow_popup: None,
remap_attempts: 0,
background_element: None,
is_background_dirty: false,
last_minimize_update: Instant::now() - Duration::from_secs(1),
anchor_gap: 0,
notification_subscription: None,
overlap_notify: None,
hover_track: HoverTrack::default(),
transitioning: false,
logical_layer_start_overlap: 0,
logical_layer_end_overlap: 0,
toplevel_overlaps: HashSet::new(),
layer_overlaps: HashMap::new(),
minimized_toplevels: HashSet::new(),
start_show_instant: Rc::new(RefCell::new(None)),
}
}
pub fn has_toplevel_overlap(&self) -> bool {
self.toplevel_overlaps
.iter()
.filter(|t| !self.minimized_toplevels.contains(&t))
.next()
.is_some()
}
pub fn crosswise(&self) -> i32 {
if self.config.is_horizontal() { self.dimensions.h } else { self.dimensions.w }
}
pub fn insert_layer_overlap(&mut self, id: String, rect: Rectangle<i32, Logical>) {
self.layer_overlaps.insert(id, rect);
self.apply_layer_overlaps();
}
pub fn remove_layer_overlap(&mut self, id: &str) {
self.layer_overlaps.remove(id);
self.apply_layer_overlaps();
}
pub fn has_layer_overlap(&self) -> bool {
!self.layer_overlaps.is_empty()
}
pub fn apply_layer_overlaps(&mut self) {
self.is_dirty = true;
self.is_background_dirty = true;
self.logical_layer_start_overlap = 0;
self.logical_layer_end_overlap = 0;
for rect in self.layer_overlaps.values() {
if self.config.is_horizontal() {
if rect.loc.x + rect.size.w < self.dimensions.w / 2 {
self.logical_layer_start_overlap =
self.logical_layer_start_overlap.max(rect.loc.x + rect.size.w)
- self.config.spacing as i32
+ self.config.margin as i32;
} else {
self.logical_layer_end_overlap =
self.logical_layer_end_overlap.max(self.dimensions.w - rect.loc.x)
- self.config.spacing as i32
+ self.config.margin as i32;
}
} else {
if rect.loc.y + rect.size.h < self.dimensions.h / 2 {
self.logical_layer_start_overlap =
self.logical_layer_start_overlap.max(rect.loc.y + rect.size.h)
- self.config.spacing as i32
+ self.config.margin as i32;
} else {
self.logical_layer_end_overlap =
self.logical_layer_end_overlap.max(self.dimensions.h - rect.loc.y)
- self.config.spacing as i32
+ self.config.margin as i32;
}
}
}
let layer_major = match self.config.anchor {
PanelAnchor::Left | PanelAnchor::Right => self.dimensions.h,
PanelAnchor::Top | PanelAnchor::Bottom => self.dimensions.w,
};
let container_length = self.container_length as i32;
let is_overlapping_start =
layer_major.saturating_sub(container_length) < 2 * self.logical_layer_start_overlap;
let is_overlapping_end =
layer_major.saturating_sub(container_length) < 2 * self.logical_layer_end_overlap;
if is_overlapping_start {
self.add_spacer_element_to_start(self.logical_layer_start_overlap as u32);
} else {
self.clear_spacer_start();
}
if is_overlapping_end {
self.add_spacer_element_to_end(self.logical_layer_end_overlap as u32);
} else {
self.clear_spacer_end();
}
}
fn clear_spacer_start(&mut self) {
// remove fake client from start of left client list or middle client list if
// left is empty this is used to create a spacer element
let mut left_guard = self.clients_left.lock().unwrap();
let mut center_guard = self.clients_center.lock().unwrap();
if left_guard.get(0).is_some_and(|c| c.name == "spacer-start") {
left_guard.remove(0);
} else if center_guard.get(0).is_some_and(|c| c.name == "spacer-start") {
center_guard.remove(0);
}
// remove from space
if let Some(element) = self
.space
.element_under((0., 0.))
.filter(|e| matches!(e.0, CosmicMappedInternal::Spacer(_)))
.map(|e| e.0.clone())
{
self.space.unmap_elem(&element);
}
}
fn clear_spacer_end(&mut self) {
// remove fake client from end of right client list
// this is used to create a spacer element
let mut right_guard = self.clients_right.lock().unwrap();
let mut center_guard = self.clients_center.lock().unwrap();
if right_guard.get(0).is_some_and(|c| c.name == "spacer-end") {
right_guard.remove(0);
} else if center_guard.get(0).is_some_and(|c| c.name == "spacer-end") {
center_guard.remove(0);
}
// remove from space
if let Some(element) = self
.space
.element_under((self.dimensions.w as f64, self.dimensions.h as f64))
.filter(|e| matches!(e.0, CosmicMappedInternal::Spacer(_)))
.map(|e| e.0.clone())
{
self.space.unmap_elem(&element);
}
}
pub fn add_spacer_element_to_start(&mut self, dim: u32) {
// add fake client to start of left client list or middle client list if left is
// empty this is used to create a spacer element
let mut left_guard = self.clients_left.lock().unwrap();
let mut center_guard = self.clients_center.lock().unwrap();
let spacer_client = PanelClient {
name: "spacer-start".to_string(),
path: None,
client: None,
stream: None,
security_ctx: None,
exec: None,
minimize_priority: None,
requests_wayland_display: None,
is_notification_applet: None,
shrink_priority: None,
shrink_min_size: None,
padding_shrinkable: false,
auto_popup_hover_press: None,
};
// add to list if not already there
if left_guard.get(0).is_some_and(|c| c.name != "spacer-start") {
left_guard.insert(0, spacer_client);
} else if center_guard.get(0).is_some_and(|c| c.name != "spacer-start") {
center_guard.insert(0, spacer_client);
}
// add to space if not already there
if let Some(e) = self
.space
.element_under((0.5, 0.5))
.filter(|e| !matches!(e.0, CosmicMappedInternal::Spacer(_)))
.map(|e| e.0.clone())
{
self.space.unmap_elem(&e);
}
let size = if self.config.is_horizontal() {
(dim as i32, 4 as i32)
} else {
(4 as i32, dim as i32)
};
self.space.map_element(
CosmicMappedInternal::Spacer(Spacer {
name: "spacer-start".to_string(),
bbox: Rectangle::new((0, 0).into(), size.into()),
}),
(0, 0),
false,
);
}
pub fn add_spacer_element_to_end(&mut self, dim: u32) {
// add fake client to end of right client list
// this is used to create a spacer element
let mut right_guard = self.clients_right.lock().unwrap();
let mut center_guard = self.clients_center.lock().unwrap();
let spacer_client = PanelClient {
name: "spacer-end".to_string(),
path: None,
client: None,
stream: None,
security_ctx: None,
exec: None,
minimize_priority: None,
requests_wayland_display: None,
is_notification_applet: None,
shrink_priority: None,
shrink_min_size: None,
padding_shrinkable: false,
auto_popup_hover_press: None,
};
// add to list if not already there
if right_guard.last().is_some_and(|c| c.name != "spacer-end") {
right_guard.push(spacer_client);
} else if center_guard.last().is_some_and(|c| c.name != "spacer-end") {
center_guard.push(spacer_client);
}
// location should be layer dimensions - dim
// add to space if not already there
let loc = if self.config.is_horizontal() {
(self.dimensions.w - dim as i32, 0)
} else {
(0, self.dimensions.h - dim as i32)
};
if let Some(e) = self
.space
.element_under((self.dimensions.w as f64, self.dimensions.h as f64))
.filter(|e| !matches!(e.0, CosmicMappedInternal::Spacer(_)))
.map(|e| e.0.clone())
{
self.space.unmap_elem(&e);
}
let size = if self.config.is_horizontal() {
(dim as i32, 4 as i32)
} else {
(4 as i32, dim as i32)
};
self.space.map_element(
CosmicMappedInternal::Spacer(Spacer {
name: "spacer-end".to_string(),
bbox: Rectangle::new(loc.into(), size.into()),
}),
loc,
false,
);
}
pub fn bg_color(&self) -> [f32; 4] {
if let Some(animatable_state) = self.animate_state.as_ref() {
animatable_state.cur.bg_color
} else {
self.colors.bg_color(self.config.opacity)
}
}
pub fn border_radius(&self) -> u32 {
if let Some(animatable_state) = self.animate_state.as_ref() {
animatable_state.cur.border_radius
} else {
self.config.border_radius
}
}
pub fn gap(&self) -> u16 {
if let Some(animatable_state) = self.animate_state.as_ref() {
animatable_state.cur.gap
} else {
self.config.get_effective_anchor_gap() as u16
}
}
pub fn id(&self) -> String {
let id = format!(
"panel-{}-{}-{}",
self.config.name,
self.config.output,
self.output.as_ref().map(|o| o.2.name.clone().unwrap_or_default()).unwrap_or_default()
);
id
}
fn start_show_delay(&mut self) {
if self.start_show_instant.borrow().is_none() {
self.start_show_instant.borrow_mut().replace(Instant::now());
}
}
fn show_delay_done(&self, intellihide: bool) -> bool {
let mut start_show_instant_opt = self.start_show_instant.borrow_mut();
if intellihide {
*start_show_instant_opt = None;
return true;
}
let unhide_delay = if let Some(ref autohide) = self.config.autohide {
autohide.unhide_delay
} else {
*start_show_instant_opt = None;
return true;
};
if let Some(start_show_instant) = *start_show_instant_opt {
let start_show_duration =
match Instant::now().checked_duration_since(start_show_instant) {
Some(d) => d,
None => {
*start_show_instant_opt = None;
return true;
},
};
if start_show_duration >= Duration::from_millis(unhide_delay as u64) {
*start_show_instant_opt = None;
true
} else {
false
}
} else {
false
}
}
fn reset_show_delay(&mut self) {
*self.start_show_instant.borrow_mut() = None;
}
pub fn handle_focus(&mut self) {
let (layer_surface, _) = if let Some(layer_surface) = self.layer.as_ref() {
(layer_surface, layer_surface.wl_surface())
} else {
return;
};
let intellihide = self.overlap_notify.is_some();
// Panel should remain visibile until workspaces overview is no longer shown
if self.shared.workspaces_shown.get() {
return;
}
let cur_hover = {
let c_focused_surface = self.shared.c_focused_surface.borrow();
let c_hovered_surface = self.shared.c_hovered_surface.borrow();
// no transition if not configured for autohide
let no_hover_focus =
c_focused_surface.iter().all(|f| matches!(f.2, FocusStatus::LastFocused(_)))
&& c_hovered_surface.iter().all(|f| matches!(f.2, FocusStatus::LastFocused(_)));
if self.config.autohide().is_none() {
if no_hover_focus && self.animate_state.is_none() {
self.visibility = Visibility::Hidden;
} else {
self.visibility = Visibility::Visible;
}
return;
};
let f = c_hovered_surface.iter().fold(
if self.animate_state.is_some() || (intellihide && !self.has_toplevel_overlap()) {
FocusStatus::Focused
} else {
FocusStatus::LastFocused(self.start_instant)
},
|acc, (surface, _, f)| {
if surface.is_alive()
&& (self.layer.as_ref().is_some_and(|s| *s.wl_surface() == *surface)
|| self.popups.iter().any(|p| {
p.popup.c_popup.wl_surface() == surface
|| self
.popups
.iter()
.any(|p| p.popup.c_popup.wl_surface() == surface)
}))
|| self
.overflow_popup
.as_ref()
.is_some_and(|(p, _)| p.c_popup.wl_surface() == surface)
{
match (&acc, &f) {
(FocusStatus::LastFocused(t_acc), FocusStatus::LastFocused(t_cur)) => {
if t_cur > t_acc {
*f
} else {
acc
}
},
(FocusStatus::LastFocused(_), FocusStatus::Focused) => *f,
_ => acc,
}
} else {
acc
}
},
);
f
};
let intellihide = self.overlap_notify.is_some();
let intellihide_no_toplevel = intellihide && !self.has_toplevel_overlap();
match self.visibility {
Visibility::Hidden => {
if matches!(cur_hover, FocusStatus::Focused) || intellihide_no_toplevel {
if self.show_delay_done(intellihide_no_toplevel) {
self.transitioning = true;
// start transition to visible
let hidden_offset = match self.config.anchor() {
PanelAnchor::Left | PanelAnchor::Right => -(self.dimensions.w),
PanelAnchor::Top | PanelAnchor::Bottom => -(self.dimensions.h),
} + self.config.get_hide_handle().unwrap() as i32;
self.is_dirty = true;
self.visibility = Visibility::TransitionToVisible {
last_instant: Instant::now(),
progress: Duration::new(0, 0),
prev_margin: hidden_offset,
};
// Don't reset margin here - let the animation handle it frame by frame
} else {
self.start_show_delay();
}
} else {
self.reset_show_delay();
}
},
Visibility::Visible => {
if let FocusStatus::LastFocused(t) = cur_hover {
// start transition to hidden
let duration_since_last_focus = match Instant::now().checked_duration_since(t) {
Some(d) => d,
None => return,
};
if duration_since_last_focus > self.config.get_hide_wait().unwrap()
&& (!intellihide || self.has_toplevel_overlap())
{
self.transitioning = true;
self.is_dirty = true;
// Set exclusive zone to handle size at START of hide animation
// to avoid per-frame relayout in the compositor
if self.config.exclusive_zone() {
let handle = self.config.get_hide_handle().unwrap() as i32;
layer_surface.set_exclusive_zone(handle);
}
self.visibility = Visibility::TransitionToHidden {
last_instant: Instant::now(),
progress: Duration::new(0, 0),
prev_margin: 0,
}
}
}
},
Visibility::TransitionToHidden { last_instant, progress, prev_margin } => {
self.transitioning = true;
let now = Instant::now();
let total_t = self.config.get_hide_transition().unwrap();
let delta_t = match now.checked_duration_since(last_instant) {
Some(d) => d,
None => return,
};
let prev_progress = progress;
let progress = match prev_progress.checked_add(delta_t) {
Some(d) => d,
None => return,
};
let progress_norm =
smootherstep(progress.as_millis() as f32 / total_t.as_millis() as f32);
let handle = self.config.get_hide_handle().unwrap() as i32;
self.is_dirty = true;
if matches!(cur_hover, FocusStatus::Focused)
|| (intellihide && !self.has_toplevel_overlap())
{
// start transition to visible
self.visibility = Visibility::TransitionToVisible {
last_instant: now,
progress: total_t.checked_sub(progress).unwrap_or_default(),
prev_margin,
}
} else {
let panel_size = if self.config().is_horizontal() {
self.dimensions.h
} else {
self.dimensions.w
};
let target = -panel_size + handle;
let cur_pix = (progress_norm * target as f32) as i32;
if progress >= total_t {
// Exclusive zone was already set to handle size at animation start
Self::set_margin_with_offset(
self.config.anchor,
self.config.get_margin() as i32,
self.additional_gap,
target,
layer_surface,
true, // commit immediately at end of animation
);
self.visibility = Visibility::Hidden;
} else {
if prev_margin != cur_pix {
// Only update margin during animation, not exclusive zone
// Exclusive zone was set at animation start to avoid per-frame relayout
Self::set_margin_with_offset(
self.config.anchor,
self.config.get_margin() as i32,
self.additional_gap,
cur_pix,
layer_surface,
true, // commit immediately during animation for smooth frames
);
}
self.close_popups(|_| false);
self.visibility = Visibility::TransitionToHidden {
last_instant: now,
progress,
prev_margin: cur_pix,
};
}
}
},
Visibility::TransitionToVisible { last_instant, progress, prev_margin } => {
self.transitioning = true;
let now = Instant::now();
let total_t = self.config.get_hide_transition().unwrap();
let delta_t = match now.checked_duration_since(last_instant) {
Some(d) => d,
None => return,
};
let prev_progress = progress;
let progress = match prev_progress.checked_add(delta_t) {
Some(d) => d,
None => return,
};
let progress_norm =
smootherstep(progress.as_millis() as f32 / total_t.as_millis() as f32);
let handle = self.config.get_hide_handle().unwrap() as i32;
self.is_dirty = true;
if matches!(cur_hover, FocusStatus::LastFocused(_))
&& (!intellihide || !self.has_toplevel_overlap())
{
// start transition to hide
self.close_popups(|_| false);