-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathniri.rs
More file actions
6536 lines (5656 loc) · 244 KB
/
Copy pathniri.rs
File metadata and controls
6536 lines (5656 loc) · 244 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};
use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::os::unix::net::UnixStream;
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::debug::PreviewRender;
use niri_config::output::MaxBpc;
use niri_config::{
Config, FloatOrInt, Key, Modifiers, OutputName, TrackLayout, WarpMouseToFocusMode,
WorkspaceReference, Xkb,
};
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::surface::WaylandSurfaceRenderElement;
use smithay::backend::renderer::element::utils::{
select_dmabuf_feedback, CropRenderElement, Relocate, RelocateRenderElement,
RescaleRenderElement,
};
use smithay::backend::renderer::element::{
default_primary_scanout_output_compare, Element, Id, Kind, PrimaryScanoutOutput, RenderElement,
RenderElementStates,
};
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::backend::renderer::sync::SyncPoint;
use smithay::backend::renderer::Color32F;
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, with_surfaces_surface_tree,
OutputPresentationFeedback,
};
use smithay::desktop::{
find_popup_root_surface, layer_map_for_output, LayerMap, LayerSurface, PopupGrab, PopupManager,
PopupUngrabStrategy, Space, Window, WindowSurfaceType,
};
use smithay::input::keyboard::{Layout as KeyboardLayout, XkbConfig};
use smithay::input::pointer::{
CursorIcon, CursorImageStatus, CursorImageSurfaceData, Focus,
GrabStartData as PointerGrabStartData, MotionEvent,
};
use smithay::input::{Seat, SeatState};
use smithay::output::{self, Output, OutputModeSource, PhysicalProperties, Subpixel, WeakOutput};
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::background_effect::BackgroundEffectState;
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;
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::ext_data_control::DataControlState as ExtDataControlState;
use smithay::wayland::selection::primary_selection::PrimarySelectionState;
use smithay::wayland::selection::wlr_data_control::DataControlState as WlrDataControlState;
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 smithay::wayland::xdg_toplevel_tag::XdgToplevelTagManager;
use wayland_server::protocol::wl_output::WlOutput;
#[cfg(feature = "dbus")]
use crate::a11y::A11y;
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::freedesktop_locale1::Locale1ToNiri;
#[cfg(feature = "dbus")]
use crate::dbus::freedesktop_login1::Login1ToNiri;
#[cfg(feature = "dbus")]
use crate::dbus::gnome_shell_introspect::{self, IntrospectToNiri, NiriToIntrospect};
#[cfg(feature = "dbus")]
use crate::dbus::gnome_shell_screenshot::{NiriToScreenshot, ScreenshotToNiri};
use crate::frame_clock::FrameClock;
use crate::handlers::{configure_lock_surface, XDG_ACTIVATION_TOKEN_TIMEOUT};
use crate::input::pick_color_grab::PickColorGrab;
use crate::input::scroll_swipe_gesture::ScrollSwipeGesture;
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::{Workspace, WorkspaceId};
use crate::layout::{
HitType, Layout, LayoutElement as _, LayoutElementRenderElement, MonitorRenderElement,
};
use crate::niri_render_elements;
use crate::protocols::ext_workspace::{self, ExtWorkspaceManagerState};
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::render_helpers::blur::BlurOptions;
use crate::render_helpers::debug::push_opaque_regions;
use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
use crate::render_helpers::renderer::NiriRenderer;
use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
use crate::render_helpers::surface::push_elements_from_surface_tree;
use crate::render_helpers::texture::TextureBuffer;
use crate::render_helpers::xray::{Xray, XrayPos};
use crate::render_helpers::{
encompassing_geo, render_to_dmabuf, render_to_encompassing_texture, render_to_shm,
render_to_texture, render_to_vec, shaders, RenderCtx, RenderTarget,
};
#[cfg(feature = "xdp-gnome-screencast")]
use crate::screencasting::Screencasting;
use crate::ui::config_error_notification::ConfigErrorNotification;
use crate::ui::exit_confirm_dialog::{ExitConfirmDialog, ExitConfirmDialogRenderElement};
use crate::ui::hotkey_overlay::HotkeyOverlay;
use crate::ui::mru::{MruCloseRequest, WindowMruUi, WindowMruUiRenderElement};
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_DISPLAY, CHILD_ENV};
use crate::utils::vblank_throttle::VBlankThrottle;
use crate::utils::watcher::Watcher;
use crate::utils::xwayland::satellite::Satellite;
use crate::utils::{
center, center_f64, expand_home, get_monotonic_time, ipc_transform_to_smithay, is_mapped,
logical_output, make_screenshot_path, output_matches_name, output_size, panel_orientation,
send_scale_transform, write_png_rgba8, xwayland,
};
use crate::window::mapped::MappedId;
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 config_file_watcher: Option<Watcher>,
pub event_loop: LoopHandle<'static, State>,
pub scheduler: Scheduler<()>,
pub stop_signal: LoopSignal,
pub display_handle: DisplayHandle,
/// Whether niri was run with `--session`
pub is_session_instance: bool,
/// Name of the Wayland socket.
///
/// This is `None` when creating `Niri` without a Wayland socket.
pub socket_name: Option<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 ext_workspace_state: ExtWorkspaceManagerState,
pub screencopy_state: ScreencopyManagerState,
pub output_management_state: OutputManagementManagerState,
pub viewporter_state: ViewporterState,
pub background_effect_state: BackgroundEffectState,
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 wlr_data_control_state: WlrDataControlState,
pub ext_data_control_state: ExtDataControlState,
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,
pub xdg_toplevel_tag_manager: XdgToplevelTagManager,
// 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/niri-wm/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 idle_inhibiting_surfaces: HashSet<WlSurface>,
pub is_fdo_idle_inhibited: Arc<AtomicBool>,
pub keyboard_shortcuts_inhibiting_surfaces: HashMap<WlSurface, KeyboardShortcutsInhibitor>,
/// Most recent XKB settings from org.freedesktop.locale1.
pub xkb_from_locale1: Option<Xkb>,
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,
pub pointer_visibility: PointerVisibility,
pub pointer_inactivity_timer: Option<RegistrationToken>,
/// Whether the pointer inactivity timer got reset this event loop iteration.
///
/// Used for limiting the reset to once per iteration, so that it's not spammed with high
/// resolution mice.
pub pointer_inactivity_timer_got_reset: bool,
/// Whether the (idle notifier) activity was notified this event loop iteration.
///
/// Used for limiting the notify to once per iteration, so that it's not spammed with high
/// resolution mice.
pub notified_activity_this_iteration: bool,
pub pointer_inside_hot_corner: bool,
pub tablet_cursor_location: Option<Point<f64, Logical>>,
pub gesture_swipe_3f_cumulative: Option<(f64, f64)>,
pub overview_scroll_swipe_gesture: ScrollSwipeGesture,
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,
// State that we last sent to the logind LockedHint.
pub locked_hint: Option<bool>,
pub screenshot_ui: ScreenshotUi,
pub config_error_notification: ConfigErrorNotification,
pub hotkey_overlay: HotkeyOverlay,
pub exit_confirm_dialog: ExitConfirmDialog,
pub window_mru_ui: WindowMruUi,
pub pending_mru_commit: Option<PendingMruCommit>,
pub pick_window: Option<async_channel::Sender<Option<MappedId>>>,
pub pick_color: Option<async_channel::Sender<Option<niri_ipc::PickedColor>>>,
pub debug_draw_opaque_regions: bool,
pub debug_draw_damage: bool,
#[cfg(feature = "dbus")]
pub dbus: Option<crate::dbus::DBusServers>,
#[cfg(feature = "dbus")]
pub a11y_keyboard_monitor: Option<crate::dbus::freedesktop_a11y::KeyboardMonitor>,
#[cfg(feature = "dbus")]
pub a11y: A11y,
#[cfg(feature = "dbus")]
pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>,
pub ipc_server: Option<IpcServer>,
pub ipc_outputs_changed: bool,
pub satellite: Option<Satellite>,
#[cfg(feature = "xdp-gnome-screencast")]
pub casting: Screencasting,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PointerVisibility {
/// The pointer is visible.
Visible,
/// The pointer is invisible, but retains its focus.
///
/// This state is set temporarily after auto-hiding the pointer to keep tooltips open and grabs
/// ongoing.
Hidden,
/// The pointer is invisible and cannot focus.
///
/// Corresponds to a fully disabled pointer, for example after a touchscreen input, or after
/// the pointer contents changed in a Hidden state.
Disabled,
}
impl PointerVisibility {
pub fn is_visible(&self) -> bool {
matches!(self, Self::Visible)
}
}
#[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>,
pub vblank_throttle: VBlankThrottle,
/// 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 backdrop that we use instead of clearing to avoid damage
/// tracking issues and make screenshots easier.
pub backdrop_buffer: SolidColorBuffer,
pub xray: Xray,
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,
ExitConfirmDialog,
Overview,
Mru,
}
#[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.
//
// Can be `None` even when `window` is set, for example when the pointer is over the niri
// border around the window.
pub surface: Option<(WlSurface, Point<f64, Logical>)>,
// If surface belongs to a window, this is that window.
pub window: Option<(Window, HitType)>,
// If surface belongs to a layer surface, this is that layer surface.
pub layer: Option<LayerSurface>,
// Pointer is over a hot corner.
pub hot_corner: bool,
}
#[derive(Debug, Default)]
pub enum LockState {
#[default]
Unlocked,
WaitingForSurfaces {
confirmation: SessionLocker,
deadline_token: RegistrationToken,
},
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,
// Force centering even if the cursor is already in the rectangle.
BothAlways,
}
#[derive(Clone, PartialEq, Eq)]
pub enum CastTarget {
// Dynamic cast before selecting anything.
Nothing,
Output {
output: WeakOutput,
/// Cached name of the output.
name: String,
},
Window {
id: u64,
},
}
impl CastTarget {
pub fn output(output: &Output) -> Self {
Self::Output {
output: output.downgrade(),
name: output.name(),
}
}
pub fn matches_output(&self, weak: &WeakOutput) -> bool {
matches!(self, CastTarget::Output { output, .. } if output == weak)
}
pub fn matches(&self, ipc: &niri_ipc::CastTarget) -> bool {
use CastTarget::*;
match (self, ipc) {
(Nothing, niri_ipc::CastTarget::Nothing {}) => true,
(Output { name, .. }, niri_ipc::CastTarget::Output { name: ipc_name }) => {
name == ipc_name
}
(Window { id }, niri_ipc::CastTarget::Window { id: ipc_id }) => id == ipc_id,
_ => false,
}
}
pub fn make_ipc(&self) -> niri_ipc::CastTarget {
use CastTarget::*;
match self {
Nothing => niri_ipc::CastTarget::Nothing {},
Output { name, .. } => niri_ipc::CastTarget::Output { name: name.clone() },
Window { id } => niri_ipc::CastTarget::Window { id: *id },
}
}
}
/// Pending update to a window's focus timestamp.
#[derive(Debug)]
pub struct PendingMruCommit {
id: MappedId,
token: RegistrationToken,
stamp: Duration,
}
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,
KeyboardFocus::ExitConfirmDialog => None,
KeyboardFocus::Overview => None,
KeyboardFocus::Mru => 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,
KeyboardFocus::ExitConfirmDialog => None,
KeyboardFocus::Overview => None,
KeyboardFocus::Mru => None,
}
}
pub fn is_layout(&self) -> bool {
matches!(self, KeyboardFocus::Layout { .. })
}
pub fn is_overview(&self) -> bool {
matches!(self, KeyboardFocus::Overview)
}
}
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,
create_wayland_socket: bool,
is_session_instance: 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,
create_wayland_socket,
is_session_instance,
);
backend.init(&mut niri);
let mut state = Self { backend, niri };
// Load the xkb_file config option if set by the user.
state.load_xkb_file();
// Initialize some IPC server state.
state.ipc_keyboard_layouts_changed();
// Focus the default monitor if set by the user.
state.focus_default_monitor();
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();
}
#[cfg(feature = "dbus")]
self.niri.update_locked_hint();
// Clear the time so it's fetched afresh next iteration.
self.niri.clock.clear();
self.niri.pointer_inactivity_timer_got_reset = false;
self.niri.notified_activity_this_iteration = false;
}
// We monitor both libinput and logind: libinput is always there (including without DBus), but
// it misses some switch events (e.g. after unsuspend) on some systems.
pub fn set_lid_closed(&mut self, is_closed: bool) {
if self.niri.is_lid_closed == is_closed {
return;
}
debug!("laptop lid {}", if is_closed { "closed" } else { "opened" });
self.niri.is_lid_closed = is_closed;
self.backend.on_output_config_changed(&mut self.niri);
}
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();
// Should be called before refresh_layout() because that one will refresh other window
// states and then send a pending configure.
self.niri.refresh_window_states();
// 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);
ext_workspace::refresh(self);
#[cfg(feature = "xdp-gnome-screencast")]
self.niri.refresh_mapped_cast_outputs();
// Should happen before refresh_window_rules(), but after anything that can start or stop
// screencasts.
#[cfg(feature = "xdp-gnome-screencast")]
self.niri.refresh_mapped_cast_window_rules();
self.ipc_refresh_casts();
self.niri.refresh_window_rules();
self.refresh_ipc_outputs();
self.ipc_refresh_layout();
self.ipc_refresh_keyboard_layout_index();
// Needs to be called after updating the keyboard focus.
#[cfg(feature = "dbus")]
self.niri.refresh_a11y();
}
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 mut under = match self.niri.pointer_visibility {
PointerVisibility::Disabled => PointContents::default(),
_ => self.niri.contents_under(location),
};
// Disable the hidden pointer if the contents underneath have changed.
if !self.niri.pointer_visibility.is_visible() && self.niri.pointer_contents != under {
self.niri.pointer_visibility = PointerVisibility::Disabled;
// When setting PointerVisibility::Hidden together with pointer contents changing,
// we can change straight to nothing to avoid one frame of hover. Notably, this can
// be triggered through warp-mouse-to-focus combined with hide-when-typing.
under = PointContents::default();
}
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)
}
}
CenterCoords::BothAlways => 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_window_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
}
pub fn focus_default_monitor(&mut self) {
// Our default target is the first output in sorted order.
let Some(mut target) = self.niri.sorted_outputs.first().cloned() else {
// No outputs are connected.
return;
};
let config = self.niri.config.borrow();
for config in &config.outputs.0 {
if !config.focus_at_startup {
continue;
}
if let Some(output) = self.niri.output_by_name_match(&config.name) {
target = output.clone();
break;
}
}
drop(config);
self.niri.layout.focus_output(&target);
self.move_cursor_to_output(&target);
}
/// 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();
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 confirm_mru(&mut self) {
if let Some(window) = self.niri.close_mru(MruCloseRequest::Confirm) {
self.focus_window(&window);
}
}