Repository navigation
Expand file tree
/
Copy pathserver.cpp
More file actions
2219 lines (2066 loc) · 87.9 KB
/
Copy pathserver.cpp
File metadata and controls
2219 lines (2066 loc) · 87.9 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
#include "server/server.h"
#include "config/config.h"
#include "config/config_diag.h"
#include "config/config_watcher.h"
#include "config/resolve.h"
#include "core/application_scope.h"
#include "core/fdlimit.h"
#include "core/log.h"
#include "core/process.h"
#include "core/tracy.h"
#include "input/cursor.h"
#include "input/eis.h"
#include "input/gestures.h"
#include "input/input_capture.h"
#include "input/keyboard.h"
#include "input/keyboard_leds.h"
#include "input/seat.h"
#include "input/text_input.h"
#include "layer/layer_surface.h"
#include "lock/session_lock.h"
#include "output/output.h"
#include "overview/overview.h"
#include "scene/cheatsheet.h"
#include "scene/color.h"
#include "scene/config_banner.h"
#include "scene/effect_registry.h"
#include "scene/hint_rect.h"
#include "scene/quit_confirm.h"
#include "server/allocator.h"
#include "server/backend_manager.h"
#include "server/color_manager.h"
#include "server/drm_lease.h"
#include "server/ipc.h"
#include "server/syncobj_acquire_barrier.h"
#include "server/syncobj_superseded_release.h"
#include "server/syncobj_unmap_release.h"
#include "view/view.h"
#include "wlr.h"
#include "workspace/scratchpad.h"
#include "workspace/workspace.h"
#include "xwayland/xwayland.h"
extern "C" {
#include <umbrielfx/render/effect.h>
}
#include <algorithm>
#include <array>
#include <cerrno>
#include <cmath>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <format>
#include <optional>
#include <ranges>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unistd.h>
#include <vector>
namespace umbriel {
namespace {
constexpr Logger kLog("server");
constexpr size_t kWaylandClientBufferSize = 1024 * 1024;
// Security-context clients only receive reviewed, ordinary application
// protocols. New globals stay unavailable until they are classified here.
// [[security_context_rule]] widens the set for matching clients.
constexpr std::array<std::string_view, 32> kAllowedSecurityContextGlobals{
"wl_shm",
"wl_drm",
"zwp_linux_dmabuf_v1",
"wp_linux_drm_syncobj_manager_v1",
"wl_compositor",
"wl_subcompositor",
"wl_data_device_manager",
"zwp_primary_selection_device_manager_v1",
"wp_viewporter",
"wp_fractional_scale_manager_v1",
"wp_presentation",
"wp_tearing_control_manager_v1",
"wp_content_type_manager_v1",
"wl_output",
"wp_color_manager_v1",
"xdg_wm_base",
"xdg_toplevel_tag_manager_v1",
"xdg_toplevel_drag_manager_v1",
"zxdg_exporter_v2",
"xdg_wm_dialog_v1",
"zxdg_decoration_manager_v1",
"org_kde_kwin_server_decoration_manager",
"zwp_relative_pointer_manager_v1",
"zwp_pointer_constraints_v1",
"zwp_pointer_gestures_v1",
"zwp_tablet_manager_v2",
"zwp_idle_inhibit_manager_v1",
"zwp_keyboard_shortcuts_inhibit_manager_v1",
"xdg_activation_v1",
"wl_seat",
"wp_cursor_shape_manager_v1",
"zwp_text_input_manager_v3",
};
bool isAllowedSecurityContextGlobal(std::string_view interface) {
return std::ranges::find(kAllowedSecurityContextGlobals, interface) != kAllowedSecurityContextGlobals.end();
}
struct ClientGlobalPolicy {
wl_listener destroy{};
bool advertiseDecorationManagers = true;
bool advertisePrimarySelection = true;
// Resolved on first use: security-context metadata is attached after the client-created signal.
std::optional<std::vector<std::string>> securityContextGlobals;
};
void onClientGlobalPolicyDestroy(wl_listener* listener, void* /*data*/) {
ClientGlobalPolicy* policy;
policy = wl_container_of(listener, policy, destroy);
wl_list_remove(&policy->destroy.link);
delete policy;
}
ClientGlobalPolicy* attachClientGlobalPolicy(wl_client* client) {
auto* policy = new ClientGlobalPolicy{};
policy->advertiseDecorationManagers = config().appearance.preferNoCsd;
policy->advertisePrimarySelection = config().input.middleClickPaste;
policy->destroy.notify = onClientGlobalPolicyDestroy;
wl_client_add_destroy_listener(client, &policy->destroy);
return policy;
}
ClientGlobalPolicy* clientGlobalPolicy(const wl_client* client) {
wl_listener* listener =
wl_client_get_destroy_listener(const_cast<wl_client*>(client), onClientGlobalPolicyDestroy);
if (listener == nullptr) {
return attachClientGlobalPolicy(const_cast<wl_client*>(client));
}
ClientGlobalPolicy* policy;
policy = wl_container_of(listener, policy, destroy);
return policy;
}
void onClientCreated(wl_listener* /*listener*/, void* data) {
attachClientGlobalPolicy(static_cast<wl_client*>(data));
}
bool filterGlobal(const wl_client* client, const wl_global* global, void* data) {
auto* server = static_cast<Server*>(data);
const wl_interface* interface = wl_global_get_interface(global);
if (interface == nullptr) {
return true;
}
const std::string_view interfaceName(interface->name);
// A global filter is consulted both when a global is advertised and when
// it is bound, so each client's decisions must remain stable for its
// entire connection.
ClientGlobalPolicy* policy = clientGlobalPolicy(client);
if (const wlr_security_context_v1_state* context = server->clientSecurityContext(client);
context != nullptr && !isAllowedSecurityContextGlobal(interfaceName)) {
// Nested contexts stay blocked unconditionally: per-app grants are only
// trustworthy while labels originate from unrestricted clients.
if (interfaceName == "wp_security_context_manager_v1") {
return false;
}
if (!policy->securityContextGlobals) {
policy->securityContextGlobals =
securityContextRuleGlobals(config(), context->sandbox_engine, context->app_id);
}
if (std::ranges::find(*policy->securityContextGlobals, interfaceName)
== policy->securityContextGlobals->end()) {
return false;
}
}
if (interfaceName == "zwp_primary_selection_device_manager_v1") {
return policy->advertisePrimarySelection;
}
if (interfaceName == "zxdg_decoration_manager_v1" || interfaceName == "org_kde_kwin_server_decoration_manager") {
return policy->advertiseDecorationManagers;
}
if (interfaceName == "zxdg_output_manager_v1" && server->xwayland() != nullptr) {
return server->xwayland()->advertiseOutputManager(client, global);
}
return true;
}
std::string shellQuote(std::string_view value) {
std::string quoted("'");
for (const char character : value) {
if (character == '\'') {
quoted += "'\\''";
} else {
quoted += character;
}
}
quoted += '\'';
return quoted;
}
void applyConfiguredEnvironment() {
for (const auto& [name, value] : config().environment.variables) {
if (setenv(name.c_str(), value.c_str(), 1) != 0) {
kLog.warn("failed to export environment variable {}", name);
}
}
}
std::string sessionEnvironmentCommand(bool managedReadiness) {
std::string configuredAssignments;
for (const auto& [name, value] : config().environment.variables) {
configuredAssignments += ' ';
configuredAssignments += shellQuote(std::format("{}={}", name, value));
}
const std::string publishConfigured =
configuredAssignments.empty() ? "" : " && systemctl --user set-environment" + configuredAssignments;
std::string command =
"variables='WAYLAND_DISPLAY DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP XDG_SESSION_TYPE "
"XCURSOR_THEME XCURSOR_SIZE UMBRIEL_SOCKET'; systemd_ready=false; "
"if command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; then "
"if systemctl --user import-environment $variables";
command += publishConfigured;
command += "; then systemd_ready=true; else "
"echo 'umbriel: failed to publish the session environment' >&2; exit 1; fi; fi; "
// The compositor waits on this script with its event loop stopped. Without a bus address, libdbus
// autolaunches over X11, and DISPLAY names an Xwayland that only that loop can start. Use the
// user bus socket when the address is unset, and skip the update when there is no bus at all.
"if [ -z \"${DBUS_SESSION_BUS_ADDRESS:-}\" ] && [ -S \"${XDG_RUNTIME_DIR:-}/bus\" ]; then "
"export DBUS_SESSION_BUS_ADDRESS=\"unix:path=$XDG_RUNTIME_DIR/bus\"; fi; "
"if [ -n \"${DBUS_SESSION_BUS_ADDRESS:-}\" ] "
"&& command -v dbus-update-activation-environment >/dev/null 2>&1; then "
"dbus-update-activation-environment $variables || { "
"echo 'umbriel: failed to update the D-Bus activation environment' >&2; exit 1; }; fi; ";
if (managedReadiness) {
command += "$systemd_ready";
} else {
command += "if $systemd_ready; then systemctl --user start --no-block umbriel-session.target; fi";
}
return command;
}
} // namespace
void Server::setScreenCastActive(bool active) {
if (m_screenCastActive == active) {
return;
}
m_screenCastActive = active;
m_screenCastDynamicConfirmed = false;
m_pendingScreenCastCommand.reset();
if (m_quitConfirm != nullptr
&& m_quitConfirm->visible()
&& m_quitConfirm->kind() == QuitConfirm::Kind::ScreenCastDynamic) {
m_quitConfirm->hide();
}
}
void Server::clearScreenCastTarget() {
if (m_quitConfirm != nullptr
&& m_quitConfirm->visible()
&& m_quitConfirm->kind() == QuitConfirm::Kind::ScreenCastDynamic) {
dismissConfirmation();
}
m_screenCastCommand.kind = ScreenCastCommandKind::Clear;
m_screenCastCommand.value.clear();
++m_screenCastCommand.serial;
if (m_ipc != nullptr) {
m_ipc->notifyScreenCastChanged();
}
}
bool Server::requestScreenCastCommand(ScreenCastCommandKind kind, std::string value, std::string* error) {
if (!m_screenCastActive) {
if (error != nullptr) {
*error = "no active screencast";
}
return false;
}
ScreenCastCommand requested{.kind = kind, .value = std::move(value)};
if (config().screenCast.disableDynamicConfirmation || m_screenCastDynamicConfirmed) {
if (m_quitConfirm != nullptr
&& m_quitConfirm->visible()
&& m_quitConfirm->kind() == QuitConfirm::Kind::ScreenCastDynamic) {
dismissConfirmation();
}
m_screenCastCommand.kind = requested.kind;
m_screenCastCommand.value = std::move(requested.value);
++m_screenCastCommand.serial;
if (m_ipc != nullptr) {
m_ipc->notifyScreenCastChanged();
}
return true;
}
if (m_quitConfirm == nullptr || sessionLocked()) {
if (error != nullptr) {
*error = "screencast target change confirmation is unavailable";
}
return false;
}
if (m_quitConfirm->visible()) {
if (m_quitConfirm->kind() != QuitConfirm::Kind::ScreenCastDynamic) {
if (error != nullptr) {
*error = "another confirmation is active";
}
return false;
}
m_pendingScreenCastCommand = std::move(requested);
confirmScreenCastDynamic();
return true;
}
m_pendingScreenCastCommand = std::move(requested);
m_quitConfirm->show(QuitConfirm::Kind::ScreenCastDynamic);
return true;
}
bool Server::setScreenCastOutput(const Output& output, std::string* error) {
return requestScreenCastCommand(ScreenCastCommandKind::SetOutput, output.wlr()->name, error);
}
bool Server::setScreenCastWindow(const View& view, std::string* error) {
const char* identifier = view.extForeignIdentifier();
if (identifier == nullptr) {
if (error != nullptr) {
*error = "window has no capture identifier";
}
return false;
}
return requestScreenCastCommand(ScreenCastCommandKind::SetWindow, identifier, error);
}
bool Server::followScreenCastWindow(std::string* error) {
return requestScreenCastCommand(ScreenCastCommandKind::FollowWindow, {}, error);
}
bool Server::followScreenCastOutput(std::string* error) {
return requestScreenCastCommand(ScreenCastCommandKind::FollowOutput, {}, error);
}
void Server::confirmScreenCastDynamic() {
if (!m_screenCastActive || !m_pendingScreenCastCommand) {
dismissConfirmation();
return;
}
ScreenCastCommand requested = std::move(*m_pendingScreenCastCommand);
m_pendingScreenCastCommand.reset();
m_screenCastDynamicConfirmed = true;
if (m_quitConfirm != nullptr) {
m_quitConfirm->hide();
}
m_screenCastCommand.kind = requested.kind;
m_screenCastCommand.value = std::move(requested.value);
++m_screenCastCommand.serial;
if (m_ipc != nullptr) {
m_ipc->notifyScreenCastChanged();
}
}
void Server::dismissConfirmation() {
if (m_pendingCaptureId != 0 && m_inputCapture != nullptr) {
const auto id = std::exchange(m_pendingCaptureId, 0);
m_inputCapture->authorizeSession(id, false);
}
if (m_pendingInputId != 0) {
const auto id = std::exchange(m_pendingInputId, 0);
m_deniedInputNames.insert(m_pendingInputName);
kLog.info("input permission denied id={} app='{}'", id, m_pendingInputName);
m_pendingInputName.clear();
if (m_eisInput != nullptr) {
m_eisInput->authorizeClient(id, false);
}
}
if (m_quitConfirm != nullptr
&& m_quitConfirm->visible()
&& m_quitConfirm->kind() == QuitConfirm::Kind::ScreenCastDynamic) {
m_pendingScreenCastCommand.reset();
}
if (m_quitConfirm != nullptr) {
m_quitConfirm->hide();
}
}
void Server::requestInputEmulation(uint64_t id, std::string_view name) {
const std::string application(name);
if (m_allowedInputNames.contains(application) && !sessionLocked()) {
m_eisInput->authorizeClient(id, true);
return;
}
if (application.empty()
|| application.size() > 256
|| sessionLocked()
|| m_deniedInputNames.contains(application)
|| m_quitConfirm == nullptr
|| m_quitConfirm->visible()) {
m_eisInput->authorizeClient(id, false);
return;
}
m_pendingInputId = id;
m_pendingInputName = application;
std::string displayName;
for (const unsigned char character : application) {
displayName += character >= 32 && character < 127 ? static_cast<char>(character) : '?';
}
kLog.info("input permission requested id={} app='{}'", id, displayName);
m_quitConfirm->showInputEmulation(displayName);
}
void Server::confirmInputEmulation() {
if (m_pendingInputId == 0 || m_eisInput == nullptr || sessionLocked()) {
dismissConfirmation();
return;
}
const auto id = std::exchange(m_pendingInputId, 0);
m_allowedInputNames.insert(m_pendingInputName);
kLog.info("input permission granted id={} app='{}'", id, m_pendingInputName);
m_pendingInputName.clear();
m_quitConfirm->hide();
m_eisInput->authorizeClient(id, true);
}
void Server::cancelInputEmulation(uint64_t id) {
if (id != m_pendingInputId) {
return;
}
m_pendingInputId = 0;
m_pendingInputName.clear();
if (m_quitConfirm != nullptr && m_quitConfirm->kind() == QuitConfirm::Kind::InputEmulation) {
m_quitConfirm->hide();
}
}
void Server::requestInputCapture(uint64_t id, std::string_view name, uint32_t persistMode) {
if (m_stopping
|| m_sessionLock != nullptr
|| sessionLocked()
|| (m_session != nullptr && !m_session->active)
|| name.size() > 256
|| m_quitConfirm == nullptr
|| m_quitConfirm->visible()
|| (m_inputCapture != nullptr && m_inputCapture->active())) {
m_inputCapture->authorizeSession(id, false);
return;
}
m_pendingCaptureId = id;
std::string label;
for (const unsigned char character : name) {
label += character >= 32 && character < 127 ? static_cast<char>(character) : '?';
}
m_quitConfirm->showInputCapture(label.empty() ? "Unknown application" : label, persistMode);
if (!m_quitConfirm->visible()) {
dismissConfirmation();
}
}
void Server::confirmInputCapture(bool remember) {
if (m_pendingCaptureId == 0
|| m_inputCapture == nullptr
|| m_sessionLock != nullptr
|| sessionLocked()
|| (m_session != nullptr && !m_session->active)
|| (remember && (m_quitConfirm == nullptr || !m_quitConfirm->canRememberInputCapture()))) {
dismissConfirmation();
return;
}
const auto id = std::exchange(m_pendingCaptureId, 0);
m_quitConfirm->hide();
m_inputCapture->authorizeSession(id, true, remember);
}
void Server::cancelInputCapture(uint64_t id) {
if (m_pendingCaptureId != id) {
return;
}
m_pendingCaptureId = 0;
if (m_quitConfirm != nullptr && m_quitConfirm->kind() == QuitConfirm::Kind::InputCapture) {
m_quitConfirm->hide();
}
}
void Server::inputCaptureStateChanged(bool active) {
if (m_stopping) {
return;
}
const uint32_t capabilities = active ? m_inputCapture->capabilities() : m_inputCaptureCapabilities;
m_inputCaptureCapabilities = active ? capabilities : 0;
cancelModifierTap();
if ((capabilities & 1U) != 0) {
for (const auto& keyboard : m_keyboards) {
keyboard->prepareInputCapture(!active);
}
if (active) {
notifyKeyboardClearFocus();
m_seat->notifyPointerModifiers(true);
} else if (!sessionLocked()) {
refocus();
if (m_eisInput != nullptr) {
if (wlr_keyboard* keyboard = wlr_seat_get_keyboard(m_seat->wlr()); keyboard != nullptr) {
m_eisInput->updateModifiers(keyboard->modifiers);
}
}
}
}
if ((capabilities & 2U) != 0 && m_cursor != nullptr) {
m_cursor->setInputCaptured(active);
}
}
bool Server::physicalInputDevice(const wlr_input_device* device) const {
return device != nullptr
&& (m_eisInput == nullptr || !m_eisInput->ownsDevice(device))
&& std::ranges::none_of(m_virtualPointers, [device](const auto& pointer) {
return &pointer->vpointer->pointer.base == device;
});
}
bool Server::keyboardKeyConsumed(wlr_keyboard* keyboard, uint32_t keycode) const {
const auto entry =
std::ranges::find_if(m_keyboards, [keyboard](const auto& candidate) { return candidate->wlr() == keyboard; });
return entry != m_keyboards.end() && (*entry)->consumedKeycodes().contains(keycode);
}
void Server::onSessionActive(wl_listener* listener, void* /*data*/) {
Server* self;
self = wl_container_of(listener, self, m_sessionActive);
self->updateDrmLeaseState();
if (!self->m_session->active) {
if (self->m_inputCapture != nullptr) {
self->m_inputCapture->suspend();
}
if (self->m_pendingCaptureId != 0) {
self->dismissConfirmation();
}
}
}
void Server::updateDrmLeaseState() {
if (m_drmLeaseManager != nullptr) {
m_drmLeaseManager->setActive(
!m_stopping && !m_sessionLocked && m_sessionLock == nullptr && (m_session == nullptr || m_session->active)
);
}
}
void Server::stopFollowingScreenCast() {
if (m_quitConfirm != nullptr
&& m_quitConfirm->visible()
&& m_quitConfirm->kind() == QuitConfirm::Kind::ScreenCastDynamic) {
dismissConfirmation();
}
m_screenCastCommand.kind = ScreenCastCommandKind::FollowStop;
m_screenCastCommand.value.clear();
++m_screenCastCommand.serial;
if (m_ipc != nullptr) {
m_ipc->notifyScreenCastChanged();
}
}
const wlr_security_context_v1_state* Server::clientSecurityContext(const wl_client* client) const {
if (m_securityContextManager == nullptr) {
return nullptr;
}
return wlr_security_context_manager_v1_lookup_client(m_securityContextManager, client);
}
ContentType Server::surfaceContentType(wlr_surface* surface) const {
if (m_contentTypeManager == nullptr || surface == nullptr) {
return ContentType::None;
}
switch (wlr_surface_get_content_type_v1(m_contentTypeManager, surface)) {
case WP_CONTENT_TYPE_V1_TYPE_PHOTO:
return ContentType::Photo;
case WP_CONTENT_TYPE_V1_TYPE_VIDEO:
return ContentType::Video;
case WP_CONTENT_TYPE_V1_TYPE_GAME:
return ContentType::Game;
case WP_CONTENT_TYPE_V1_TYPE_NONE:
default:
return ContentType::None;
}
}
pid_t surfaceClientPid(const wlr_surface* surface) {
if (surface == nullptr || surface->resource == nullptr) {
return -1;
}
pid_t pid = -1;
wl_client_get_credentials(wl_resource_get_client(surface->resource), &pid, nullptr, nullptr);
return pid > 0 ? pid : -1;
}
Server::Server() : m_effects(*this) {
m_nested = std::getenv("WAYLAND_DISPLAY") != nullptr
|| std::getenv("WAYLAND_SOCKET") != nullptr
|| std::getenv("DISPLAY") != nullptr;
m_display = wl_display_create();
if (m_display == nullptr) {
throw std::runtime_error("failed to create wl_display");
}
m_protocolLogger = wl_display_add_protocol_logger(m_display, onProtocolMessage, this);
if (m_protocolLogger == nullptr) {
throw std::runtime_error("failed to register Wayland protocol logger");
}
wl_display_set_default_max_buffer_size(m_display, kWaylandClientBufferSize);
m_clientCreated.notify = onClientCreated;
wl_display_add_client_created_listener(m_display, &m_clientCreated);
m_backendManager = BackendManager::create(m_display, config().drm);
if (m_backendManager == nullptr) {
throw std::runtime_error("failed to create wlr_backend");
}
m_backend = m_backendManager->backend();
m_session = m_backendManager->session();
m_renderer = m_backendManager->createRenderer();
if (m_renderer == nullptr) {
throw std::runtime_error("failed to create fx_renderer");
}
m_rendererLost.notify = onRendererLost;
wl_signal_add(&m_renderer->events.lost, &m_rendererLost);
if (!wlr_renderer_init_wl_shm(m_renderer, m_display)) {
throw std::runtime_error("failed to initialize wl_shm");
}
const int drmFd = wlr_renderer_get_drm_fd(m_renderer);
wlr_linux_dmabuf_v1* linuxDmabuf = nullptr;
if (wlr_renderer_get_texture_formats(m_renderer, WLR_BUFFER_CAP_DMABUF) != nullptr && drmFd >= 0) {
if (wlr_drm_create(m_display, m_renderer) == nullptr) {
kLog.warn("failed to create legacy wl_drm global");
}
linuxDmabuf = wlr_linux_dmabuf_v1_create_with_renderer(m_display, 4, m_renderer);
if (linuxDmabuf == nullptr) {
throw std::runtime_error("failed to create linux-dmabuf global");
}
}
const bool explicitSync = drmFd >= 0 && m_renderer->features.timeline && m_backend->features.timeline;
if (explicitSync) {
if (wlr_linux_drm_syncobj_manager_v1_create(m_display, 1, drmFd) == nullptr) {
throw std::runtime_error("failed to create linux-drm-syncobj manager");
}
kLog.info("explicit synchronization enabled");
}
m_allocator = createAllocator(m_backend, m_renderer);
if (m_allocator == nullptr) {
throw std::runtime_error("failed to create wlr_allocator");
}
if (!m_backendManager->verifyOpenDevices("after allocator creation")) {
throw std::runtime_error("renderer or allocator opened an excluded GPU");
}
m_cursorEffectSlot.configuredSelector = config().effects.cursor;
resolveEffectSlot(m_cursorEffectSlot, EffectKind::Cursor);
effectRegistry().prepare(m_renderer);
m_compositor = wlr_compositor_create(m_display, 5, m_renderer);
if (explicitSync) {
m_syncobjAcquireBarrier = std::make_unique<SyncobjAcquireBarrier>(m_compositor);
m_syncobjUnmapRelease = std::make_unique<SyncobjUnmapRelease>(m_compositor);
m_syncobjSupersededRelease = std::make_unique<SyncobjSupersededRelease>(m_compositor);
}
wlr_subcompositor_create(m_display);
wlr_data_device_manager_create(m_display);
if (wlr_primary_selection_v1_device_manager_create(m_display) == nullptr) {
throw std::runtime_error("failed to create primary-selection manager");
}
m_securityContextManager = wlr_security_context_manager_v1_create(m_display);
if (m_securityContextManager == nullptr) {
throw std::runtime_error("failed to create security-context manager");
}
wl_display_set_global_filter(m_display, filterGlobal, this);
m_drmLeaseManager = std::make_unique<DrmLeaseManager>(m_display, m_backend);
updateDrmLeaseState();
wlr_viewporter_create(m_display);
wlr_fractional_scale_manager_v1_create(m_display, 1);
wlr_presentation_create(m_display, m_backend, 2);
m_tearingControlManager = wlr_tearing_control_manager_v1_create(m_display, 1);
if (m_tearingControlManager == nullptr) {
throw std::runtime_error("failed to create tearing-control manager");
}
m_contentTypeManager = wlr_content_type_manager_v1_create(m_display, 1);
if (m_contentTypeManager == nullptr) {
throw std::runtime_error("failed to create content-type manager");
}
if (wlr_ext_data_control_manager_v1_create(m_display, 1) == nullptr) {
throw std::runtime_error("failed to create ext-data-control manager");
}
if (wlr_data_control_manager_v1_create(m_display) == nullptr) {
throw std::runtime_error("failed to create legacy data-control manager");
}
m_outputLayout = wlr_output_layout_create(m_display);
wlr_xdg_output_manager_v1_create(m_display, m_outputLayout);
// A scene helper served by libwlroots allocates nodes too small for
// umbrielfx's trailing fields, which renders every surface black instead of
// failing. Refuse to build a scene on top of that.
if (const char* mismatch = umbrielfx_scene_check_helpers(); mismatch != nullptr) {
throw std::runtime_error(std::string("umbrielfx scene helpers are not linked correctly: ") + mismatch);
}
m_scene = wlr_scene_create();
if (linuxDmabuf != nullptr) {
wlr_scene_set_linux_dmabuf_v1(m_scene, linuxDmabuf);
}
if (m_renderer->features.input_color_transform) {
m_colorManager = std::make_unique<ColorManager>(*this);
if (!m_colorManager->valid()) {
throw std::runtime_error("failed to create color-management manager");
}
}
const Config::Appearance::Blur& blur = config().appearance.blur;
wlr_scene_set_blur_data(
m_scene, blur.passes, blur.radius, static_cast<float>(blur.noise), static_cast<float>(blur.brightness),
static_cast<float>(blur.contrast), static_cast<float>(blur.saturation)
);
m_sceneLayout = wlr_scene_attach_output_layout(m_scene, m_outputLayout);
wlr_scene_set_background_color(m_scene, config().colors.backdrop.data());
// Global stacking keeps scratchpads above normal windows and below drag, panels, fullscreen, overlays, and lock.
// Per-output layer trees keep normal windows below panels.
m_backdrop = wlr_scene_rect_create(&m_scene->tree, 0, 0, config().colors.backdrop.data());
wlr_scene_rect_set_corner_radius(m_backdrop, 0);
m_shellLayerTrees[ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND] = wlr_scene_tree_create(&m_scene->tree);
m_overviewBlurTree = wlr_scene_tree_create(&m_scene->tree);
wlr_scene_node_set_enabled(&m_overviewBlurTree->node, false);
m_shellLayerTrees[ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM] = wlr_scene_tree_create(&m_scene->tree);
m_xdgTree = wlr_scene_tree_create(&m_scene->tree);
m_scratchpadTree = wlr_scene_tree_create(&m_scene->tree);
m_scratchpadManager = std::make_unique<ScratchpadManager>(*this, m_scratchpadTree);
m_overviewTree = wlr_scene_tree_create(&m_scene->tree);
wlr_scene_node_set_enabled(&m_overviewTree->node, false);
m_dragTree = wlr_scene_tree_create(&m_scene->tree);
m_dragIconTree = wlr_scene_tree_create(&m_scene->tree);
m_shellLayerTrees[ZWLR_LAYER_SHELL_V1_LAYER_TOP] = wlr_scene_tree_create(&m_scene->tree);
m_fullscreenTree = wlr_scene_tree_create(&m_scene->tree);
m_pinnedTree = wlr_scene_tree_create(&m_scene->tree);
m_xwaylandUnmanagedTree = wlr_scene_tree_create(&m_scene->tree);
m_shellLayerTrees[ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY] = wlr_scene_tree_create(&m_scene->tree);
m_imPopupTree = wlr_scene_tree_create(&m_scene->tree);
m_cheatsheetTree = wlr_scene_tree_create(&m_scene->tree);
m_bannerTree = wlr_scene_tree_create(&m_scene->tree);
m_quitConfirmTree = wlr_scene_tree_create(&m_scene->tree);
m_lockTree = wlr_scene_tree_create(&m_scene->tree);
m_lockBlank = wlr_scene_rect_create(m_lockTree, 0, 0, config().colors.backdrop.data());
wlr_scene_rect_set_corner_radius(m_lockBlank, 0);
wlr_scene_node_set_enabled(&m_lockBlank->node, false);
wlr_scene_node_set_enabled(&m_lockTree->node, false);
wlr_scene_node_lower_to_bottom(&m_backdrop->node);
m_effects.syncLightLayer();
m_gammaManager = wlr_gamma_control_manager_v1_create(m_display);
m_setGamma.notify = onSetGamma;
wl_signal_add(&m_gammaManager->events.set_gamma, &m_setGamma);
// Version 6 adds the suspended state hidden tabs are given. The window-manager capabilities version 5 sends default
// to every capability, which is what a client assumed before, so no client sees a change in what it may ask for.
m_xdgShell = wlr_xdg_shell_create(m_display, 6);
m_newXdgToplevel.notify = onNewXdgToplevel;
wl_signal_add(&m_xdgShell->events.new_toplevel, &m_newXdgToplevel);
m_newXdgPopup.notify = onNewXdgPopup;
wl_signal_add(&m_xdgShell->events.new_popup, &m_newXdgPopup);
wlr_xdg_foreign_registry* foreignRegistry = wlr_xdg_foreign_registry_create(m_display);
if (foreignRegistry == nullptr) {
throw std::runtime_error("failed to create xdg-foreign registry");
}
if (wlr_xdg_foreign_v2_create(m_display, foreignRegistry) == nullptr) {
throw std::runtime_error("failed to create xdg-foreign global");
}
wlr_xdg_wm_dialog_v1* dialogManager = wlr_xdg_wm_dialog_v1_create(m_display, 1);
if (dialogManager == nullptr) {
throw std::runtime_error("failed to create xdg-dialog global");
}
m_newXdgDialog.notify = onNewXdgDialog;
wl_signal_add(&dialogManager->events.new_dialog, &m_newXdgDialog);
m_xdgToplevelTagManager = wlr_xdg_toplevel_tag_manager_v1_create(m_display, 1);
if (m_xdgToplevelTagManager == nullptr) {
throw std::runtime_error("failed to create XDG toplevel tag manager");
}
m_setXdgToplevelTag.notify = onSetXdgToplevelTag;
wl_signal_add(&m_xdgToplevelTagManager->events.set_tag, &m_setXdgToplevelTag);
m_xdgDecorationManager = wlr_xdg_decoration_manager_v1_create(m_display);
m_newXdgDecoration.notify = onNewXdgDecoration;
wl_signal_add(&m_xdgDecorationManager->events.new_toplevel_decoration, &m_newXdgDecoration);
m_serverDecorationManager = wlr_server_decoration_manager_create(m_display);
m_newLegacyDecoration.notify = onNewLegacyDecoration;
wl_signal_add(&m_serverDecorationManager->events.new_decoration, &m_newLegacyDecoration);
wlr_server_decoration_manager_set_default_mode(
m_serverDecorationManager, WLR_SERVER_DECORATION_MANAGER_MODE_SERVER
);
m_layerShell = wlr_layer_shell_v1_create(m_display, 4);
m_newLayerSurface.notify = onNewLayerSurface;
wl_signal_add(&m_layerShell->events.new_surface, &m_newLayerSurface);
m_foreignToplevelManager = wlr_foreign_toplevel_manager_v1_create(m_display);
m_extForeignToplevelList = wlr_ext_foreign_toplevel_list_v1_create(m_display, 1);
m_toplevelCaptureSourceManager = wlr_ext_foreign_toplevel_image_capture_source_manager_v1_create(m_display, 1);
m_toplevelCaptureRequest.notify = onToplevelCaptureRequest;
wl_signal_add(&m_toplevelCaptureSourceManager->events.new_request, &m_toplevelCaptureRequest);
m_workspaceManager = wlr_ext_workspace_manager_v1_create(m_display, 1);
m_workspaceCommit.notify = onWorkspaceCommit;
wl_signal_add(&m_workspaceManager->events.commit, &m_workspaceCommit);
m_sessionLockManager = wlr_session_lock_manager_v1_create(m_display);
m_newSessionLock.notify = onNewSessionLock;
wl_signal_add(&m_sessionLockManager->events.new_lock, &m_newSessionLock);
m_relativePointerManager = wlr_relative_pointer_manager_v1_create(m_display);
m_pointerConstraints = wlr_pointer_constraints_v1_create(m_display);
m_newPointerConstraint.notify = onNewPointerConstraint;
wl_signal_add(&m_pointerConstraints->events.new_constraint, &m_newPointerConstraint);
m_pointerGestures = wlr_pointer_gestures_v1_create(m_display);
m_virtualKeyboardManager = wlr_virtual_keyboard_manager_v1_create(m_display);
m_newVirtualKeyboard.notify = onNewVirtualKeyboard;
wl_signal_add(&m_virtualKeyboardManager->events.new_virtual_keyboard, &m_newVirtualKeyboard);
m_virtualPointerManager = wlr_virtual_pointer_manager_v1_create(m_display);
m_newVirtualPointer.notify = onNewVirtualPointer;
wl_signal_add(&m_virtualPointerManager->events.new_virtual_pointer, &m_newVirtualPointer);
m_tabletManager = wlr_tablet_v2_create(m_display);
m_idleNotifier = wlr_idle_notifier_v1_create(m_display);
m_idleInhibitManager = wlr_idle_inhibit_v1_create(m_display);
m_newIdleInhibitor.notify = onNewIdleInhibitor;
wl_signal_add(&m_idleInhibitManager->events.new_inhibitor, &m_newIdleInhibitor);
m_shortcutsInhibitManager = wlr_keyboard_shortcuts_inhibit_v1_create(m_display);
if (m_shortcutsInhibitManager == nullptr) {
throw std::runtime_error("failed to create keyboard-shortcuts-inhibit manager");
}
m_newShortcutsInhibitor.notify = onNewShortcutsInhibitor;
wl_signal_add(&m_shortcutsInhibitManager->events.new_inhibitor, &m_newShortcutsInhibitor);
wlr_screencopy_manager_v1_create(m_display);
wlr_ext_output_image_capture_source_manager_v1_create(m_display, 1);
wlr_ext_image_copy_capture_manager_v1* imageCopyManager =
wlr_ext_image_copy_capture_manager_v1_create(m_display, 1);
if (imageCopyManager == nullptr) {
throw std::runtime_error("failed to create image-copy-capture manager");
}
m_newImageCopySession.notify = onNewImageCopySession;
wl_signal_add(&imageCopyManager->events.new_session, &m_newImageCopySession);
// Create the manager so apply/test listeners stay wired, but leave heads empty (see updateOutputManagerConfig).
// Advertising a full configuration on bind currently takes down the desktop shell from this flake.
m_outputManager = wlr_output_manager_v1_create(m_display);
m_outputManagerApply.notify = onOutputManagerApply;
wl_signal_add(&m_outputManager->events.apply, &m_outputManagerApply);
m_outputManagerTest.notify = onOutputManagerTest;
wl_signal_add(&m_outputManager->events.test, &m_outputManagerTest);
m_xdgActivation = wlr_xdg_activation_v1_create(m_display);
m_newActivationToken.notify = onNewActivationToken;
wl_signal_add(&m_xdgActivation->events.new_token, &m_newActivationToken);
m_requestActivate.notify = onRequestActivate;
wl_signal_add(&m_xdgActivation->events.request_activate, &m_requestActivate);
m_cursor = std::make_unique<Cursor>(*this);
// Registered after the cursor attaches to the layout: wlr_cursor's own listener clamps the pointer first.
m_outputLayoutChange.notify = onOutputLayoutChange;
wl_signal_add(&m_outputLayout->events.change, &m_outputLayoutChange);
m_seat = std::make_unique<Seat>(*this);
m_padKeyboardFocusChange.notify = onPadKeyboardFocusChange;
wl_signal_add(&m_seat->wlr()->keyboard_state.events.focus_change, &m_padKeyboardFocusChange);
m_layerKeyboardFocusChange.notify = onLayerKeyboardFocusChange;
wl_signal_add(&m_seat->wlr()->keyboard_state.events.focus_change, &m_layerKeyboardFocusChange);
m_inputMethodRelay = std::make_unique<InputMethodRelay>(*this);
m_keyboardLeds =
std::make_unique<KeyboardLeds>(wl_display_get_event_loop(m_display), [this](wlr_keyboard* keyboard) {
return m_inputMethodRelay == nullptr || !m_inputMethodRelay->ownsKeyboard(keyboard);
});
m_gestures = std::make_unique<Gestures>(*this);
m_overview = std::make_unique<Overview>(*this);
updateSeatCapabilities();
m_newOutput.notify = onNewOutput;
wl_signal_add(&m_backend->events.new_output, &m_newOutput);
m_newInput.notify = onNewInput;
wl_signal_add(&m_backend->events.new_input, &m_newInput);
wlr_log(WLR_INFO, "mod key: %s (%s session)", m_nested ? "Alt" : "Super", m_nested ? "nested" : "native");
kLog.info("mod key: {} ({} session)", m_nested ? "Alt" : "Super", m_nested ? "nested" : "native");
}
namespace {
// wlroots never announces ext-image-copy-capture cursor sessions and their struct is private, so the only
// public trace of "this client asked for cursor metadata for this source" is the update listener the session
// attaches to that source's cursor. Probing it per source keeps a cursor session bound to output A from
// pacing the same client's pixel-only capture of output B. The seat is only what the interface takes; the
// output source ignores it.
constexpr std::string_view kSourceInterface = "ext_image_capture_source_v1";
struct CursorSessionProbe {
const wlr_output* output = nullptr;
wlr_seat* seat = nullptr;
bool found = false;
};
wl_iterator_result probeCursorSession(wl_resource* resource, void* data) {
auto* probe = static_cast<CursorSessionProbe*>(data);
const char* klass = wl_resource_get_class(resource);
if (klass == nullptr || std::string_view(klass) != kSourceInterface) {
return WL_ITERATOR_CONTINUE;
}
wlr_ext_image_capture_source_v1* source = wlr_ext_image_capture_source_v1_from_resource(resource);
if (source == nullptr || wlr_output_try_from_ext_image_capture_source_v1(source) != probe->output) {
return WL_ITERATOR_CONTINUE;
}
// Only a live cursor session for exactly this source has a listener here; its destroy path removes it.
const wlr_ext_image_capture_source_v1_cursor* cursor = source->impl->get_pointer_cursor(source, probe->seat);
if (cursor != nullptr && !wl_list_empty(&cursor->events.update.listener_list)) {
probe->found = true;
return WL_ITERATOR_STOP;
}
return WL_ITERATOR_CONTINUE;
}
} // namespace
bool Server::outputCaptured(const wlr_output* output) const {
return output != nullptr
&& std::ranges::any_of(m_imageCopySessions, [output](const std::unique_ptr<ImageCopySessionWatch>& watch) {
return watch->session != nullptr && watch->output == output;
});
}
bool Server::hasCopyCaptureFor(const wlr_output* output) const {
if (output == nullptr) {
return false;
}
for (const auto& watch : m_imageCopySessions) {
if (watch->session == nullptr || watch->output != output) {
continue;
}
wl_client* client = wl_resource_get_client(watch->session->resource);
if (client == nullptr) {
continue;
}
CursorSessionProbe probe{.output = output, .seat = m_seat != nullptr ? m_seat->wlr() : nullptr};
wl_client_for_each_resource(client, probeCursorSession, &probe);
if (probe.found) {
return true;
}
}
return false;
}
Server::~Server() {
m_stopping = true;
updateDrmLeaseState();
m_inputCapture.reset();
if (m_sessionActive.link.next != nullptr) {
wl_list_remove(&m_sessionActive.link);
}
m_keyboardLeds.reset();
xkb_keymap_unref(m_compiledKeymap);
if (m_cursor != nullptr) {
m_cursor->finishToplevelDrag(false);
}
if (m_sessionExitResultSource != nullptr) {
wl_event_source_remove(m_sessionExitResultSource);
}
if (m_sessionExitResultFd >= 0) {
close(m_sessionExitResultFd);
}
if (m_lidStateReconcileIdle != nullptr) {
wl_event_source_remove(m_lidStateReconcileIdle);
m_lidStateReconcileIdle = nullptr;
}
if (m_rendererRecoveryIdle != nullptr) {
wl_event_source_remove(m_rendererRecoveryIdle);
m_rendererRecoveryIdle = nullptr;
}
if (m_suspensionSyncIdle != nullptr) {
wl_event_source_remove(m_suspensionSyncIdle);
m_suspensionSyncIdle = nullptr;
}
if (m_protocolLogger != nullptr) {
wl_protocol_logger_destroy(m_protocolLogger);
m_protocolLogger = nullptr;
}
wl_list_remove(&m_clientCreated.link);
wl_list_remove(&m_newOutput.link);
wl_list_remove(&m_newInput.link);
wl_list_remove(&m_newXdgToplevel.link);
wl_list_remove(&m_setXdgToplevelTag.link);
wl_list_remove(&m_newXdgDialog.link);
wl_list_remove(&m_newXdgPopup.link);
wl_list_remove(&m_newXdgDecoration.link);
wl_list_remove(&m_newLegacyDecoration.link);
wl_list_remove(&m_newLayerSurface.link);
wl_list_remove(&m_newSessionLock.link);