-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathmod.rs
4585 lines (3993 loc) · 157 KB
/
mod.rs
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
//! Window layout logic.
//!
//! Niri implements scrollable tiling with dynamic workspaces. The scrollable tiling is mostly
//! orthogonal to any particular workspace system, though outputs living in separate coordinate
//! spaces suggest per-output workspaces.
//!
//! I chose a dynamic workspace system because I think it works very well. In particular, it works
//! naturally across outputs getting added and removed, since workspaces can move between outputs
//! as necessary.
//!
//! In the layout, one output (the first one to be added) is designated as *primary*. This is where
//! workspaces from disconnected outputs will move. Currently, the primary output has no other
//! distinction from other outputs.
//!
//! Where possible, niri tries to follow these principles with regards to outputs:
//!
//! 1. Disconnecting and reconnecting the same output must not change the layout.
//! * This includes both secondary outputs and the primary output.
//! 2. Connecting an output must not change the layout for any workspaces that were never on that
//! output.
//!
//! Therefore, we implement the following logic: every workspace keeps track of which output it
//! originated on—its *original output*. When an output disconnects, its workspaces are appended to
//! the (potentially new) primary output, but remember their original output. Then, if the original
//! output connects again, all workspaces originally from there move back to that output.
//!
//! In order to avoid surprising behavior, if the user creates or moves any new windows onto a
//! workspace, it forgets its original output, and its current output becomes its original output.
//! Imagine a scenario: the user works with a laptop and a monitor at home, then takes their laptop
//! with them, disconnecting the monitor, and keeps working as normal, using the second monitor's
//! workspace just like any other. Then they come back, reconnect the second monitor, and now we
//! don't want an unassuming workspace to end up on it.
use std::cmp::min;
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use std::time::Duration;
use monitor::MonitorAddWindowTarget;
use niri_config::{
CenterFocusedColumn, Config, CornerRadius, FloatOrInt, PresetSize, Struts,
Workspace as WorkspaceConfig, WorkspaceReference,
};
use niri_ipc::{ColumnDisplay, PositionChange, SizeChange};
use scrolling::{Column, ColumnWidth, InsertHint, InsertPosition};
use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
use smithay::backend::renderer::element::Id;
use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
use smithay::output::{self, Output};
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use smithay::utils::{Logical, Point, Rectangle, Scale, Serial, Size, Transform};
use tile::{Tile, TileRenderElement};
use workspace::{WorkspaceAddWindowTarget, WorkspaceId};
pub use self::monitor::MonitorRenderElement;
use self::monitor::{Monitor, WorkspaceSwitch};
use self::workspace::{OutputId, Workspace};
use crate::animation::Clock;
use crate::layout::scrolling::ScrollDirection;
use crate::niri_render_elements;
use crate::render_helpers::renderer::NiriRenderer;
use crate::render_helpers::snapshot::RenderSnapshot;
use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
use crate::render_helpers::texture::TextureBuffer;
use crate::render_helpers::{BakedBuffer, RenderTarget, SplitElements};
use crate::rubber_band::RubberBand;
use crate::utils::transaction::{Transaction, TransactionBlocker};
use crate::utils::{
ensure_min_max_size_maybe_zero, output_matches_name, output_size,
round_logical_in_physical_max1, ResizeEdge,
};
use crate::window::ResolvedWindowRules;
pub mod closing_window;
pub mod floating;
pub mod focus_ring;
pub mod insert_hint_element;
pub mod monitor;
pub mod opening_window;
pub mod scrolling;
pub mod shadow;
pub mod tab_indicator;
pub mod tile;
pub mod workspace;
#[cfg(test)]
mod tests;
/// Size changes up to this many pixels don't animate.
pub const RESIZE_ANIMATION_THRESHOLD: f64 = 10.;
/// Pointer needs to move this far to pull a window from the layout.
const INTERACTIVE_MOVE_START_THRESHOLD: f64 = 256. * 256.;
/// Size-relative units.
pub struct SizeFrac;
niri_render_elements! {
LayoutElementRenderElement<R> => {
Wayland = WaylandSurfaceRenderElement<R>,
SolidColor = SolidColorRenderElement,
}
}
pub type LayoutElementRenderSnapshot =
RenderSnapshot<BakedBuffer<TextureBuffer<GlesTexture>>, BakedBuffer<SolidColorBuffer>>;
pub trait LayoutElement {
/// Type that can be used as a unique ID of this element.
type Id: PartialEq + std::fmt::Debug + Clone;
/// Unique ID of this element.
fn id(&self) -> &Self::Id;
/// Visual size of the element.
///
/// This is what the user would consider the size, i.e. excluding CSD shadows and whatnot.
/// Corresponds to the Wayland window geometry size.
fn size(&self) -> Size<i32, Logical>;
/// Returns the location of the element's buffer relative to the element's visual geometry.
///
/// I.e. if the element has CSD shadows, its buffer location will have negative coordinates.
fn buf_loc(&self) -> Point<i32, Logical>;
/// Checks whether a point is in the element's input region.
///
/// The point is relative to the element's visual geometry.
fn is_in_input_region(&self, point: Point<f64, Logical>) -> bool;
/// Renders the element at the given visual location.
///
/// The element should be rendered in such a way that its visual geometry ends up at the given
/// location.
fn render<R: NiriRenderer>(
&self,
renderer: &mut R,
location: Point<f64, Logical>,
scale: Scale<f64>,
alpha: f32,
target: RenderTarget,
) -> SplitElements<LayoutElementRenderElement<R>>;
/// Renders the non-popup parts of the element.
fn render_normal<R: NiriRenderer>(
&self,
renderer: &mut R,
location: Point<f64, Logical>,
scale: Scale<f64>,
alpha: f32,
target: RenderTarget,
) -> Vec<LayoutElementRenderElement<R>> {
self.render(renderer, location, scale, alpha, target).normal
}
/// Renders the popups of the element.
fn render_popups<R: NiriRenderer>(
&self,
renderer: &mut R,
location: Point<f64, Logical>,
scale: Scale<f64>,
alpha: f32,
target: RenderTarget,
) -> Vec<LayoutElementRenderElement<R>> {
self.render(renderer, location, scale, alpha, target).popups
}
/// Requests the element to change its size.
///
/// The size request is stored and will be continuously sent to the element on any further
/// state changes.
fn request_size(
&mut self,
size: Size<i32, Logical>,
animate: bool,
transaction: Option<Transaction>,
);
/// Requests the element to change size once, clearing the request afterwards.
fn request_size_once(&mut self, size: Size<i32, Logical>, animate: bool) {
self.request_size(size, animate, None);
}
fn request_fullscreen(&mut self, size: Size<i32, Logical>);
fn min_size(&self) -> Size<i32, Logical>;
fn max_size(&self) -> Size<i32, Logical>;
fn is_wl_surface(&self, wl_surface: &WlSurface) -> bool;
fn has_ssd(&self) -> bool;
fn set_preferred_scale_transform(&self, scale: output::Scale, transform: Transform);
fn output_enter(&self, output: &Output);
fn output_leave(&self, output: &Output);
fn set_offscreen_element_id(&self, id: Option<Id>);
fn set_activated(&mut self, active: bool);
fn set_active_in_column(&mut self, active: bool);
fn set_floating(&mut self, floating: bool);
fn set_bounds(&self, bounds: Size<i32, Logical>);
fn is_ignoring_opacity_window_rule(&self) -> bool;
fn configure_intent(&self) -> ConfigureIntent;
fn send_pending_configure(&mut self);
/// Whether the element is currently fullscreen.
///
/// This will *not* switch immediately after a [`LayoutElement::request_fullscreen()`] call.
fn is_fullscreen(&self) -> bool;
/// Whether we're requesting the element to be fullscreen.
///
/// This *will* switch immediately after a [`LayoutElement::request_fullscreen()`] call.
fn is_pending_fullscreen(&self) -> bool;
/// Size previously requested through [`LayoutElement::request_size()`].
fn requested_size(&self) -> Option<Size<i32, Logical>>;
/// Non-fullscreen size that we expect this window has or will shortly have.
///
/// This can be different from [`requested_size()`](LayoutElement::requested_size()). For
/// example, for floating windows this will generally return the current window size, rather
/// than the last size that we requested, since we want floating windows to be able to change
/// size freely. But not always: if we just requested a floating window to resize and it hasn't
/// responded to it yet, this will return the newly requested size.
///
/// This function should never return a 0 size component. `None` means there's no known
/// expected size (for example, the window is fullscreen).
///
/// The default impl is for testing only, it will not preserve the window's own size changes.
fn expected_size(&self) -> Option<Size<i32, Logical>> {
if self.is_fullscreen() {
return None;
}
let mut requested = self.requested_size().unwrap_or_default();
let current = self.size();
if requested.w == 0 {
requested.w = current.w;
}
if requested.h == 0 {
requested.h = current.h;
}
Some(requested)
}
fn is_child_of(&self, parent: &Self) -> bool;
fn rules(&self) -> &ResolvedWindowRules;
/// Runs periodic clean-up tasks.
fn refresh(&self);
fn animation_snapshot(&self) -> Option<&LayoutElementRenderSnapshot>;
fn take_animation_snapshot(&mut self) -> Option<LayoutElementRenderSnapshot>;
fn set_interactive_resize(&mut self, data: Option<InteractiveResizeData>);
fn cancel_interactive_resize(&mut self);
fn interactive_resize_data(&self) -> Option<InteractiveResizeData>;
fn on_commit(&mut self, serial: Serial);
}
#[derive(Debug)]
pub struct Layout<W: LayoutElement> {
/// Monitors and workspaes in the layout.
monitor_set: MonitorSet<W>,
/// Whether the layout should draw as active.
///
/// This normally indicates that the layout has keyboard focus, but not always. E.g. when the
/// screenshot UI is open, it keeps the layout drawing as active.
is_active: bool,
/// Map from monitor name to id of its last active workspace.
///
/// This data is stored upon monitor removal and is used to restore the active workspace when
/// the monitor is reconnected.
///
/// The workspace id does not necessarily point to a valid workspace. If it doesn't, then it is
/// simply ignored.
last_active_workspace_id: HashMap<String, WorkspaceId>,
/// Ongoing interactive move.
interactive_move: Option<InteractiveMoveState<W>>,
/// Ongoing drag-and-drop operation.
dnd: Option<DndData>,
/// Clock for driving animations.
clock: Clock,
/// Time that we last updated render elements for.
update_render_elements_time: Duration,
/// Configurable properties of the layout.
options: Rc<Options>,
}
#[derive(Debug)]
enum MonitorSet<W: LayoutElement> {
/// At least one output is connected.
Normal {
/// Connected monitors.
monitors: Vec<Monitor<W>>,
/// Index of the primary monitor.
primary_idx: usize,
/// Index of the active monitor.
active_monitor_idx: usize,
},
/// No outputs are connected, and these are the workspaces.
NoOutputs {
/// The workspaces.
workspaces: Vec<Workspace<W>>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct Options {
/// Padding around windows in logical pixels.
pub gaps: f64,
/// Extra padding around the working area in logical pixels.
pub struts: Struts,
pub focus_ring: niri_config::FocusRing,
pub border: niri_config::Border,
pub shadow: niri_config::Shadow,
pub tab_indicator: niri_config::TabIndicator,
pub insert_hint: niri_config::InsertHint,
pub center_focused_column: CenterFocusedColumn,
pub always_center_single_column: bool,
pub empty_workspace_above_first: bool,
pub default_column_display: ColumnDisplay,
/// Column or window widths that `toggle_width()` switches between.
pub preset_column_widths: Vec<PresetSize>,
/// Initial width for new columns.
pub default_column_width: Option<PresetSize>,
/// Window height that `toggle_window_height()` switches between.
pub preset_window_heights: Vec<PresetSize>,
pub animations: niri_config::Animations,
pub gestures: niri_config::Gestures,
// Debug flags.
pub disable_resize_throttling: bool,
pub disable_transactions: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
gaps: 16.,
struts: Default::default(),
focus_ring: Default::default(),
border: Default::default(),
shadow: Default::default(),
tab_indicator: Default::default(),
insert_hint: Default::default(),
center_focused_column: Default::default(),
always_center_single_column: false,
empty_workspace_above_first: false,
default_column_display: ColumnDisplay::Normal,
preset_column_widths: vec![
PresetSize::Proportion(1. / 3.),
PresetSize::Proportion(0.5),
PresetSize::Proportion(2. / 3.),
],
default_column_width: None,
animations: Default::default(),
gestures: Default::default(),
disable_resize_throttling: false,
disable_transactions: false,
preset_window_heights: vec![
PresetSize::Proportion(1. / 3.),
PresetSize::Proportion(0.5),
PresetSize::Proportion(2. / 3.),
],
}
}
}
#[derive(Debug)]
enum InteractiveMoveState<W: LayoutElement> {
/// Initial rubberbanding; the window remains in the layout.
Starting {
/// The window we're moving.
window_id: W::Id,
/// Current pointer delta from the starting location.
pointer_delta: Point<f64, Logical>,
/// Pointer location within the visual window geometry as ratio from geometry size.
///
/// This helps the pointer remain inside the window as it resizes.
pointer_ratio_within_window: (f64, f64),
},
/// Moving; the window is no longer in the layout.
Moving(InteractiveMoveData<W>),
}
#[derive(Debug)]
struct InteractiveMoveData<W: LayoutElement> {
/// The window being moved.
pub(self) tile: Tile<W>,
/// Output where the window is currently located/rendered.
pub(self) output: Output,
/// Current pointer position within output.
pub(self) pointer_pos_within_output: Point<f64, Logical>,
/// Window column width.
pub(self) width: ColumnWidth,
/// Whether the window column was full-width.
pub(self) is_full_width: bool,
/// Whether the window targets the floating layout.
pub(self) is_floating: bool,
/// Pointer location within the visual window geometry as ratio from geometry size.
///
/// This helps the pointer remain inside the window as it resizes.
pub(self) pointer_ratio_within_window: (f64, f64),
}
#[derive(Debug)]
pub struct DndData {
/// Output where the pointer is currently located.
output: Output,
/// Current pointer position within output.
pointer_pos_within_output: Point<f64, Logical>,
}
#[derive(Debug, Clone, Copy)]
pub struct InteractiveResizeData {
pub(self) edges: ResizeEdge,
}
#[derive(Debug, Clone, Copy)]
pub enum ConfigureIntent {
/// A configure is not needed (no changes to server pending state).
NotNeeded,
/// A configure is throttled (due to resizing too fast for example).
Throttled,
/// Can send the configure if it isn't throttled externally (only size changed).
CanSend,
/// Should send the configure regardless of external throttling (something other than size
/// changed).
ShouldSend,
}
/// Tile that was just removed from the layout.
pub struct RemovedTile<W: LayoutElement> {
tile: Tile<W>,
/// Width of the column the tile was in.
width: ColumnWidth,
/// Whether the column the tile was in was full-width.
is_full_width: bool,
/// Whether the tile was floating.
is_floating: bool,
}
/// Whether to activate a newly added window.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ActivateWindow {
/// Activate unconditionally.
Yes,
/// Activate based on heuristics.
#[default]
Smart,
/// Do not activate.
No,
}
/// Where to put a newly added window.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum AddWindowTarget<'a, W: LayoutElement> {
/// No particular preference.
#[default]
Auto,
/// On this output.
Output(&'a Output),
/// On this workspace.
Workspace(WorkspaceId),
/// Next to this existing window.
NextTo(&'a W::Id),
}
/// Type of the window hit from `window_under()`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum HitType {
/// The hit is within a window's input region and can be used for sending events to it.
Input {
/// Position of the window's buffer.
win_pos: Point<f64, Logical>,
},
/// The hit can activate a window, but it is not in the input region so cannot send events.
///
/// For example, this could be clicking on a tile border outside the window.
Activate {
/// Whether the hit was on the tab indicator.
is_tab_indicator: bool,
},
}
impl<W: LayoutElement> InteractiveMoveState<W> {
fn moving(&self) -> Option<&InteractiveMoveData<W>> {
match self {
InteractiveMoveState::Moving(move_) => Some(move_),
_ => None,
}
}
fn moving_mut(&mut self) -> Option<&mut InteractiveMoveData<W>> {
match self {
InteractiveMoveState::Moving(move_) => Some(move_),
_ => None,
}
}
}
impl<W: LayoutElement> InteractiveMoveData<W> {
fn tile_render_location(&self) -> Point<f64, Logical> {
let scale = Scale::from(self.output.current_scale().fractional_scale());
let window_size = self.tile.window_size();
let pointer_offset_within_window = Point::from((
window_size.w * self.pointer_ratio_within_window.0,
window_size.h * self.pointer_ratio_within_window.1,
));
let pos =
self.pointer_pos_within_output - pointer_offset_within_window - self.tile.window_loc()
+ self.tile.render_offset();
// Round to physical pixels.
pos.to_physical_precise_round(scale).to_logical(scale)
}
}
impl ActivateWindow {
pub fn map_smart(self, f: impl FnOnce() -> bool) -> bool {
match self {
ActivateWindow::Yes => true,
ActivateWindow::Smart => f(),
ActivateWindow::No => false,
}
}
}
impl HitType {
pub fn offset_win_pos(mut self, offset: Point<f64, Logical>) -> Self {
match &mut self {
HitType::Input { win_pos } => *win_pos += offset,
HitType::Activate { .. } => (),
}
self
}
pub fn hit_tile<W: LayoutElement>(
tile: &Tile<W>,
tile_pos: Point<f64, Logical>,
point: Point<f64, Logical>,
) -> Option<(&W, Self)> {
let pos_within_tile = point - tile_pos;
tile.hit(pos_within_tile)
.map(|hit| (tile.window(), hit.offset_win_pos(tile_pos)))
}
}
impl Options {
fn from_config(config: &Config) -> Self {
let layout = &config.layout;
let preset_column_widths = if layout.preset_column_widths.is_empty() {
Options::default().preset_column_widths
} else {
layout.preset_column_widths.clone()
};
let preset_window_heights = if layout.preset_window_heights.is_empty() {
Options::default().preset_window_heights
} else {
layout.preset_window_heights.clone()
};
// Missing default_column_width maps to Some(PresetSize::Proportion(0.5)),
// while present, but empty, maps to None.
let default_column_width = layout
.default_column_width
.as_ref()
.map(|w| w.0)
.unwrap_or(Some(PresetSize::Proportion(0.5)));
Self {
gaps: layout.gaps.0,
struts: layout.struts,
focus_ring: layout.focus_ring,
border: layout.border,
shadow: layout.shadow,
tab_indicator: layout.tab_indicator,
insert_hint: layout.insert_hint,
center_focused_column: layout.center_focused_column,
always_center_single_column: layout.always_center_single_column,
empty_workspace_above_first: layout.empty_workspace_above_first,
default_column_display: layout.default_column_display,
preset_column_widths,
default_column_width,
animations: config.animations.clone(),
gestures: config.gestures,
disable_resize_throttling: config.debug.disable_resize_throttling,
disable_transactions: config.debug.disable_transactions,
preset_window_heights,
}
}
fn adjusted_for_scale(mut self, scale: f64) -> Self {
let round = |logical: f64| round_logical_in_physical_max1(scale, logical);
self.gaps = round(self.gaps);
self.focus_ring.width = FloatOrInt(round(self.focus_ring.width.0));
self.border.width = FloatOrInt(round(self.border.width.0));
self
}
}
impl<W: LayoutElement> Layout<W> {
pub fn new(clock: Clock, config: &Config) -> Self {
Self::with_options_and_workspaces(clock, config, Options::from_config(config))
}
pub fn with_options(clock: Clock, options: Options) -> Self {
Self {
monitor_set: MonitorSet::NoOutputs { workspaces: vec![] },
is_active: true,
last_active_workspace_id: HashMap::new(),
interactive_move: None,
dnd: None,
clock,
update_render_elements_time: Duration::ZERO,
options: Rc::new(options),
}
}
fn with_options_and_workspaces(clock: Clock, config: &Config, options: Options) -> Self {
let opts = Rc::new(options);
let workspaces = config
.workspaces
.iter()
.map(|ws| {
Workspace::new_with_config_no_outputs(Some(ws.clone()), clock.clone(), opts.clone())
})
.collect();
Self {
monitor_set: MonitorSet::NoOutputs { workspaces },
is_active: true,
last_active_workspace_id: HashMap::new(),
interactive_move: None,
dnd: None,
clock,
update_render_elements_time: Duration::ZERO,
options: opts,
}
}
pub fn add_output(&mut self, output: Output) {
self.monitor_set = match mem::take(&mut self.monitor_set) {
MonitorSet::Normal {
mut monitors,
primary_idx,
active_monitor_idx,
} => {
let primary = &mut monitors[primary_idx];
let ws_id_to_activate = self.last_active_workspace_id.remove(&output.name());
let mut active_workspace_idx = None;
let mut stopped_primary_ws_switch = false;
let mut workspaces = vec![];
for i in (0..primary.workspaces.len()).rev() {
if primary.workspaces[i].original_output.matches(&output) {
let ws = primary.workspaces.remove(i);
// FIXME: this can be coded in a way that the workspace switch won't be
// affected if the removed workspace is invisible. But this is good enough
// for now.
if primary.workspace_switch.is_some() {
primary.workspace_switch = None;
stopped_primary_ws_switch = true;
}
// The user could've closed a window while remaining on this workspace, on
// another monitor. However, we will add an empty workspace in the end
// instead.
if ws.has_windows_or_name() {
if Some(ws.id()) == ws_id_to_activate {
active_workspace_idx = Some(workspaces.len());
}
workspaces.push(ws);
}
if i <= primary.active_workspace_idx
// Generally when moving the currently active workspace, we want to
// fall back to the workspace above, so as not to end up on the last
// empty workspace. However, with empty workspace above first, when
// moving the workspace at index 1 (first non-empty), we want to stay
// at index 1, so as once again not to end up on an empty workspace.
//
// This comes into play at compositor startup when having named
// workspaces set up across multiple monitors. Without this check, the
// first monitor to connect can end up with the first empty workspace
// focused instead of the first named workspace.
&& !(self.options.empty_workspace_above_first
&& primary.active_workspace_idx == 1)
{
primary.active_workspace_idx =
primary.active_workspace_idx.saturating_sub(1);
}
}
}
// If we stopped a workspace switch, then we might need to clean up workspaces.
// Also if empty_workspace_above_first is set and there are only 2 workspaces left,
// both will be empty and one of them needs to be removed. clean_up_workspaces
// takes care of this.
if stopped_primary_ws_switch
|| (primary.options.empty_workspace_above_first
&& primary.workspaces.len() == 2)
{
primary.clean_up_workspaces();
}
workspaces.reverse();
if let Some(idx) = &mut active_workspace_idx {
*idx = workspaces.len() - *idx - 1;
}
let mut active_workspace_idx = active_workspace_idx.unwrap_or(0);
// Make sure there's always an empty workspace.
workspaces.push(Workspace::new(
output.clone(),
self.clock.clone(),
self.options.clone(),
));
if self.options.empty_workspace_above_first && workspaces.len() > 1 {
workspaces.insert(
0,
Workspace::new(output.clone(), self.clock.clone(), self.options.clone()),
);
active_workspace_idx += 1;
}
for ws in &mut workspaces {
ws.set_output(Some(output.clone()));
}
let mut monitor =
Monitor::new(output, workspaces, self.clock.clone(), self.options.clone());
monitor.active_workspace_idx = active_workspace_idx;
monitors.push(monitor);
MonitorSet::Normal {
monitors,
primary_idx,
active_monitor_idx,
}
}
MonitorSet::NoOutputs { mut workspaces } => {
// We know there are no empty workspaces there, so add one.
workspaces.push(Workspace::new(
output.clone(),
self.clock.clone(),
self.options.clone(),
));
let mut active_workspace_idx = 0;
if self.options.empty_workspace_above_first && workspaces.len() > 1 {
workspaces.insert(
0,
Workspace::new(output.clone(), self.clock.clone(), self.options.clone()),
);
active_workspace_idx += 1;
}
let ws_id_to_activate = self.last_active_workspace_id.remove(&output.name());
for (i, workspace) in workspaces.iter_mut().enumerate() {
workspace.set_output(Some(output.clone()));
if Some(workspace.id()) == ws_id_to_activate {
active_workspace_idx = i;
}
}
let mut monitor =
Monitor::new(output, workspaces, self.clock.clone(), self.options.clone());
monitor.active_workspace_idx = active_workspace_idx;
MonitorSet::Normal {
monitors: vec![monitor],
primary_idx: 0,
active_monitor_idx: 0,
}
}
}
}
pub fn remove_output(&mut self, output: &Output) {
self.monitor_set = match mem::take(&mut self.monitor_set) {
MonitorSet::Normal {
mut monitors,
mut primary_idx,
mut active_monitor_idx,
} => {
let idx = monitors
.iter()
.position(|mon| &mon.output == output)
.expect("trying to remove non-existing output");
let monitor = monitors.remove(idx);
self.last_active_workspace_id.insert(
monitor.output_name().clone(),
monitor.workspaces[monitor.active_workspace_idx].id(),
);
let mut workspaces = monitor.workspaces;
for ws in &mut workspaces {
ws.set_output(None);
}
// Get rid of empty workspaces.
workspaces.retain(|ws| ws.has_windows_or_name());
if monitors.is_empty() {
// Removed the last monitor.
MonitorSet::NoOutputs { workspaces }
} else {
if primary_idx >= idx {
// Update primary_idx to either still point at the same monitor, or at some
// other monitor if the primary has been removed.
primary_idx = primary_idx.saturating_sub(1);
}
if active_monitor_idx >= idx {
// Update active_monitor_idx to either still point at the same monitor, or
// at some other monitor if the active monitor has
// been removed.
active_monitor_idx = active_monitor_idx.saturating_sub(1);
}
let primary = &mut monitors[primary_idx];
for ws in &mut workspaces {
ws.set_output(Some(primary.output.clone()));
}
let mut stopped_primary_ws_switch = false;
if !workspaces.is_empty() && primary.workspace_switch.is_some() {
// FIXME: if we're adding workspaces to currently invisible positions
// (outside the workspace switch), we don't need to cancel it.
primary.workspace_switch = None;
stopped_primary_ws_switch = true;
}
let empty_was_focused =
primary.active_workspace_idx == primary.workspaces.len() - 1;
// Push the workspaces from the removed monitor in the end, right before the
// last, empty, workspace.
let empty = primary.workspaces.remove(primary.workspaces.len() - 1);
primary.workspaces.extend(workspaces);
primary.workspaces.push(empty);
// If empty_workspace_above_first is set and the first workspace is now no
// longer empty, add a new empty workspace on top.
if primary.options.empty_workspace_above_first
&& primary.workspaces[0].has_windows_or_name()
{
primary.add_workspace_top();
}
// If the empty workspace was focused on the primary monitor, keep it focused.
if empty_was_focused {
primary.active_workspace_idx = primary.workspaces.len() - 1;
}
if stopped_primary_ws_switch {
primary.clean_up_workspaces();
}
MonitorSet::Normal {
monitors,
primary_idx,
active_monitor_idx,
}
}
}
MonitorSet::NoOutputs { .. } => {
panic!("tried to remove output when there were already none")
}
}
}
pub fn add_column_by_idx(
&mut self,
monitor_idx: usize,
workspace_idx: usize,
column: Column<W>,
activate: bool,
) {
let MonitorSet::Normal {
monitors,
active_monitor_idx,
..
} = &mut self.monitor_set
else {
panic!()
};
monitors[monitor_idx].add_column(workspace_idx, column, activate);
if activate {
*active_monitor_idx = monitor_idx;
}
}
/// Adds a new window to the layout.
///
/// Returns an output that the window was added to, if there were any outputs.
#[allow(clippy::too_many_arguments)]
pub fn add_window(
&mut self,
window: W,
target: AddWindowTarget<W>,
width: Option<PresetSize>,
height: Option<PresetSize>,
is_full_width: bool,
is_floating: bool,
activate: ActivateWindow,
) -> Option<&Output> {
let scrolling_width = self.resolve_scrolling_width(&window, width);
let scrolling_height = height.map(SizeChange::from);
let id = window.id().clone();
match &mut self.monitor_set {
MonitorSet::Normal {
monitors,
active_monitor_idx,
..
} => {
let (mon_idx, target) = match target {
AddWindowTarget::Auto => (*active_monitor_idx, MonitorAddWindowTarget::Auto),
AddWindowTarget::Output(output) => {
let mon_idx = monitors
.iter()
.position(|mon| mon.output == *output)
.unwrap();
(mon_idx, MonitorAddWindowTarget::Auto)
}
AddWindowTarget::Workspace(ws_id) => {
let mon_idx = monitors
.iter()
.position(|mon| mon.workspaces.iter().any(|ws| ws.id() == ws_id))
.unwrap();
(
mon_idx,
MonitorAddWindowTarget::Workspace {
id: ws_id,
column_idx: None,
},
)
}
AddWindowTarget::NextTo(next_to) => {
if let Some(output) = self
.interactive_move
.as_ref()
.and_then(|move_| {
if let InteractiveMoveState::Moving(move_) = move_ {
Some(move_)
} else {
None
}
})
.filter(|move_| next_to == move_.tile.window().id())
.map(|move_| move_.output.clone())
{
// The next_to window is being interactively moved.
let mon_idx = monitors
.iter()
.position(|mon| mon.output == output)
.unwrap_or(*active_monitor_idx);
(mon_idx, MonitorAddWindowTarget::Auto)
} else {
let mon_idx = monitors
.iter()
.position(|mon| {
mon.workspaces.iter().any(|ws| ws.has_window(next_to))
})
.unwrap();
(mon_idx, MonitorAddWindowTarget::NextTo(next_to))
}
}
};
let mon = &mut monitors[mon_idx];
mon.add_window(
window,
target,
activate,
scrolling_width,
is_full_width,
is_floating,
);