-
-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathniri.rs
5178 lines (4467 loc) · 193 KB
/
niri.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
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::{env, mem, thread};
use _server_decoration::server::org_kde_kwin_server_decoration_manager::Mode as KdeDecorationsMode;
use anyhow::{bail, ensure, Context};
use calloop::futures::Scheduler;
use niri_config::{
Config, FloatOrInt, Key, Modifiers, OutputName, PreviewRender, TrackLayout, WorkspaceReference,
DEFAULT_BACKGROUND_COLOR,
};
use smithay::backend::allocator::Fourcc;
use smithay::backend::input::Keycode;
use smithay::backend::renderer::damage::OutputDamageTracker;
use smithay::backend::renderer::element::memory::MemoryRenderBufferRenderElement;
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
use smithay::backend::renderer::element::surface::{
render_elements_from_surface_tree, WaylandSurfaceRenderElement,
};
use smithay::backend::renderer::element::utils::{
select_dmabuf_feedback, Relocate, RelocateRenderElement,
};
use smithay::backend::renderer::element::{
default_primary_scanout_output_compare, Element as _, Id, Kind, PrimaryScanoutOutput,
RenderElementStates,
};
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::backend::renderer::sync::SyncPoint;
use smithay::backend::renderer::{Color32F, Unbind};
use smithay::desktop::utils::{
bbox_from_surface_tree, output_update, send_dmabuf_feedback_surface_tree,
send_frames_surface_tree, surface_presentation_feedback_flags_from_states,
surface_primary_scanout_output, take_presentation_feedback_surface_tree,
under_from_surface_tree, update_surface_primary_scanout_output, OutputPresentationFeedback,
};
use smithay::desktop::{
layer_map_for_output, LayerMap, LayerSurface, PopupGrab, PopupManager, PopupUngrabStrategy,
Space, Window, WindowSurfaceType,
};
use smithay::input::keyboard::Layout as KeyboardLayout;
use smithay::input::pointer::{CursorIcon, CursorImageAttributes, CursorImageStatus, MotionEvent};
use smithay::input::{Seat, SeatState};
use smithay::output::{self, Output, OutputModeSource, PhysicalProperties, Subpixel};
use smithay::reexports::calloop::generic::Generic;
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
use smithay::reexports::calloop::{
Interest, LoopHandle, LoopSignal, Mode, PostAction, RegistrationToken,
};
use smithay::reexports::wayland_protocols::ext::session_lock::v1::server::ext_session_lock_v1::ExtSessionLockV1;
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;
use smithay::reexports::wayland_protocols_misc::server_decoration as _server_decoration;
use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1;
use smithay::reexports::wayland_server::backend::{
ClientData, ClientId, DisconnectReason, GlobalId,
};
use smithay::reexports::wayland_server::protocol::wl_shm;
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use smithay::reexports::wayland_server::{Client, Display, DisplayHandle, Resource};
use smithay::utils::{
ClockSource, IsAlive as _, Logical, Monotonic, Physical, Point, Rectangle, Scale, Size,
Transform, SERIAL_COUNTER,
};
use smithay::wayland::compositor::{
with_states, with_surface_tree_downward, CompositorClientState, CompositorHandler,
CompositorState, HookId, SurfaceData, TraversalAction,
};
use smithay::wayland::cursor_shape::CursorShapeManagerState;
use smithay::wayland::dmabuf::DmabufState;
use smithay::wayland::fractional_scale::FractionalScaleManagerState;
use smithay::wayland::idle_inhibit::IdleInhibitManagerState;
use smithay::wayland::idle_notify::IdleNotifierState;
use smithay::wayland::input_method::{InputMethodManagerState, InputMethodSeat};
use smithay::wayland::keyboard_shortcuts_inhibit::{
KeyboardShortcutsInhibitState, KeyboardShortcutsInhibitor,
};
use smithay::wayland::output::OutputManagerState;
use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraintsState};
use smithay::wayland::pointer_gestures::PointerGesturesState;
use smithay::wayland::presentation::PresentationState;
use smithay::wayland::relative_pointer::RelativePointerManagerState;
use smithay::wayland::security_context::SecurityContextState;
use smithay::wayland::selection::data_device::{set_data_device_selection, DataDeviceState};
use smithay::wayland::selection::primary_selection::PrimarySelectionState;
use smithay::wayland::selection::wlr_data_control::DataControlState;
use smithay::wayland::session_lock::{LockSurface, SessionLockManagerState, SessionLocker};
use smithay::wayland::shell::kde::decoration::KdeDecorationState;
use smithay::wayland::shell::wlr_layer::{self, Layer, WlrLayerShellState};
use smithay::wayland::shell::xdg::decoration::XdgDecorationState;
use smithay::wayland::shell::xdg::XdgShellState;
use smithay::wayland::shm::ShmState;
#[cfg(test)]
use smithay::wayland::single_pixel_buffer::SinglePixelBufferState;
use smithay::wayland::socket::ListeningSocketSource;
use smithay::wayland::tablet_manager::TabletManagerState;
use smithay::wayland::text_input::TextInputManagerState;
use smithay::wayland::viewporter::ViewporterState;
use smithay::wayland::virtual_keyboard::VirtualKeyboardManagerState;
use smithay::wayland::xdg_activation::XdgActivationState;
use smithay::wayland::xdg_foreign::XdgForeignState;
use crate::animation::Clock;
use crate::backend::tty::SurfaceDmabufFeedback;
use crate::backend::{Backend, Headless, RenderResult, Tty, Winit};
use crate::cursor::{CursorManager, CursorTextureCache, RenderCursor, XCursor};
#[cfg(feature = "dbus")]
use crate::dbus::gnome_shell_introspect::{self, IntrospectToNiri, NiriToIntrospect};
#[cfg(feature = "dbus")]
use crate::dbus::gnome_shell_screenshot::{NiriToScreenshot, ScreenshotToNiri};
#[cfg(feature = "xdp-gnome-screencast")]
use crate::dbus::mutter_screen_cast::{self, ScreenCastToNiri};
use crate::frame_clock::FrameClock;
use crate::handlers::{configure_lock_surface, XDG_ACTIVATION_TOKEN_TIMEOUT};
use crate::input::scroll_tracker::ScrollTracker;
use crate::input::{
apply_libinput_settings, mods_with_finger_scroll_binds, mods_with_mouse_binds,
mods_with_wheel_binds, TabletData,
};
use crate::ipc::server::IpcServer;
use crate::layer::mapped::LayerSurfaceRenderElement;
use crate::layer::MappedLayer;
use crate::layout::tile::TileRenderElement;
use crate::layout::workspace::WorkspaceId;
use crate::layout::{Layout, LayoutElement as _, MonitorRenderElement};
use crate::niri_render_elements;
use crate::protocols::foreign_toplevel::{self, ForeignToplevelManagerState};
use crate::protocols::gamma_control::GammaControlManagerState;
use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState;
use crate::protocols::output_management::OutputManagementManagerState;
use crate::protocols::screencopy::{Screencopy, ScreencopyBuffer, ScreencopyManagerState};
use crate::protocols::virtual_pointer::VirtualPointerManagerState;
use crate::pw_utils::{Cast, PipeWire};
#[cfg(feature = "xdp-gnome-screencast")]
use crate::pw_utils::{CastSizeChange, CastTarget, PwToNiri};
use crate::render_helpers::debug::draw_opaque_regions;
use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
use crate::render_helpers::renderer::NiriRenderer;
use crate::render_helpers::texture::TextureBuffer;
use crate::render_helpers::{
render_to_dmabuf, render_to_encompassing_texture, render_to_shm, render_to_texture,
render_to_vec, shaders, RenderTarget, SplitElements,
};
use crate::ui::config_error_notification::ConfigErrorNotification;
use crate::ui::exit_confirm_dialog::ExitConfirmDialog;
use crate::ui::hotkey_overlay::HotkeyOverlay;
use crate::ui::screen_transition::{self, ScreenTransition};
use crate::ui::screenshot_ui::{OutputScreenshot, ScreenshotUi, ScreenshotUiRenderElement};
use crate::utils::scale::{closest_representable_scale, guess_monitor_scale};
use crate::utils::spawning::CHILD_ENV;
use crate::utils::{
center, center_f64, get_monotonic_time, ipc_transform_to_smithay, logical_output,
make_screenshot_path, output_matches_name, output_size, send_scale_transform, write_png_rgba8,
};
use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped, WindowRef};
const CLEAR_COLOR_LOCKED: [f32; 4] = [0.3, 0.1, 0.1, 1.];
// We'll try to send frame callbacks at least once a second. We'll make a timer that fires once a
// second, so with the worst timing the maximum interval between two frame callbacks for a surface
// should be ~1.995 seconds.
const FRAME_CALLBACK_THROTTLE: Option<Duration> = Some(Duration::from_millis(995));
pub struct Niri {
pub config: Rc<RefCell<Config>>,
/// Output config from the config file.
///
/// This does not include transient output config changes done via IPC. It is only used when
/// reloading the config from disk to determine if the output configuration should be reloaded
/// (and transient changes dropped).
pub config_file_output_config: niri_config::Outputs,
pub event_loop: LoopHandle<'static, State>,
pub scheduler: Scheduler<()>,
pub stop_signal: LoopSignal,
pub display_handle: DisplayHandle,
pub socket_name: OsString,
pub start_time: Instant,
/// Whether the at-startup=true window rules are active.
pub is_at_startup: bool,
/// Clock for driving animations.
pub clock: Clock,
// Each workspace corresponds to a Space. Each workspace generally has one Output mapped to it,
// however it may have none (when there are no outputs connected) or multiple (when mirroring).
pub layout: Layout<Mapped>,
// This space does not actually contain any windows, but all outputs are mapped into it
// according to their global position.
pub global_space: Space<Window>,
/// Mapped outputs, sorted by their name and position.
pub sorted_outputs: Vec<Output>,
// Windows which don't have a buffer attached yet.
pub unmapped_windows: HashMap<WlSurface, Unmapped>,
/// Layer surfaces which don't have a buffer attached yet.
pub unmapped_layer_surfaces: HashSet<WlSurface>,
/// Extra data for mapped layer surfaces.
pub mapped_layer_surfaces: HashMap<LayerSurface, MappedLayer>,
// Cached root surface for every surface, so that we can access it in destroyed() where the
// normal get_parent() is cleared out.
pub root_surface: HashMap<WlSurface, WlSurface>,
// Dmabuf readiness pre-commit hook for a surface.
pub dmabuf_pre_commit_hook: HashMap<WlSurface, HookId>,
/// Clients to notify about their blockers being cleared.
pub blocker_cleared_tx: Sender<Client>,
pub blocker_cleared_rx: Receiver<Client>,
pub output_state: HashMap<Output, OutputState>,
// When false, we're idling with monitors powered off.
pub monitors_active: bool,
/// Whether the laptop lid is closed.
///
/// Libinput guarantees that the lid switch starts in open state, and if it was closed during
/// startup, libinput will immediately send a closed event.
pub is_lid_closed: bool,
pub devices: HashSet<input::Device>,
pub tablets: HashMap<input::Device, TabletData>,
pub touch: HashSet<input::Device>,
// Smithay state.
pub compositor_state: CompositorState,
pub xdg_shell_state: XdgShellState,
pub xdg_decoration_state: XdgDecorationState,
pub kde_decoration_state: KdeDecorationState,
pub layer_shell_state: WlrLayerShellState,
pub session_lock_state: SessionLockManagerState,
pub foreign_toplevel_state: ForeignToplevelManagerState,
pub screencopy_state: ScreencopyManagerState,
pub output_management_state: OutputManagementManagerState,
pub viewporter_state: ViewporterState,
pub xdg_foreign_state: XdgForeignState,
pub shm_state: ShmState,
pub output_manager_state: OutputManagerState,
pub dmabuf_state: DmabufState,
pub fractional_scale_manager_state: FractionalScaleManagerState,
pub seat_state: SeatState<State>,
pub tablet_state: TabletManagerState,
pub text_input_state: TextInputManagerState,
pub input_method_state: InputMethodManagerState,
pub keyboard_shortcuts_inhibit_state: KeyboardShortcutsInhibitState,
pub virtual_keyboard_state: VirtualKeyboardManagerState,
pub virtual_pointer_state: VirtualPointerManagerState,
pub pointer_gestures_state: PointerGesturesState,
pub relative_pointer_state: RelativePointerManagerState,
pub pointer_constraints_state: PointerConstraintsState,
pub idle_notifier_state: IdleNotifierState<State>,
pub idle_inhibit_manager_state: IdleInhibitManagerState,
pub data_device_state: DataDeviceState,
pub primary_selection_state: PrimarySelectionState,
pub data_control_state: DataControlState,
pub popups: PopupManager,
pub popup_grab: Option<PopupGrabState>,
pub presentation_state: PresentationState,
pub security_context_state: SecurityContextState,
pub gamma_control_manager_state: GammaControlManagerState,
pub activation_state: XdgActivationState,
pub mutter_x11_interop_state: MutterX11InteropManagerState,
// This will not work as is outside of tests, so it is gated with #[cfg(test)] for now. In
// particular, shaders will need to learn about the single pixel buffer. Also, it must be
// verified that a black single-pixel-buffer background lets the foreground surface to be
// unredirected.
//
// https://github.com/YaLTeR/niri/issues/619
#[cfg(test)]
pub single_pixel_buffer_state: SinglePixelBufferState,
pub seat: Seat<State>,
/// Scancodes of the keys to suppress.
pub suppressed_keys: HashSet<Keycode>,
/// Button codes of the mouse buttons to suppress.
pub suppressed_buttons: HashSet<u32>,
pub bind_cooldown_timers: HashMap<Key, RegistrationToken>,
pub bind_repeat_timer: Option<RegistrationToken>,
pub keyboard_focus: KeyboardFocus,
pub layer_shell_on_demand_focus: Option<LayerSurface>,
pub previously_focused_window: Option<Window>,
pub idle_inhibiting_surfaces: HashSet<WlSurface>,
pub is_fdo_idle_inhibited: Arc<AtomicBool>,
pub keyboard_shortcuts_inhibiting_surfaces: HashMap<WlSurface, KeyboardShortcutsInhibitor>,
pub cursor_manager: CursorManager,
pub cursor_texture_cache: CursorTextureCache,
pub cursor_shape_manager_state: CursorShapeManagerState,
pub dnd_icon: Option<DndIcon>,
/// Contents under pointer.
///
/// Periodically updated: on motion and other events and in the loop callback. If you require
/// the real up-to-date contents somewhere, it's better to recompute on the spot.
///
/// This is not pointer focus. I.e. during a click grab, the pointer focus remains on the
/// client with the grab, but this field will keep updating to the latest contents as if no
/// grab was active.
///
/// This is primarily useful for emitting pointer motion events for surfaces that move
/// underneath the cursor on their own (i.e. when the tiling layout moves). In this case, not
/// taking grabs into account is expected, because we pass the information to pointer.motion()
/// which passes it down through grabs, which decide what to do with it as they see fit.
pub pointer_contents: PointContents,
/// Whether the pointer is hidden, for example due to a previous touch input.
///
/// When this happens, the pointer also loses any focus. This is so that touch can prevent
/// various tooltips from sticking around.
pub pointer_hidden: bool,
pub pointer_inactivity_timer: Option<RegistrationToken>,
pub tablet_cursor_location: Option<Point<f64, Logical>>,
pub gesture_swipe_3f_cumulative: Option<(f64, f64)>,
pub vertical_wheel_tracker: ScrollTracker,
pub horizontal_wheel_tracker: ScrollTracker,
pub mods_with_mouse_binds: HashSet<Modifiers>,
pub mods_with_wheel_binds: HashSet<Modifiers>,
pub vertical_finger_scroll_tracker: ScrollTracker,
pub horizontal_finger_scroll_tracker: ScrollTracker,
pub mods_with_finger_scroll_binds: HashSet<Modifiers>,
pub lock_state: LockState,
pub screenshot_ui: ScreenshotUi,
pub config_error_notification: ConfigErrorNotification,
pub hotkey_overlay: HotkeyOverlay,
pub exit_confirm_dialog: Option<ExitConfirmDialog>,
pub debug_draw_opaque_regions: bool,
pub debug_draw_damage: bool,
#[cfg(feature = "dbus")]
pub dbus: Option<crate::dbus::DBusServers>,
#[cfg(feature = "dbus")]
pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>,
pub ipc_server: Option<IpcServer>,
pub ipc_outputs_changed: bool,
// Casts are dropped before PipeWire to prevent a double-free (yay).
pub casts: Vec<Cast>,
pub pipewire: Option<PipeWire>,
#[cfg(feature = "xdp-gnome-screencast")]
pub pw_to_niri: calloop::channel::Sender<PwToNiri>,
// Screencast output for each mapped window.
#[cfg(feature = "xdp-gnome-screencast")]
pub mapped_cast_output: HashMap<Window, Output>,
}
#[derive(Debug)]
pub struct DndIcon {
pub surface: WlSurface,
pub offset: Point<i32, Logical>,
}
pub struct OutputState {
pub global: GlobalId,
pub frame_clock: FrameClock,
pub redraw_state: RedrawState,
pub on_demand_vrr_enabled: bool,
// After the last redraw, some ongoing animations still remain.
pub unfinished_animations_remain: bool,
/// Last sequence received in a vblank event.
pub last_drm_sequence: Option<u32>,
/// Sequence for frame callback throttling.
///
/// We want to send frame callbacks for each surface at most once per monitor refresh cycle.
///
/// Even if a surface commit resulted in empty damage to the monitor, we want to delay the next
/// frame callback until roughly when a VBlank would occur, had the monitor been damaged. This
/// is necessary to prevent clients busy-looping with frame callbacks that result in empty
/// damage.
///
/// This counter wrapping-increments by 1 every time we move into the next refresh cycle, as
/// far as frame callback throttling is concerned. Specifically, it happens:
///
/// 1. Upon a successful DRM frame submission. Notably, we don't wait for the VBlank here,
/// because the client buffers are already "latched" at the point of submission. Even if a
/// client submits a new buffer right away, we will wait for a VBlank to draw it, which
/// means that busy looping is avoided.
/// 2. If a frame resulted in empty damage, a timer is queued to fire roughly when a VBlank
/// would occur, based on the last presentation time and output refresh interval. Sequence
/// is incremented in that timer, before attempting a redraw or sending frame callbacks.
pub frame_callback_sequence: u32,
/// Solid color buffer for the background that we use instead of clearing to avoid damage
/// tracking issues and make screenshots easier.
pub background_buffer: SolidColorBuffer,
pub lock_render_state: LockRenderState,
pub lock_surface: Option<LockSurface>,
pub lock_color_buffer: SolidColorBuffer,
screen_transition: Option<ScreenTransition>,
/// Damage tracker used for the debug damage visualization.
pub debug_damage_tracker: OutputDamageTracker,
}
#[derive(Debug, Default)]
pub enum RedrawState {
/// The compositor is idle.
#[default]
Idle,
/// A redraw is queued.
Queued,
/// We submitted a frame to the KMS and waiting for it to be presented.
WaitingForVBlank { redraw_needed: bool },
/// We did not submit anything to KMS and made a timer to fire at the estimated VBlank.
WaitingForEstimatedVBlank(RegistrationToken),
/// A redraw is queued on top of the above.
WaitingForEstimatedVBlankAndQueued(RegistrationToken),
}
pub struct PopupGrabState {
pub root: WlSurface,
pub grab: PopupGrab<State>,
pub has_keyboard_grab: bool,
}
// The surfaces here are always toplevel surfaces focused as far as niri's logic is concerned, even
// when popup grabs are active (which means the real keyboard focus is on a popup descending from
// that toplevel surface).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyboardFocus {
// Layout is focused by default if there's nothing else to focus.
Layout { surface: Option<WlSurface> },
LayerShell { surface: WlSurface },
LockScreen { surface: Option<WlSurface> },
ScreenshotUi,
}
#[derive(Default, Clone, PartialEq)]
pub struct PointContents {
// Output under point.
pub output: Option<Output>,
// Surface under point and its location in the global coordinate space.
pub surface: Option<(WlSurface, Point<f64, Logical>)>,
// If surface belongs to a window, this is that window.
pub window: Option<Window>,
// If surface belongs to a layer surface, this is that layer surface.
pub layer: Option<LayerSurface>,
}
#[derive(Default)]
pub enum LockState {
#[default]
Unlocked,
Locking(SessionLocker),
Locked(ExtSessionLockV1),
}
#[derive(PartialEq, Eq)]
pub enum LockRenderState {
/// The output displays a normal session frame.
Unlocked,
/// The output displays a locked frame.
Locked,
}
// Not related to the one in Smithay.
//
// This state keeps track of when a surface last received a frame callback.
struct SurfaceFrameThrottlingState {
/// Output and sequence that the frame callback was last sent at.
last_sent_at: RefCell<Option<(Output, u32)>>,
}
pub enum CenterCoords {
Separately,
Both,
}
#[derive(Default)]
pub struct WindowOffscreenId(pub RefCell<Option<Id>>);
impl RedrawState {
fn queue_redraw(self) -> Self {
match self {
RedrawState::Idle => RedrawState::Queued,
RedrawState::WaitingForEstimatedVBlank(token) => {
RedrawState::WaitingForEstimatedVBlankAndQueued(token)
}
// A redraw is already queued.
value @ (RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)) => {
value
}
// We're waiting for VBlank, request a redraw afterwards.
RedrawState::WaitingForVBlank { .. } => RedrawState::WaitingForVBlank {
redraw_needed: true,
},
}
}
}
impl Default for SurfaceFrameThrottlingState {
fn default() -> Self {
Self {
last_sent_at: RefCell::new(None),
}
}
}
impl KeyboardFocus {
pub fn surface(&self) -> Option<&WlSurface> {
match self {
KeyboardFocus::Layout { surface } => surface.as_ref(),
KeyboardFocus::LayerShell { surface } => Some(surface),
KeyboardFocus::LockScreen { surface } => surface.as_ref(),
KeyboardFocus::ScreenshotUi => None,
}
}
pub fn into_surface(self) -> Option<WlSurface> {
match self {
KeyboardFocus::Layout { surface } => surface,
KeyboardFocus::LayerShell { surface } => Some(surface),
KeyboardFocus::LockScreen { surface } => surface,
KeyboardFocus::ScreenshotUi => None,
}
}
pub fn is_layout(&self) -> bool {
matches!(self, KeyboardFocus::Layout { .. })
}
}
pub struct State {
pub backend: Backend,
pub niri: Niri,
}
impl State {
pub fn new(
config: Config,
event_loop: LoopHandle<'static, State>,
stop_signal: LoopSignal,
display: Display<State>,
headless: bool,
) -> Result<Self, Box<dyn std::error::Error>> {
let _span = tracy_client::span!("State::new");
let config = Rc::new(RefCell::new(config));
let has_display = env::var_os("WAYLAND_DISPLAY").is_some()
|| env::var_os("WAYLAND_SOCKET").is_some()
|| env::var_os("DISPLAY").is_some();
let mut backend = if headless {
let headless = Headless::new();
Backend::Headless(headless)
} else if has_display {
let winit = Winit::new(config.clone(), event_loop.clone())?;
Backend::Winit(winit)
} else {
let tty = Tty::new(config.clone(), event_loop.clone())
.context("error initializing the TTY backend")?;
Backend::Tty(tty)
};
let mut niri = Niri::new(config.clone(), event_loop, stop_signal, display, &backend);
backend.init(&mut niri);
let mut state = Self { backend, niri };
// Initialize some IPC server state.
state.ipc_keyboard_layouts_changed();
Ok(state)
}
pub fn refresh_and_flush_clients(&mut self) {
let _span = tracy_client::span!("State::refresh_and_flush_clients");
self.refresh();
// Advance animations to the current time (not target render time) before rendering outputs
// in order to clear completed animations and render elements. Even if we're not rendering,
// it's good to advance every now and then so the workspace clean-up and animations don't
// build up (the 1 second frame callback timer will call this line).
self.niri.advance_animations();
self.niri.redraw_queued_outputs(&mut self.backend);
{
let _span = tracy_client::span!("flush_clients");
self.niri.display_handle.flush_clients().unwrap();
}
// Clear the time so it's fetched afresh next iteration.
self.niri.clock.clear();
}
fn refresh(&mut self) {
let _span = tracy_client::span!("State::refresh");
// Handle commits for surfaces whose blockers cleared this cycle. This should happen before
// layout.refresh() since this is where these surfaces handle commits.
self.notify_blocker_cleared();
// These should be called periodically, before flushing the clients.
self.niri.popups.cleanup();
self.refresh_popup_grab();
self.update_keyboard_focus();
// Needs to be called after updating the keyboard focus.
self.niri.refresh_layout();
self.niri.cursor_manager.check_cursor_image_surface_alive();
self.niri.refresh_pointer_outputs();
self.niri.global_space.refresh();
self.niri.refresh_idle_inhibit();
self.refresh_pointer_contents();
foreign_toplevel::refresh(self);
self.niri.refresh_window_rules();
self.refresh_ipc_outputs();
self.ipc_refresh_layout();
self.ipc_refresh_keyboard_layout_index();
#[cfg(feature = "xdp-gnome-screencast")]
self.niri.refresh_mapped_cast_outputs();
}
fn notify_blocker_cleared(&mut self) {
let dh = self.niri.display_handle.clone();
while let Ok(client) = self.niri.blocker_cleared_rx.try_recv() {
trace!("calling blocker_cleared");
self.client_compositor_state(&client)
.blocker_cleared(self, &dh);
}
}
pub fn move_cursor(&mut self, location: Point<f64, Logical>) {
let under = self.niri.contents_under(location);
self.niri.pointer_contents.clone_from(&under);
let pointer = &self.niri.seat.get_pointer().unwrap();
pointer.motion(
self,
under.surface,
&MotionEvent {
location,
serial: SERIAL_COUNTER.next_serial(),
time: get_monotonic_time().as_millis() as u32,
},
);
pointer.frame(self);
self.niri.maybe_activate_pointer_constraint();
// We do not show the pointer on programmatic or keyboard movement.
// FIXME: granular
self.niri.queue_redraw_all();
}
/// Moves cursor within the specified rectangle, only adjusting coordinates if needed.
fn move_cursor_to_rect(&mut self, rect: Rectangle<f64, Logical>, mode: CenterCoords) -> bool {
let pointer = &self.niri.seat.get_pointer().unwrap();
let cur_loc = pointer.current_location();
let x_in_bound = cur_loc.x >= rect.loc.x && cur_loc.x <= rect.loc.x + rect.size.w;
let y_in_bound = cur_loc.y >= rect.loc.y && cur_loc.y <= rect.loc.y + rect.size.h;
let p = match mode {
CenterCoords::Separately => {
if x_in_bound && y_in_bound {
return false;
} else if y_in_bound {
// adjust x
Point::from((rect.loc.x + rect.size.w / 2.0, cur_loc.y))
} else if x_in_bound {
// adjust y
Point::from((cur_loc.x, rect.loc.y + rect.size.h / 2.0))
} else {
// adjust x and y
center_f64(rect)
}
}
CenterCoords::Both => {
if x_in_bound && y_in_bound {
return false;
} else {
// adjust x and y
center_f64(rect)
}
}
};
self.move_cursor(p);
true
}
pub fn move_cursor_to_focused_tile(&mut self, mode: CenterCoords) -> bool {
if !self.niri.keyboard_focus.is_layout() {
return false;
}
if self.niri.tablet_cursor_location.is_some() {
return false;
}
let Some(output) = self.niri.layout.active_output() else {
return false;
};
let monitor = self.niri.layout.monitor_for_output(output).unwrap();
let mut rv = false;
let rect = monitor.active_tile_visual_rectangle();
if let Some(rect) = rect {
let output_geo = self.niri.global_space.output_geometry(output).unwrap();
let mut rect = rect;
rect.loc += output_geo.loc.to_f64();
rv = self.move_cursor_to_rect(rect, mode);
}
rv
}
/// Focus a specific window, taking care of a potential active output change and cursor
/// warp.
pub fn focus_window(&mut self, window: &Window) {
let active_output = self.niri.layout.active_output().cloned();
self.niri.layout.activate_window(window);
let new_active = self.niri.layout.active_output().cloned();
#[allow(clippy::collapsible_if)]
if new_active != active_output {
if !self.maybe_warp_cursor_to_focus_centered() {
self.move_cursor_to_output(&new_active.unwrap());
}
} else {
self.maybe_warp_cursor_to_focus();
}
// FIXME: granular
self.niri.queue_redraw_all();
}
pub fn maybe_warp_cursor_to_focus(&mut self) -> bool {
if !self.niri.config.borrow().input.warp_mouse_to_focus {
return false;
}
self.move_cursor_to_focused_tile(CenterCoords::Separately)
}
pub fn maybe_warp_cursor_to_focus_centered(&mut self) -> bool {
if !self.niri.config.borrow().input.warp_mouse_to_focus {
return false;
}
self.move_cursor_to_focused_tile(CenterCoords::Both)
}
pub fn refresh_pointer_contents(&mut self) {
let _span = tracy_client::span!("Niri::refresh_pointer_contents");
let pointer = &self.niri.seat.get_pointer().unwrap();
let location = pointer.current_location();
if !self.niri.is_locked() && !self.niri.screenshot_ui.is_open() {
// Don't refresh cursor focus during transitions.
if let Some((output, _)) = self.niri.output_under(location) {
let monitor = self.niri.layout.monitor_for_output(output).unwrap();
if monitor.are_transitions_ongoing() {
return;
}
}
}
if !self.update_pointer_contents() {
return;
}
pointer.frame(self);
// Pointer motion from a surface to nothing triggers a cursor change to default, which
// means we may need to redraw.
// FIXME: granular
self.niri.queue_redraw_all();
}
pub fn update_pointer_contents(&mut self) -> bool {
let _span = tracy_client::span!("Niri::update_pointer_contents");
let pointer = &self.niri.seat.get_pointer().unwrap();
let location = pointer.current_location();
let under = if self.niri.pointer_hidden {
PointContents::default()
} else {
self.niri.contents_under(location)
};
// We're not changing the global cursor location here, so if the contents did not change,
// then nothing changed.
if self.niri.pointer_contents == under {
return false;
}
self.niri.pointer_contents.clone_from(&under);
pointer.motion(
self,
under.surface,
&MotionEvent {
location,
serial: SERIAL_COUNTER.next_serial(),
time: get_monotonic_time().as_millis() as u32,
},
);
self.niri.maybe_activate_pointer_constraint();
true
}
pub fn move_cursor_to_output(&mut self, output: &Output) {
let geo = self.niri.global_space.output_geometry(output).unwrap();
self.move_cursor(center(geo).to_f64());
}
pub fn refresh_popup_grab(&mut self) {
let keyboard_grabbed = self.niri.seat.input_method().keyboard_grabbed();
if let Some(grab) = &mut self.niri.popup_grab {
if grab.grab.has_ended() {
self.niri.popup_grab = None;
} else if keyboard_grabbed {
// HACK: remove popup grab if IME grabbed the keyboard, because we can't yet do
// popup grabs together with an IME grab.
// FIXME: do this properly.
grab.grab.ungrab(PopupUngrabStrategy::All);
self.niri.seat.get_pointer().unwrap().unset_grab(
self,
SERIAL_COUNTER.next_serial(),
get_monotonic_time().as_millis() as u32,
);
self.niri.popup_grab = None;
}
}
}
pub fn update_keyboard_focus(&mut self) {
// Clean up on-demand layer surface focus if necessary.
if let Some(surface) = &self.niri.layer_shell_on_demand_focus {
// Still alive and has on-demand interactivity.
let good = surface.alive()
&& surface.cached_state().keyboard_interactivity
== wlr_layer::KeyboardInteractivity::OnDemand;
if !good {
self.niri.layer_shell_on_demand_focus = None;
}
}
// Compute the current focus.
let focus = if self.niri.is_locked() {
KeyboardFocus::LockScreen {
surface: self.niri.lock_surface_focus(),
}
} else if self.niri.screenshot_ui.is_open() {
KeyboardFocus::ScreenshotUi
} else if let Some(output) = self.niri.layout.active_output() {
let mon = self.niri.layout.monitor_for_output(output).unwrap();
let layers = layer_map_for_output(output);
// Explicitly check for layer-shell popup grabs here, our keyboard focus will stay on
// the root layer surface while it has grabs.
let layer_grab = self.niri.popup_grab.as_ref().and_then(|g| {
layers
.layer_for_surface(&g.root, WindowSurfaceType::TOPLEVEL)
.and_then(|l| l.can_receive_keyboard_focus().then(|| (&g.root, l.layer())))
});
let grab_on_layer = |layer: Layer| {
layer_grab
.and_then(move |(s, l)| if l == layer { Some(s.clone()) } else { None })
.map(|surface| KeyboardFocus::LayerShell { surface })
};
let layout_focus = || {
self.niri
.layout
.focus()
.map(|win| win.toplevel().wl_surface().clone())
.map(|surface| KeyboardFocus::Layout {
surface: Some(surface),
})
};
let excl_focus_on_layer = |layer| {
layers.layers_on(layer).find_map(|surface| {
let can_receive_exclusive_focus = surface.cached_state().keyboard_interactivity
== wlr_layer::KeyboardInteractivity::Exclusive;
can_receive_exclusive_focus
.then(|| surface.wl_surface().clone())
.map(|surface| KeyboardFocus::LayerShell { surface })
})
};
let on_d_focus_on_layer = |layer| {
layers.layers_on(layer).find_map(|surface| {
let is_on_demand_surface =
Some(surface) == self.niri.layer_shell_on_demand_focus.as_ref();
is_on_demand_surface
.then(|| surface.wl_surface().clone())
.map(|surface| KeyboardFocus::LayerShell { surface })
})
};
// Prefer exclusive focus on a layer, then check on-demand focus.
let focus_on_layer =
|layer| excl_focus_on_layer(layer).or_else(|| on_d_focus_on_layer(layer));
let mut surface = grab_on_layer(Layer::Overlay);
// FIXME: we shouldn't prioritize the top layer grabs over regular overlay input or a
// fullscreen layout window. This will need tracking in grab() to avoid handing it out
// in the first place. Or a better way to structure this code.
surface = surface.or_else(|| grab_on_layer(Layer::Top));
surface = surface.or_else(|| grab_on_layer(Layer::Bottom));
surface = surface.or_else(|| grab_on_layer(Layer::Background));
surface = surface.or_else(|| focus_on_layer(Layer::Overlay));
if mon.render_above_top_layer() {
surface = surface.or_else(layout_focus);
surface = surface.or_else(|| focus_on_layer(Layer::Top));
surface = surface.or_else(|| focus_on_layer(Layer::Bottom));
surface = surface.or_else(|| focus_on_layer(Layer::Background));
} else {
surface = surface.or_else(|| focus_on_layer(Layer::Top));
surface = surface.or_else(|| on_d_focus_on_layer(Layer::Bottom));
surface = surface.or_else(|| on_d_focus_on_layer(Layer::Background));
surface = surface.or_else(layout_focus);
// Bottom and background layers can only receive exclusive focus when there are no
// layout windows.
surface = surface.or_else(|| excl_focus_on_layer(Layer::Bottom));
surface = surface.or_else(|| excl_focus_on_layer(Layer::Background));
}
surface.unwrap_or(KeyboardFocus::Layout { surface: None })
} else {
KeyboardFocus::Layout { surface: None }
};
let keyboard = self.niri.seat.get_keyboard().unwrap();
if self.niri.keyboard_focus != focus {
trace!(
"keyboard focus changed from {:?} to {:?}",
self.niri.keyboard_focus,
focus
);
// Tell the windows their new focus state for window rule purposes.
let mut previous_focus = None;
if let KeyboardFocus::Layout {
surface: Some(surface),
} = &self.niri.keyboard_focus
{
if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
mapped.set_is_focused(false);
previous_focus = Some(mapped.window.clone());
}
}
if let KeyboardFocus::Layout {
surface: Some(surface),
} = &focus
{
if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
mapped.set_is_focused(true);
}
}
// Update the previous focus but only when staying focused on the layout.
//
// Case 1: opening and closing exclusive-keyboard layer-shell (e.g. app launcher). This
// involves going from Layout to LayerShell, then from LayerShell to Layout. The
// previously focused window should stay unchanged.
//
// Case 1.5: opening layer-shell, in the background switching layout focus, closing
// layer-shell. With the current logic, this won't update the previously focused
// window, which is incorrect. But this case should be rare.
//
// Case 2: switching to an empty workspace, then hitting FocusWindowPrevious. The focus
// should go to the window that was just focused. The keyboard focus goes from Layout
// (with Some surface) to Layout (with None surface), so we update the previously