-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1099 lines (935 loc) · 42 KB
/
main.cpp
File metadata and controls
1099 lines (935 loc) · 42 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
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 wayland-cxx-scanner contributors
//
// xdg-csd — Client-Side Decoration example with plugin architecture
//
// Demonstrates the zxdg_decoration_manager_v1 protocol for negotiating
// CSD vs SSD with the compositor, and renders client-side decorations
// (title bar with close/maximize/minimize buttons, resize borders)
// using a pluggable CSD rendering backend.
//
// Following the plugin pattern from libdecor
// (https://gitlab.freedesktop.org/libdecor/libdecor/-/tree/master/src/plugins/gtk):
// • GtkCsdPlugin — GTK-themed decorations via Cairo/Pango (optional)
// • FallbackCsdPlugin — flat-color SHM decorations (always available)
//
// The build system selects the GTK plugin when gtk+-3.0 is available,
// otherwise falls back to the regular plugin.
//
// This example provides equivalent functionality to libdecor's core
// decoration features:
// • Decoration mode negotiation via xdg-decoration-unstable-v1
// • Title bar rendering with window control buttons
// • Resize borders around the window
// • Interactive move (click title bar), resize (click border),
// and close (click close button) via pointer events
// • Proper xdg_surface.set_window_geometry to exclude decorations
//
// Usage:
// xdg_csd [-w WIDTH] [-h HEIGHT] [-t TITLE]
// clang-tidy: suppress diagnostics common to Wayland C-API boundary code.
// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables,
// cppcoreguidelines-pro-bounds-pointer-arithmetic,
// cppcoreguidelines-pro-bounds-array-to-pointer-decay,
// cppcoreguidelines-pro-bounds-constant-array-index,
// cppcoreguidelines-pro-type-reinterpret-cast)
// ── Generated C++ protocol headers ───────────────────────────────────────────
#include "wayland_client.hpp" // namespace wayland::client
#include "xdg_decoration_unstable_v1_client.hpp" // namespace xdg_decoration_unstable_v1::client
#include "xdg_shell_client.hpp" // namespace xdg_shell::client
// ── Framework headers ────────────────────────────────────────────────────────
#include <wl/client_helpers.hpp>
#include <wl/csd_plugin.hpp>
#ifdef USE_GTK_CSD
#include <wl/csd_gtk.hpp>
#elif defined(USE_CAIRO_CSD)
#include <wl/csd_cairo.hpp>
#else
#include <wl/csd_fallback.hpp>
#endif
#include <wl/display.hpp>
#include <wl/raii.hpp>
#include <wl/registry.hpp>
#include <wl/seat.hpp>
#include <wl/wl_ptr.hpp>
#include <wl/xdg_decoration.hpp>
#include <wl/xdg_shell.hpp>
// ── System Wayland C headers ─────────────────────────────────────────────────
extern "C" {
#include <linux/input-event-codes.h>
#include <sys/mman.h>
#include <unistd.h>
#include <wayland-client-protocol.h>
#include <wayland-util.h>
}
// ── Standard library ─────────────────────────────────────────────────────────
#include <algorithm>
#include <array>
#include <cerrno>
#include <climits>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iterator>
#include <span>
#include <string_view>
#include <vector>
// ══════════════════════════════════════════════════════════════════════════════
// wl_iface() — core Wayland interfaces
//
// wl_seat_traits::wl_iface() and wl_keyboard_traits::wl_iface() are provided
// inline by <wl/seat.hpp>.
// All xdg_shell traits are provided inline by <wl/xdg_shell.hpp>.
// All xdg_decoration traits are provided inline by <wl/xdg_decoration.hpp>.
// ══════════════════════════════════════════════════════════════════════════════
namespace wayland::client {
const wl_interface& wl_callback_traits::wl_iface() noexcept {
return wl_callback_interface;
}
const wl_interface& wl_compositor_traits::wl_iface() noexcept {
return wl_compositor_interface;
}
const wl_interface& wl_surface_traits::wl_iface() noexcept {
return wl_surface_interface;
}
const wl_interface& wl_shm_pool_traits::wl_iface() noexcept {
return wl_shm_pool_interface;
}
const wl_interface& wl_shm_traits::wl_iface() noexcept {
return wl_shm_interface;
}
const wl_interface& wl_buffer_traits::wl_iface() noexcept {
return wl_buffer_interface;
}
const wl_interface& wl_pointer_traits::wl_iface() noexcept {
return wl_pointer_interface;
}
} // namespace wayland::client
// ══════════════════════════════════════════════════════════════════════════════
// CSD types — provided by the plugin interface in <wl/csd_plugin.hpp>
// ══════════════════════════════════════════════════════════════════════════════
using wl::csd::CsdPlugin;
using wl::csd::HitZone;
// ══════════════════════════════════════════════════════════════════════════════
// Shared-memory helper
// ══════════════════════════════════════════════════════════════════════════════
struct ShmMapping {
int fd = -1;
void* data = MAP_FAILED;
std::size_t size = 0;
ShmMapping() = default;
~ShmMapping() noexcept { Reset(); }
ShmMapping(const ShmMapping&) = delete;
ShmMapping& operator=(const ShmMapping&) = delete;
ShmMapping(ShmMapping&&) = delete;
ShmMapping& operator=(ShmMapping&&) = delete;
[[nodiscard]] bool Create(std::size_t n) noexcept {
Reset();
fd = memfd_create("xdg-csd", 0);
if (fd < 0)
return false;
if (ftruncate(fd, static_cast<off_t>(n)) < 0) {
Reset();
return false;
}
data = mmap(nullptr, n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) {
Reset();
return false;
}
size = n;
return true;
}
void Reset() noexcept {
if (data != MAP_FAILED) {
munmap(data, size);
data = MAP_FAILED;
}
if (fd >= 0) {
close(fd);
fd = -1;
}
size = 0;
}
};
// ══════════════════════════════════════════════════════════════════════════════
// CRTP handler classes
// ══════════════════════════════════════════════════════════════════════════════
class App;
// ── WlCompositorHandler ─────────────────────────────────────────────────────
class WlCompositorHandler
: public wayland::client::CWlCompositor<WlCompositorHandler> {
public:
};
// ── WlShmPoolHandler ────────────────────────────────────────────────────────
class WlShmPoolHandler : public wayland::client::CWlShmPool<WlShmPoolHandler> {
public:
};
// ── WlShmHandler ────────────────────────────────────────────────────────────
class WlShmHandler : public wayland::client::CWlShm<WlShmHandler> {
public:
uint32_t formats = 0;
void OnFormat(uint32_t fmt) override {
if (fmt < 32u)
formats |= (1u << fmt);
}
};
// ── WlBufferHandler ─────────────────────────────────────────────────────────
class WlBufferHandler : public wayland::client::CWlBuffer<WlBufferHandler> {
public:
bool busy = false;
void OnRelease() override { busy = false; }
};
// ── WlSurfaceHandler ────────────────────────────────────────────────────────
class WlSurfaceHandler : public wayland::client::CWlSurface<WlSurfaceHandler> {
};
// ── WlCallbackHandler ───────────────────────────────────────────────────────
class WlCallbackHandler
: public wayland::client::CWlCallback<WlCallbackHandler> {
public:
App* app_ = nullptr;
void OnDone(uint32_t time_ms) override;
};
// ── WlPointerHandler ────────────────────────────────────────────────────────
class WlPointerHandler : public wayland::client::CWlPointer<WlPointerHandler> {
public:
App* app_ = nullptr;
void OnEnter(uint32_t serial,
wl_proxy* surface,
wl_fixed_t sx,
wl_fixed_t sy) override;
void OnLeave(uint32_t serial, wl_proxy* surface) override;
void OnMotion(uint32_t time, wl_fixed_t sx, wl_fixed_t sy) override;
void OnButton(uint32_t serial,
uint32_t time,
uint32_t button,
uint32_t state) override;
void OnAxis(uint32_t, uint32_t, wl_fixed_t) override {}
void OnFrame() override {}
void OnAxisSource(uint32_t) override {}
void OnAxisStop(uint32_t, uint32_t) override {}
void OnAxisDiscrete(uint32_t, int32_t) override {}
void OnAxisValue120(uint32_t, int32_t) override {}
void OnAxisRelativeDirection(uint32_t, uint32_t) override {}
};
// ── XDG shell handlers provided by <wl/xdg_shell.hpp> ──────────────────────
// wl::XdgWmBaseHandler — responds to ping automatically
// wl::XdgSurfaceHandler<App> — acks configure, calls OnXdgSurfaceConfigure
// wl::XdgToplevelHandler<App> — delegates configure/close to App
// ── XDG decoration handlers provided by <wl/xdg_decoration.hpp> ─────────────
// wl::XdgDecorationHandler<App> — delegates configure to App
// ── Seat handler (custom — manages both keyboard and pointer) ───────────────
class SeatHandler : public wayland::client::CWlSeat<SeatHandler> {
public:
App* app_ = nullptr;
void OnCapabilities(uint32_t caps) override;
void OnName(const char*) override {}
};
// ══════════════════════════════════════════════════════════════════════════════
// Buffer pool — pre-allocates 2 double-buffered wl_shm buffers
// ══════════════════════════════════════════════════════════════════════════════
static constexpr int kNumBuffers = 2;
struct BufferPool {
ShmMapping mem;
std::array<wl::WlPtr<WlBufferHandler>, static_cast<std::size_t>(kNumBuffers)>
bufs;
int next = 0;
int width = 0;
int height = 0;
[[nodiscard]] bool Create(int w, int h, wl_proxy* shm_raw) noexcept;
void Recreate(int w, int h, wl_proxy* shm_raw) noexcept {
for (auto& b : bufs)
b.Reset();
mem.Reset();
next = 0;
static_cast<void>(Create(w, h, shm_raw));
}
[[nodiscard]] void* PixelData(int i) const noexcept {
const std::size_t stride = static_cast<std::size_t>(width) * 4u;
return static_cast<uint8_t*>(mem.data) +
static_cast<std::size_t>(i) * stride *
static_cast<std::size_t>(height);
}
[[nodiscard]] int NextFree() noexcept {
for (int attempt = 0; attempt < kNumBuffers; ++attempt) {
const int idx = (next + attempt) % kNumBuffers;
if (!bufs.at(static_cast<std::size_t>(idx)).Get()->busy) {
next = (idx + 1) % kNumBuffers;
return idx;
}
}
return -1;
}
};
bool BufferPool::Create(int w, int h, wl_proxy* shm_raw) noexcept {
using namespace wayland::client;
width = w;
height = h;
const std::size_t stride = static_cast<std::size_t>(w) * 4u;
const std::size_t per_buf = stride * static_cast<std::size_t>(h);
const std::size_t total = per_buf * static_cast<std::size_t>(kNumBuffers);
if (!mem.Create(total)) {
std::fprintf(stderr, "xdg-csd: SHM allocation failed\n");
return false;
}
wl::WlPtr<WlShmPoolHandler> pool;
{
wl_shm_pool* raw_pool = wl_shm_create_pool(
reinterpret_cast<wl_shm*>(shm_raw), mem.fd, static_cast<int>(total));
if (!raw_pool) {
std::fprintf(stderr, "xdg-csd: wl_shm_create_pool failed\n");
return false;
}
pool.Attach(reinterpret_cast<wl_proxy*>(raw_pool));
}
for (int i = 0; i < kNumBuffers; ++i) {
const auto offset =
static_cast<int32_t>(static_cast<std::size_t>(i) * per_buf);
if (wl_proxy* raw = wl::construct<wl_buffer_traits,
wl_shm_pool_traits::Op::CreateBuffer>(
*pool.Get(), offset, w, h, static_cast<int32_t>(stride),
WL_SHM_FORMAT_XRGB8888)) {
bufs.at(static_cast<std::size_t>(i)).Get()->_SetProxy(raw);
} else {
std::fprintf(stderr, "xdg-csd: wl_shm_pool.create_buffer [%d] failed\n",
i);
return false;
}
}
pool.Reset();
return true;
}
// ══════════════════════════════════════════════════════════════════════════════
// Pixel painting
// ══════════════════════════════════════════════════════════════════════════════
/// Paint the content area only (no decorations — SSD mode).
static void paint_ssd_frame(std::span<uint32_t> buf,
int width,
int height,
uint32_t time) noexcept {
const int halfh = height / 2;
const int halfw = width / 2;
int64_t outer_r = (halfw < halfh ? halfw : halfh) - 8;
const int64_t inner_r = outer_r - 32;
outer_r *= outer_r;
const int64_t inner_r2 = inner_r * inner_r;
for (int y = 0; y < height; ++y) {
const int64_t oy = y - halfh;
const int64_t y2 = oy * oy;
for (int x = 0; x < width; ++x) {
uint32_t v;
const int64_t ox = x - halfw;
const int64_t r2 = ox * ox + y2;
if (r2 < inner_r2)
v = (static_cast<uint32_t>(r2 / 32) + time / 64) * 0x0080401u;
else if (r2 < outer_r)
v = (static_cast<uint32_t>(y) + time / 32) * 0x0080401u;
else
v = (static_cast<uint32_t>(x) + time / 16) * 0x0080401u;
v &= 0x00FFFFFFu;
if (std::abs(x - y) > 6 && std::abs(x + y - height) > 6)
v |= 0xFF000000u;
const std::size_t idx =
static_cast<std::size_t>(y) * static_cast<std::size_t>(width) +
static_cast<std::size_t>(x);
buf[idx] = v;
}
}
}
// ══════════════════════════════════════════════════════════════════════════════
// App class
// ══════════════════════════════════════════════════════════════════════════════
class App {
public:
App(int content_w,
int content_h,
const char* title,
std::unique_ptr<CsdPlugin> plugin)
: content_w_(content_w),
content_h_(content_h),
title_(title),
csd_plugin_(std::move(plugin)) {
if (csd_plugin_)
csd_plugin_->SetTitle(title);
}
~App();
int Run();
// ── Callbacks from CRTP handlers ──────────────────────────────────────────
void OnXdgSurfaceConfigure(uint32_t serial);
void OnToplevelConfigure(int32_t width, int32_t height);
void OnToplevelClose();
void OnDecorationConfigure(uint32_t mode);
void OnKey(uint32_t key, uint32_t state);
void OnFrameDone(uint32_t stamp_ms) noexcept;
// ── Pointer callbacks ─────────────────────────────────────────────────────
void OnPointerEnter(uint32_t serial, wl_fixed_t sx, wl_fixed_t sy) noexcept;
void OnPointerLeave() noexcept;
void OnPointerMotion(wl_fixed_t sx, wl_fixed_t sy) noexcept;
void OnPointerButton(uint32_t serial,
uint32_t button,
uint32_t state) noexcept;
// ── Seat capability callback ──────────────────────────────────────────────
void OnSeatCapabilities(uint32_t caps) noexcept;
private:
// ── Configuration ─────────────────────────────────────────────────────────
int content_w_;
int content_h_;
const char* title_;
// ── Decoration state ──────────────────────────────────────────────────────
bool use_csd_ = true; // default to CSD if no decoration manager
bool maximized_ = false;
// ── CSD plugin (fallback or GTK-themed) ───────────────────────────────
std::unique_ptr<CsdPlugin> csd_plugin_;
// ── Computed surface dimensions ───────────────────────────────────────────
[[nodiscard]] int SurfaceWidth() const noexcept {
return use_csd_ && csd_plugin_ ? csd_plugin_->SurfaceWidth(content_w_)
: content_w_;
}
[[nodiscard]] int SurfaceHeight() const noexcept {
return use_csd_ && csd_plugin_ ? csd_plugin_->SurfaceHeight(content_h_)
: content_h_;
}
// ── Hit testing ───────────────────────────────────────────────────────────
[[nodiscard]] HitZone HitTest(int x, int y) const noexcept;
// ── Wayland objects ───────────────────────────────────────────────────────
wl::DisplayHandle display_;
wl::CRegistry registry_;
wl::WlPtr<WlCompositorHandler> compositor_;
wl::WlPtr<WlShmHandler> shm_;
wl::WlPtr<wl::XdgWmBaseHandler> xdg_wm_base_;
// Optional: xdg-decoration.
wl::WlPtr<wl::XdgDecorationManagerHandler> decoration_mgr_;
wl::WlPtr<wl::XdgDecorationHandler<App>> decoration_;
// Input: seat + keyboard + pointer.
wl::SeatManager<App> seat_;
wl::WlPtr<SeatHandler> seat_handler_;
wl::WlPtr<WlPointerHandler> pointer_;
uint32_t seat_name_ = 0;
uint32_t seat_ver_ = 0;
wl::WlPtr<WlSurfaceHandler> surface_;
wl::WlPtr<wl::XdgSurfaceHandler<App>> xdg_surface_;
wl::WlPtr<wl::XdgToplevelHandler<App>> xdg_toplevel_;
wl::WlPtr<WlCallbackHandler> frame_cb_;
BufferPool pool_;
// ── Application state ─────────────────────────────────────────────────────
bool running_ = true;
bool configured_ = false;
bool need_redraw_ = true;
uint32_t last_time_ = 0;
// ── Pointer state ─────────────────────────────────────────────────────────
int pointer_x_ = 0;
int pointer_y_ = 0;
uint32_t pointer_serial_ = 0;
// ── Global IDs from registry scan ─────────────────────────────────────────
uint32_t compositor_name_ = 0, compositor_ver_ = 0;
uint32_t shm_name_ = 0, shm_ver_ = 0;
uint32_t xdg_wm_base_name_ = 0, xdg_wm_base_ver_ = 0;
uint32_t decoration_mgr_name_ = 0, decoration_mgr_ver_ = 0;
// ── Pipeline ──────────────────────────────────────────────────────────────
bool ConnectDisplay();
bool ScanGlobals();
bool BindGlobals();
bool CreateWindow();
bool CreateBuffers();
bool MainLoop();
void RequestFrameCallback() noexcept;
void CommitFrame(uint32_t time_ms) noexcept;
};
// ══════════════════════════════════════════════════════════════════════════════
// Handler implementations (need full App definition)
// ══════════════════════════════════════════════════════════════════════════════
void WlCallbackHandler::OnDone(uint32_t time_ms) {
app_->OnFrameDone(time_ms);
}
void WlPointerHandler::OnEnter(uint32_t serial,
wl_proxy* /*surface*/,
wl_fixed_t sx,
wl_fixed_t sy) {
app_->OnPointerEnter(serial, sx, sy);
}
void WlPointerHandler::OnLeave(uint32_t /*serial*/, wl_proxy* /*surface*/) {
app_->OnPointerLeave();
}
void WlPointerHandler::OnMotion(uint32_t /*time*/,
wl_fixed_t sx,
wl_fixed_t sy) {
app_->OnPointerMotion(sx, sy);
}
void WlPointerHandler::OnButton(uint32_t serial,
uint32_t /*time*/,
uint32_t button,
uint32_t state) {
app_->OnPointerButton(serial, button, state);
}
void SeatHandler::OnCapabilities(uint32_t caps) {
app_->OnSeatCapabilities(caps);
}
// ══════════════════════════════════════════════════════════════════════════════
// App method implementations
// ══════════════════════════════════════════════════════════════════════════════
static volatile std::sig_atomic_t g_running = 1;
int App::Run() {
if (!ConnectDisplay())
return EXIT_FAILURE;
if (!ScanGlobals())
return EXIT_FAILURE;
if (!BindGlobals())
return EXIT_FAILURE;
if (!CreateWindow())
return EXIT_FAILURE;
if (!CreateBuffers())
return EXIT_FAILURE;
return MainLoop() ? EXIT_SUCCESS : EXIT_FAILURE;
}
// ── ConnectDisplay ──────────────────────────────────────────────────────────
bool App::ConnectDisplay() {
if (!display_.Connect()) {
std::fprintf(stderr, "xdg-csd: wl_display_connect: %s\n",
std::strerror(errno));
return false;
}
return true;
}
// ── ScanGlobals ─────────────────────────────────────────────────────────────
bool App::ScanGlobals() {
if (!registry_.Create(display_.Get())) {
std::fprintf(stderr, "xdg-csd: registry creation failed\n");
return false;
}
registry_.OnGlobal([this](wl::CRegistry&, uint32_t name,
std::string_view iface, uint32_t ver) {
using namespace wayland::client;
using namespace xdg_shell::client;
using namespace xdg_decoration_unstable_v1::client;
if (iface == wl_compositor_traits::interface_name) {
compositor_name_ = name;
compositor_ver_ = ver;
} else if (iface == wl_shm_traits::interface_name) {
shm_name_ = name;
shm_ver_ = ver;
} else if (iface == xdg_wm_base_traits::interface_name) {
xdg_wm_base_name_ = name;
xdg_wm_base_ver_ = ver;
} else if (iface == zxdg_decoration_manager_v1_traits::interface_name) {
decoration_mgr_name_ = name;
decoration_mgr_ver_ = ver;
} else if (iface == wl_seat_traits::interface_name) {
seat_.Record(name, ver);
seat_name_ = name;
seat_ver_ = ver;
}
});
if (!wl::RoundtripWithTimeout(display_.Get())) {
std::fprintf(stderr, "xdg-csd: timed out waiting for globals\n");
return false;
}
if (!compositor_name_ || !shm_name_ || !xdg_wm_base_name_) {
std::fprintf(stderr, "xdg-csd: required globals not found\n");
return false;
}
return true;
}
// ── BindGlobals ─────────────────────────────────────────────────────────────
bool App::BindGlobals() {
using namespace wayland::client;
using namespace xdg_shell::client;
using namespace xdg_decoration_unstable_v1::client;
// wl_compositor — no events.
if (wl_proxy* raw = registry_.Bind<wl_compositor_traits>(
compositor_name_,
std::min(compositor_ver_, wl_compositor_traits::version))) {
compositor_.Attach(raw);
} else {
std::fprintf(stderr, "xdg-csd: wl_compositor bind failed\n");
return false;
}
// wl_shm.
if (!wl::BindHandler<wl_shm_traits>(registry_, shm_, shm_name_, shm_ver_)) {
std::fprintf(stderr, "xdg-csd: wl_shm bind failed\n");
return false;
}
// xdg_wm_base.
if (!wl::BindHandler<xdg_wm_base_traits>(
registry_, xdg_wm_base_, xdg_wm_base_name_, xdg_wm_base_ver_)) {
std::fprintf(stderr, "xdg-csd: xdg_wm_base bind failed\n");
return false;
}
// zxdg_decoration_manager_v1 — optional.
if (decoration_mgr_name_) {
if (wl_proxy* raw = registry_.Bind<zxdg_decoration_manager_v1_traits>(
decoration_mgr_name_,
std::min(decoration_mgr_ver_,
zxdg_decoration_manager_v1_traits::version))) {
decoration_mgr_.Attach(raw);
}
}
if (decoration_mgr_.IsNull()) {
std::fprintf(stderr,
"xdg-csd: zxdg_decoration_manager_v1 not available — "
"falling back to client-side decorations\n");
}
// wl_seat — binds keyboard via SeatManager, pointer separately.
if (!seat_.Bind(registry_, this)) {
std::fprintf(stderr, "xdg-csd: wl_seat bind failed\n");
return false;
}
// Bind seat separately for pointer management.
if (seat_name_) {
const uint32_t ver =
std::min(seat_ver_, wayland::client::wl_seat_traits::version);
if (wl_proxy* raw = registry_.Bind<wl_seat_traits>(seat_name_, ver)) {
if (wl::SetupHandler(seat_handler_, raw)) {
seat_handler_.Get()->app_ = this;
}
}
}
// Roundtrip to receive formats and capabilities.
if (!wl::RoundtripWithTimeout(display_.Get())) {
std::fprintf(stderr, "xdg-csd: timed out waiting for formats\n");
return false;
}
constexpr uint32_t kXrgb8888 = 1u;
if (!(shm_.Get()->formats & (1u << kXrgb8888))) {
std::fprintf(stderr, "xdg-csd: WL_SHM_FORMAT_XRGB8888 not supported\n");
return false;
}
return true;
}
// ── CreateWindow ────────────────────────────────────────────────────────────
bool App::CreateWindow() {
using namespace wayland::client;
using namespace xdg_shell::client;
using namespace xdg_decoration_unstable_v1::client;
// wl_surface.
if (wl_proxy* raw = wl::construct<wl_surface_traits,
wl_compositor_traits::Op::CreateSurface>(
*compositor_.Get())) {
surface_.Get()->_SetProxy(raw);
} else {
std::fprintf(stderr, "xdg-csd: wl_compositor.create_surface failed\n");
return false;
}
// xdg_surface.
if (!wl::SetupHandler(xdg_surface_,
wl::construct<xdg_surface_traits,
xdg_wm_base_traits::Op::GetXdgSurface>(
*xdg_wm_base_.Get(), surface_.Get()->GetProxy()))) {
std::fprintf(stderr, "xdg-csd: xdg_wm_base.get_xdg_surface failed\n");
return false;
}
xdg_surface_.Get()->app_ = this;
// xdg_toplevel.
if (!wl::SetupHandler(xdg_toplevel_,
wl::construct<xdg_toplevel_traits,
xdg_surface_traits::Op::GetToplevel>(
*xdg_surface_.Get()))) {
std::fprintf(stderr, "xdg-csd: xdg_surface.get_toplevel failed\n");
return false;
}
auto* toplevel = xdg_toplevel_.Get();
toplevel->app_ = this;
toplevel->SetTitle(title_);
toplevel->SetAppId("org.wayland-cxx.xdg-csd");
// Negotiate decoration mode via zxdg_decoration_manager_v1.
if (!decoration_mgr_.IsNull()) {
if (wl_proxy* raw = wl::construct<
zxdg_toplevel_decoration_v1_traits,
zxdg_decoration_manager_v1_traits::Op::GetToplevelDecoration>(
*decoration_mgr_.Get(), xdg_toplevel_.Get()->GetProxy())) {
if (wl::SetupHandler(decoration_, raw)) {
decoration_.Get()->app_ = this;
// Request client-side decorations.
decoration_.Get()->SetMode(
static_cast<uint32_t>(ZxdgToplevelDecorationV1Mode::ClientSide));
}
}
}
// Commit to trigger the configure sequence.
surface_.Get()->Commit();
if (!wl::RoundtripWithTimeout(display_.Get())) {
std::fprintf(stderr, "xdg-csd: timed out waiting for configure\n");
return false;
}
return true;
}
// ── CreateBuffers ───────────────────────────────────────────────────────────
bool App::CreateBuffers() {
return pool_.Create(SurfaceWidth(), SurfaceHeight(), shm_.Get()->GetProxy());
}
// ── Hit testing ─────────────────────────────────────────────────────────────
HitZone App::HitTest(int x, int y) const noexcept {
if (!use_csd_ || !csd_plugin_)
return HitZone::Content;
return csd_plugin_->HitTest(x, y, SurfaceWidth(), SurfaceHeight(), content_w_,
content_h_);
}
// ── Callback implementations ────────────────────────────────────────────────
void App::OnXdgSurfaceConfigure(uint32_t /*serial*/) {
configured_ = true;
need_redraw_ = true;
}
void App::OnToplevelConfigure(int32_t width, int32_t height) {
if (width > 0 && height > 0) {
// The compositor provides the total window size.
// In CSD mode, subtract decoration space to get the content area.
if (use_csd_ && csd_plugin_) {
content_w_ = width - 2 * csd_plugin_->BorderWidth();
content_h_ =
height - csd_plugin_->TitleBarHeight() - csd_plugin_->BorderWidth();
} else {
content_w_ = width;
content_h_ = height;
}
static constexpr int kMaxDim = 16384;
content_w_ = std::clamp(content_w_, 1, kMaxDim);
content_h_ = std::clamp(content_h_, 1, kMaxDim);
need_redraw_ = true;
}
}
void App::OnToplevelClose() {
running_ = false;
}
void App::OnDecorationConfigure(uint32_t mode) {
const bool was_csd = use_csd_;
use_csd_ = (mode == static_cast<uint32_t>(
xdg_decoration_unstable_v1::client::
ZxdgToplevelDecorationV1Mode::ClientSide));
if (was_csd != use_csd_) {
need_redraw_ = true;
std::fprintf(stderr, "xdg-csd: decoration mode → %s\n",
use_csd_ ? "client-side" : "server-side");
}
}
void App::OnKey(const uint32_t key, const uint32_t state) {
if (key == KEY_ESC && state == WL_KEYBOARD_KEY_STATE_PRESSED)
running_ = false;
}
void App::OnFrameDone(const uint32_t stamp_ms) noexcept {
wl_proxy* const spent = frame_cb_.Detach();
const auto guard = wl::ScopeExit{[spent] {
if (spent)
wl_proxy_destroy(spent);
}};
last_time_ = stamp_ms;
RequestFrameCallback();
CommitFrame(stamp_ms);
}
// ── Pointer event implementations ───────────────────────────────────────────
void App::OnPointerEnter(uint32_t serial,
wl_fixed_t sx,
wl_fixed_t sy) noexcept {
pointer_serial_ = serial;
pointer_x_ = wl_fixed_to_int(sx);
pointer_y_ = wl_fixed_to_int(sy);
}
void App::OnPointerLeave() noexcept {
pointer_x_ = -1;
pointer_y_ = -1;
}
void App::OnPointerMotion(wl_fixed_t sx, wl_fixed_t sy) noexcept {
pointer_x_ = wl_fixed_to_int(sx);
pointer_y_ = wl_fixed_to_int(sy);
}
void App::OnPointerButton(uint32_t serial,
uint32_t button,
uint32_t state) noexcept {
if (state != WL_POINTER_BUTTON_STATE_PRESSED)
return;
if (button != BTN_LEFT)
return;
const HitZone zone = HitTest(pointer_x_, pointer_y_);
switch (zone) {
case HitZone::TitleBar:
// Interactive move.
if (!seat_handler_.IsNull()) {
xdg_toplevel_.Get()->Move(seat_handler_.Get()->GetProxy(), serial);
}
break;
case HitZone::CloseButton:
running_ = false;
break;
case HitZone::MaximizeButton:
if (maximized_) {
xdg_toplevel_.Get()->UnsetMaximized();
maximized_ = false;
} else {
xdg_toplevel_.Get()->SetMaximized();
maximized_ = true;
}
break;
case HitZone::MinimizeButton:
xdg_toplevel_.Get()->SetMinimized();
break;
default: {
// Resize zones.
const uint32_t edge = wl::csd::HitZoneToResizeEdge(zone);
if (edge != 0 && !seat_handler_.IsNull()) {
xdg_toplevel_.Get()->Resize(seat_handler_.Get()->GetProxy(), serial,
edge);
}
} break;
}
}
// ── Seat capability handling ────────────────────────────────────────────────
void App::OnSeatCapabilities(uint32_t caps) noexcept {
using namespace wayland::client;
const bool has_pointer = (caps & WL_SEAT_CAPABILITY_POINTER) != 0u;
if (has_pointer && pointer_.IsNull()) {
if (wl_proxy* raw =
wl::construct<wl_pointer_traits, wl_seat_traits::Op::GetPointer>(
*seat_handler_.Get())) {
if (wl::SetupHandler(pointer_, raw)) {
pointer_.Get()->app_ = this;
}
}
} else if (!has_pointer && !pointer_.IsNull()) {
pointer_.Reset();
}
}
// ── Frame commit ────────────────────────────────────────────────────────────
void App::RequestFrameCallback() noexcept {
using wl_s = wayland::client::wl_surface_traits;
using wl_c = wayland::client::wl_callback_traits;
if (wl_proxy* raw = wl::construct<wl_c, wl_s::Op::Frame>(*surface_.Get())) {
frame_cb_.Get()->app_ = this;
frame_cb_.Get()->_SetProxy(raw);
}
}
void App::CommitFrame(uint32_t time_ms) noexcept {
const int sw = SurfaceWidth();
const int sh = SurfaceHeight();
// Recreate buffers if size changed.
if (pool_.width != sw || pool_.height != sh) {
pool_.Recreate(sw, sh, shm_.Get()->GetProxy());
}
const int idx = pool_.NextFree();
if (idx < 0) {
std::fprintf(stderr, "xdg-csd: all buffers busy — skipping frame\n");
return;
}
auto* pixels = static_cast<uint32_t*>(pool_.PixelData(idx));
const std::size_t npixels =
static_cast<std::size_t>(sw) * static_cast<std::size_t>(sh);
if (use_csd_ && csd_plugin_) {
csd_plugin_->RenderFrame(pixels, sw, sh, content_w_, content_h_, time_ms);
} else {
paint_ssd_frame({pixels, npixels}, sw, sh, time_ms);
}
// Set window geometry to exclude decoration area.
if (use_csd_ && csd_plugin_) {
xdg_surface_.Get()->SetWindowGeometry(csd_plugin_->BorderWidth(),
csd_plugin_->TitleBarHeight(),
content_w_, content_h_);
}
surface_.Get()->Attach(
pool_.bufs.at(static_cast<std::size_t>(idx)).Get()->GetProxy(), 0, 0);
surface_.Get()->Damage(0, 0, sw, sh);
surface_.Get()->Commit();
pool_.bufs.at(static_cast<std::size_t>(idx)).Get()->busy = true;
}
// ── MainLoop ────────────────────────────────────────────────────────────────
App::~App() {
// Release keyboard before members are destroyed.
seat_.Release();
// Release pointer.
if (!pointer_.IsNull()) {
pointer_.Reset();
}
// Destroy decoration before toplevel (protocol requirement).
decoration_.Reset();
}
bool App::MainLoop() {
std::fprintf(stderr,
"xdg-csd: %dx%d content, decorations=%s "
"(press ESC or click ✕ to quit)\n",
content_w_, content_h_, use_csd_ ? "CSD" : "SSD");
// Kickstart: request the first frame callback, then commit.
RequestFrameCallback();
CommitFrame(0);