aboutsummaryrefslogtreecommitdiff
path: root/src/platform/gui/xcb/Window.cpp
blob: f3480fe07c0a4d265cf5961f465f8ab46be2b2af (plain)
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
#include "cru/platform/gui/xcb/Window.h"
#include "cru/base/Base.h"
#include "cru/base/Guard.h"
#include "cru/platform/Check.h"
#include "cru/platform/GraphicsBase.h"
#include "cru/platform/graphics/Painter.h"
#include "cru/platform/graphics/cairo/CairoPainter.h"
#include "cru/platform/gui/Base.h"
#include "cru/platform/gui/Keyboard.h"
#include "cru/platform/gui/Window.h"
#include "cru/platform/gui/xcb/Keyboard.h"
#include "cru/platform/gui/xcb/UiApplication.h"

#include <cairo-xcb.h>
#include <cairo.h>
#include <xcb/xcb.h>
#include <xcb/xproto.h>
#include <cassert>
#include <cinttypes>
#include <cstdint>
#include <memory>
#include <optional>

namespace cru::platform::gui::xcb {

namespace {
MouseButton ConvertMouseButton(xcb_button_t button) {
  switch (button) {
    case 1:
      return MouseButtons::Left;
    case 2:
      return MouseButtons::Middle;
    case 3:
      return MouseButtons::Right;
    default:
      return MouseButtons::None;
  }
}

KeyModifier ConvertModifiers(uint32_t mask) {
  // const char *MODIFIERS[] = {
  //     "Shift", "Lock",    "Ctrl",    "Alt",     "Mod2",    "Mod3",   "Mod4",
  //     "Mod5",  "Button1", "Button2", "Button3", "Button4", "Button5"};
  constexpr KeyModifier MODIFIERS[] = {
      KeyModifiers::Shift, KeyModifiers::none, KeyModifiers::Ctrl,
      KeyModifiers::Alt,   KeyModifiers::none, KeyModifiers::none,
      KeyModifiers::none,  KeyModifiers::none, KeyModifiers::none,
      KeyModifiers::none,  KeyModifiers::none, KeyModifiers::none,
      KeyModifiers::none,
  };

  KeyModifier result;
  for (auto iter = std::begin(MODIFIERS); mask; mask >>= 1, ++iter) {
    if (mask & 1) {
      result |= *iter;
    }
  }
  return result;
}
}  // namespace

XcbWindow::XcbWindow(XcbUiApplication *application)
    : application_(application),
      xcb_window_(std::nullopt),
      cairo_surface_(nullptr),
      parent_(nullptr) {
  application->RegisterWindow(this);
}

XcbWindow::~XcbWindow() { application_->UnregisterWindow(this); }

void XcbWindow::Close() {
  if (xcb_window_) {
    xcb_destroy_window(application_->GetXcbConnection(), *xcb_window_);
  }
}

INativeWindow *XcbWindow::GetParent() { return parent_; }

void XcbWindow::SetParent(INativeWindow *parent) {
  parent_ = CheckPlatform<XcbWindow>(parent, GetPlatformIdUtf8());
  if (xcb_window_) {
    DoSetParent(*xcb_window_);
  }
}

WindowStyleFlag XcbWindow::GetStyleFlag() { return style_; }

void XcbWindow::SetStyleFlag(WindowStyleFlag flag) {
  style_ = flag;
  if (xcb_window_) {
    DoSetStyleFlags(*xcb_window_);
  }
}

String XcbWindow::GetTitle() { return String::FromUtf8(title_); }

void XcbWindow::SetTitle(String title) {
  title_ = title.ToUtf8();
  if (xcb_window_) {
    DoSetTitle(*xcb_window_);
  }
}

namespace {
constexpr int WithdrawnState = 0;
constexpr int NormalState = 1;
constexpr int IconicState = 3;
}  // namespace

WindowVisibilityType XcbWindow::GetVisibility() {
  if (!xcb_window_) return WindowVisibilityType::Hide;
  auto value = static_cast<std::uint32_t *>(
      XcbGetProperty(*xcb_window_, application_->GetXcbAtomWM_STATE(),
                     application_->GetXcbAtomWM_STATE(), 0, 1));
  if (value != nullptr && *value == IconicState) {
    return WindowVisibilityType::Minimize;
  }
  if (!mapped_) return WindowVisibilityType::Hide;
  return WindowVisibilityType::Show;
}

void XcbWindow::SetVisibility(WindowVisibilityType visibility) {
  auto update_wm_state = [this, visibility] {
    auto atom = application_->GetXcbAtomWM_STATE();
    auto window = *xcb_window_;

    std::uint32_t value[2];
    switch (visibility) {
      case WindowVisibilityType::Show:
        value[0] = NormalState;
        break;
      case WindowVisibilityType::Minimize:
        value[0] = IconicState;
        break;
      case WindowVisibilityType::Hide:
        value[0] = WithdrawnState;
        break;
      default:
        UnreachableCode();
    }

    auto old_value = static_cast<std::uint32_t *>(
        XcbGetProperty(*xcb_window_, atom, atom, 0, 2));
    if (old_value) value[1] = old_value[1];

    xcb_change_property(application_->GetXcbConnection(), XCB_PROP_MODE_REPLACE,
                        window, atom, atom, 32, sizeof(value) / sizeof(*value),
                        value);
  };

  switch (visibility) {
    case WindowVisibilityType::Show: {
      if (!xcb_window_) {
        DoCreateWindow();
      }
      update_wm_state();
      xcb_map_window(application_->GetXcbConnection(), *xcb_window_);
      break;
    }
    case WindowVisibilityType::Minimize: {
      if (!xcb_window_) {
        DoCreateWindow();
      }
      update_wm_state();
      xcb_unmap_window(application_->GetXcbConnection(), *xcb_window_);
      break;
    }
    case WindowVisibilityType::Hide: {
      if (!xcb_window_) {
        return;
      }
      update_wm_state();
      xcb_unmap_window(application_->GetXcbConnection(), *xcb_window_);
      break;
    }
    default:
      UnreachableCode();
  }
}

Size XcbWindow::GetClientSize() { return GetClientRect().GetSize(); }

void XcbWindow::SetClientSize(const Size &size) {
  auto rect = GetClientRect();
  SetClientRect(Rect(rect.GetLeftTop(), size));
}

Rect XcbWindow::GetClientRect() {
  if (!xcb_window_) {
    return Rect{};
  }

  auto window = *xcb_window_;

  auto cookie = xcb_get_geometry(application_->GetXcbConnection(), window);
  auto reply = FreeLater(xcb_get_geometry_reply(
      application_->GetXcbConnection(), cookie, nullptr));
  auto position = GetXcbWindowPosition(window);

  return Rect(position.x, position.y, reply->width, reply->height);
}

void XcbWindow::SetClientRect(const Rect &rect) {
  if (!xcb_window_) return;
  DoSetClientRect(*xcb_window_, rect);
}

Rect XcbWindow::GetWindowRect() {
  if (!xcb_window_) return {};

  auto client_rect = GetClientRect();
  auto frame_properties = Get_NET_FRAME_EXTENTS(*xcb_window_);

  if (frame_properties.has_value()) {
    return client_rect.Expand(*frame_properties);
  }

  return client_rect;
}

void XcbWindow::SetWindowRect(const Rect &rect) {
  if (!xcb_window_) return;

  auto real_rect = rect;
  auto frame_properties = Get_NET_FRAME_EXTENTS(*xcb_window_);

  if (frame_properties.has_value()) {
    real_rect = real_rect.Shrink(*frame_properties, true);
  }

  SetClientRect(real_rect);
}

bool XcbWindow::RequestFocus() {
  if (!xcb_window_) return false;
  xcb_set_input_focus(application_->GetXcbConnection(), XCB_NONE, *xcb_window_,
                      XCB_CURRENT_TIME);
  return true;
}

Point XcbWindow::GetMousePosition() {
  auto window = xcb_window_.value_or(application_->GetFirstXcbScreen()->root);
  auto cookie = xcb_query_pointer(application_->GetXcbConnection(), window);
  auto reply = FreeLater(xcb_query_pointer_reply(
      application_->GetXcbConnection(), cookie, nullptr));
  return Point(reply->win_x, reply->win_y);
}

bool XcbWindow::CaptureMouse() {
  if (!xcb_window_) return false;
  xcb_grab_pointer(application_->GetXcbConnection(), FALSE, *xcb_window_, 0,
                   XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE,
                   XCB_CURSOR_NONE, XCB_CURRENT_TIME);
  return true;
}

bool XcbWindow::ReleaseMouse() {
  if (!xcb_window_) return false;
  xcb_ungrab_pointer(application_->xcb_connection_, XCB_CURRENT_TIME);
  return true;
}

void XcbWindow::SetCursor(std::shared_ptr<ICursor> cursor) { NotImplemented(); }

void XcbWindow::SetToForeground() {
  SetVisibility(WindowVisibilityType::Show);
  assert(xcb_window_.has_value());
  const static uint32_t values[] = {XCB_STACK_MODE_ABOVE};
  xcb_configure_window(application_->GetXcbConnection(), *xcb_window_,
                       XCB_CONFIG_WINDOW_STACK_MODE, values);
}

void XcbWindow::RequestRepaint() {
  // TODO: true throttle
  paint_event_.Raise(nullptr);
}

std::unique_ptr<graphics::IPainter> XcbWindow::BeginPaint() {
  assert(cairo_surface_);

  auto factory = application_->GetCairoFactory();
  cairo_t *cairo = cairo_create(cairo_surface_);
  auto painter =
      new graphics::cairo::CairoPainter(factory, cairo, true, cairo_surface_);
  return std::unique_ptr<graphics::IPainter>(painter);
}

IEvent<std::nullptr_t> *XcbWindow::CreateEvent() { return &create_event_; }

IEvent<std::nullptr_t> *XcbWindow::DestroyEvent() { return &destroy_event_; }

IEvent<std::nullptr_t> *XcbWindow::PaintEvent() { return &paint_event_; }

IEvent<WindowVisibilityType> *XcbWindow::VisibilityChangeEvent() {
  return &visibility_change_event_;
}

IEvent<Size> *XcbWindow::ResizeEvent() { return &resize_event_; }

IEvent<FocusChangeType> *XcbWindow::FocusEvent() { return &focus_event_; }

IEvent<MouseEnterLeaveType> *XcbWindow::MouseEnterLeaveEvent() {
  return &mouse_enter_leave_event_;
}

IEvent<Point> *XcbWindow::MouseMoveEvent() { return &mouse_move_event_; }

IEvent<NativeMouseButtonEventArgs> *XcbWindow::MouseDownEvent() {
  return &mouse_down_event_;
}

IEvent<NativeMouseButtonEventArgs> *XcbWindow::MouseUpEvent() {
  return &mouse_up_event_;
}

IEvent<NativeMouseWheelEventArgs> *XcbWindow::MouseWheelEvent() {
  return &mouse_wheel_event_;
}

IEvent<NativeKeyEventArgs> *XcbWindow::KeyDownEvent() {
  return &key_down_event_;
}

IEvent<NativeKeyEventArgs> *XcbWindow::KeyUpEvent() { return &key_up_event_; }

IInputMethodContext *XcbWindow::GetInputMethodContext() { NotImplemented(); }

std::optional<xcb_window_t> XcbWindow::GetXcbWindow() { return xcb_window_; }

xcb_window_t XcbWindow::DoCreateWindow() {
  assert(xcb_window_ == std::nullopt);
  assert(cairo_surface_ == nullptr);

  auto connection = application_->GetXcbConnection();
  auto screen = application_->GetFirstXcbScreen();

  auto window = xcb_generate_id(connection);

  uint32_t mask = XCB_CW_EVENT_MASK;
  uint32_t values[1] = {
      XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY |
      XCB_EVENT_MASK_FOCUS_CHANGE | XCB_EVENT_MASK_BUTTON_PRESS |
      XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION |
      XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW |
      XCB_EVENT_MASK_KEY_PRESS | XCB_EVENT_MASK_KEY_RELEASE};

  int width = 400, height = 200;

  xcb_create_window(connection, XCB_COPY_FROM_PARENT, window, screen->root, 100,
                    100, width, height, 10, XCB_WINDOW_CLASS_INPUT_OUTPUT,
                    screen->root_visual, mask, values);
  current_size_ = Size(width, height);

  xcb_window_ = window;

  std::vector<xcb_atom_t> wm_protocols{
      application_->GetXcbAtomWM_DELETE_WINDOW()};
  xcb_change_property(application_->GetXcbConnection(), XCB_PROP_MODE_REPLACE,
                      window, application_->GetXcbAtomWM_PROTOCOLS(),
                      XCB_ATOM_ATOM, 32, wm_protocols.size(),
                      wm_protocols.data());

  DoSetStyleFlags(window);
  DoSetParent(window);

  xcb_visualtype_t *visual_type;

  for (xcb_depth_iterator_t depth_iter =
           xcb_screen_allowed_depths_iterator(screen);
       depth_iter.rem; xcb_depth_next(&depth_iter)) {
    for (xcb_visualtype_iterator_t visual_iter =
             xcb_depth_visuals_iterator(depth_iter.data);
         visual_iter.rem; xcb_visualtype_next(&visual_iter)) {
      if (screen->root_visual == visual_iter.data->visual_id) {
        visual_type = visual_iter.data;
        break;
      }
    }
  }

  cairo_surface_ =
      cairo_xcb_surface_create(connection, window, visual_type, width, height);

  create_event_.Raise(nullptr);

  return window;
}

void XcbWindow::HandleEvent(xcb_generic_event_t *event) {
  switch (event->response_type & ~0x80) {
    case XCB_EXPOSE: {
      paint_event_.Raise(nullptr);
      break;
    }
    case XCB_DESTROY_NOTIFY: {
      destroy_event_.Raise(nullptr);

      cairo_surface_destroy(cairo_surface_);
      cairo_surface_ = nullptr;
      xcb_window_ = std::nullopt;
      break;
    }
    case XCB_CONFIGURE_NOTIFY: {
      xcb_configure_notify_event_t *configure =
          (xcb_configure_notify_event_t *)event;
      auto width = configure->width, height = configure->height;
      if (width != current_size_.width || height != current_size_.height) {
        current_size_ = Size(width, height);
        assert(cairo_surface_);
        cairo_xcb_surface_set_size(cairo_surface_, width, height);
        resize_event_.Raise(current_size_);
      }
      break;
    }
    case XCB_MAP_NOTIFY: {
      visibility_change_event_.Raise(WindowVisibilityType::Show);
      mapped_ = true;
      break;
    }
    case XCB_UNMAP_NOTIFY: {
      visibility_change_event_.Raise(WindowVisibilityType::Hide);
      mapped_ = false;
      break;
    }
    case XCB_FOCUS_IN: {
      focus_event_.Raise(FocusChangeType::Gain);
      break;
    }
    case XCB_FOCUS_OUT: {
      focus_event_.Raise(FocusChangeType::Lose);
      break;
    }
    case XCB_BUTTON_PRESS: {
      xcb_button_press_event_t *bp = (xcb_button_press_event_t *)event;

      if (bp->detail >= 4 && bp->detail <= 7) {
        NativeMouseWheelEventArgs args(30, Point(bp->event_x, bp->event_y),
                                       ConvertModifiers(bp->state), false);
        if (bp->detail == 5 || bp->detail == 7) {
          args.delta = -args.delta;
        }
        if (bp->detail == 6 || bp->detail == 7) {
          args.horizontal = true;
        }
        mouse_wheel_event_.Raise(std::move(args));
        break;
      }

      NativeMouseButtonEventArgs args(ConvertMouseButton(bp->detail),
                                      Point(bp->event_x, bp->event_y),
                                      ConvertModifiers(bp->state));
      mouse_down_event_.Raise(std::move(args));
      break;
    }
    case XCB_BUTTON_RELEASE: {
      xcb_button_release_event_t *br = (xcb_button_release_event_t *)event;
      NativeMouseButtonEventArgs args(ConvertMouseButton(br->detail),
                                      Point(br->event_x, br->event_y),
                                      ConvertModifiers(br->state));
      mouse_up_event_.Raise(std::move(args));
      break;
    }
    case XCB_MOTION_NOTIFY: {
      xcb_motion_notify_event_t *motion = (xcb_motion_notify_event_t *)event;
      Point point(motion->event_x, motion->event_y);
      mouse_move_event_.Raise(point);
      break;
    }
    case XCB_ENTER_NOTIFY: {
      xcb_enter_notify_event_t *enter = (xcb_enter_notify_event_t *)event;
      mouse_enter_leave_event_.Raise(MouseEnterLeaveType::Enter);
      Point point(enter->event_x, enter->event_y);
      mouse_move_event_.Raise(point);
      break;
    }
    case XCB_LEAVE_NOTIFY: {
      // Should we do this?
      // xcb_leave_notify_event_t *leave = (xcb_leave_notify_event_t *)event;
      // Point point(leave->event_x, leave->event_y);
      // mouse_move_event_.Raise(point);
      mouse_enter_leave_event_.Raise(MouseEnterLeaveType::Leave);
      break;
    }
    case XCB_KEY_PRESS: {
      xcb_key_press_event_t *kp = (xcb_key_press_event_t *)event;
      NativeKeyEventArgs args(XorgKeycodeToCruKeyCode(application_, kp->detail),
                              ConvertModifiers(kp->state));
      key_down_event_.Raise(std::move(args));
      break;
    }
    case XCB_KEY_RELEASE: {
      xcb_key_release_event_t *kr = (xcb_key_release_event_t *)event;
      NativeKeyEventArgs args(XorgKeycodeToCruKeyCode(application_, kr->detail),
                              ConvertModifiers(kr->state));
      key_up_event_.Raise(std::move(args));
      break;
    }
    case XCB_CLIENT_MESSAGE: {
      xcb_client_message_event_t *cm = (xcb_client_message_event_t *)event;
      if (cm->data.data32[0] == application_->GetXcbAtomWM_DELETE_WINDOW() &&
          xcb_window_.has_value()) {
        xcb_destroy_window(application_->GetXcbConnection(),
                           xcb_window_.value());
        xcb_flush(application_->GetXcbConnection());
      }
      break;
    }
    default:
      /* Unknown event type, ignore it */
      printf("Unknown event: %" PRIu8 "\n", event->response_type);
      break;
  }
}

std::optional<xcb_window_t> XcbWindow::GetEventWindow(
    xcb_generic_event_t *event) {
  switch (event->response_type & ~0x80) {
    case XCB_EXPOSE: {
      xcb_expose_event_t *expose = (xcb_expose_event_t *)event;
      return expose->window;
    }
    case XCB_DESTROY_NOTIFY: {
      xcb_destroy_notify_event_t *destroy = (xcb_destroy_notify_event_t *)event;
      return destroy->event;
    }
    case XCB_CONFIGURE_NOTIFY: {
      xcb_configure_notify_event_t *configure =
          (xcb_configure_notify_event_t *)event;
      return configure->event;
    }
    case XCB_MAP_NOTIFY: {
      xcb_map_notify_event_t *map = (xcb_map_notify_event_t *)event;
      return map->event;
    }
    case XCB_UNMAP_NOTIFY: {
      xcb_unmap_notify_event_t *unmap = (xcb_unmap_notify_event_t *)event;
      return unmap->event;
    }
    case XCB_FOCUS_IN: {
      xcb_focus_in_event_t *fi = (xcb_focus_in_event_t *)event;
      return fi->event;
    }
    case XCB_FOCUS_OUT: {
      xcb_focus_out_event_t *fo = (xcb_focus_out_event_t *)event;
      return fo->event;
    }
    case XCB_BUTTON_PRESS: {
      xcb_button_press_event_t *bp = (xcb_button_press_event_t *)event;
      return bp->event;
    }
    case XCB_BUTTON_RELEASE: {
      xcb_button_release_event_t *br = (xcb_button_release_event_t *)event;
      return br->event;
    }
    case XCB_MOTION_NOTIFY: {
      xcb_motion_notify_event_t *motion = (xcb_motion_notify_event_t *)event;
      return motion->event;
    }
    case XCB_ENTER_NOTIFY: {
      xcb_enter_notify_event_t *enter = (xcb_enter_notify_event_t *)event;
      return enter->event;
    }
    case XCB_LEAVE_NOTIFY: {
      xcb_leave_notify_event_t *leave = (xcb_leave_notify_event_t *)event;
      return leave->event;
    }
    case XCB_KEY_PRESS: {
      xcb_key_press_event_t *kp = (xcb_key_press_event_t *)event;
      return kp->event;
    }
    case XCB_KEY_RELEASE: {
      xcb_key_release_event_t *kr = (xcb_key_release_event_t *)event;
      return kr->event;
    }
    case XCB_CLIENT_MESSAGE: {
      xcb_client_message_event_t *cm = (xcb_client_message_event_t *)event;
      return cm->window;
    }
    default:
      return std::nullopt;
  }
}

void XcbWindow::DoSetParent(xcb_window_t window) {
  auto real_parent =
      application_->GetFirstXcbScreen()->root;  // init to desktop
  if (parent_ && parent_->xcb_window_) {
    real_parent = *parent_->xcb_window_;
  }
  xcb_reparent_window(application_->GetXcbConnection(), window, real_parent, 0,
                      0);
  // TODO: Maybe restore position?
}

void XcbWindow::DoSetStyleFlags(xcb_window_t window) {
  std::vector<xcb_atom_t> atoms;
  if (style_.Has(WindowStyleFlags::NoCaptionAndBorder)) {
    atoms = {application_->GetXcbAtom_NET_WM_WINDOW_TYPE_UTILITY()};
  } else {
    atoms = {application_->GetXcbAtom_NET_WM_WINDOW_TYPE_NORMAL()};
  }

  xcb_change_property(application_->GetXcbConnection(), XCB_PROP_MODE_REPLACE,
                      window, application_->GetXcbAtom_NET_WM_WINDOW_TYPE(),
                      XCB_ATOM_ATOM, 32, atoms.size(), atoms.data());
}

void XcbWindow::DoSetTitle(xcb_window_t window) {
  for (auto atom : {static_cast<xcb_atom_t>(XCB_ATOM_WM_NAME),
                    application_->GetXcbAtom_NET_WM_NAME()}) {
    xcb_change_property(application_->GetXcbConnection(), XCB_PROP_MODE_REPLACE,
                        window, atom, XCB_ATOM_STRING, 8, title_.size(),
                        title_.data());
  }
}

void XcbWindow::DoSetClientRect(xcb_window_t window, const Rect &rect) {
  auto tree_cookie = xcb_query_tree(application_->GetXcbConnection(), window);
  auto tree_reply = FreeLater(xcb_query_tree_reply(
      application_->GetXcbConnection(), tree_cookie, nullptr));
  auto parent_position = GetXcbWindowPosition(tree_reply->parent);

  std::uint32_t values[4]{
      static_cast<std::uint32_t>(rect.left - parent_position.x),
      static_cast<std::uint32_t>(rect.top - parent_position.y),
      static_cast<std::uint32_t>(rect.width),
      static_cast<std::uint32_t>(rect.height)};
  xcb_configure_window(application_->GetXcbConnection(), window,
                       XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y |
                           XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT,
                       values);
}

void *XcbWindow::XcbGetProperty(xcb_window_t window, xcb_atom_t property,
                                xcb_atom_t type, std::uint32_t offset,
                                std::uint32_t length,
                                std::uint32_t *out_length) {
  auto cookie = xcb_get_property(application_->GetXcbConnection(), false,
                                 window, property, type, offset, length);
  auto reply = FreeLater(
      xcb_get_property_reply(application_->GetXcbConnection(), cookie, NULL));
  if (reply->type == XCB_ATOM_NONE) {
    return nullptr;
  }
  if (out_length != nullptr) {
    *out_length = xcb_get_property_value_length(reply);
  }
  return xcb_get_property_value(reply);
}

std::optional<Thickness> XcbWindow::Get_NET_FRAME_EXTENTS(xcb_window_t window) {
  auto frame_properties = static_cast<std::uint32_t *>(
      XcbGetProperty(window, application_->GetXcbAtom_NET_FRAME_EXTENTS(),
                     XCB_ATOM_CARDINAL, 0, 4));

  if (frame_properties == nullptr) {
    return std::nullopt;
  }

  return Thickness(frame_properties[0], frame_properties[2],
                   frame_properties[1], frame_properties[3]);
}

Point XcbWindow::GetXcbWindowPosition(xcb_window_t window) {
  Point result;

  while (true) {
    auto cookie = xcb_get_geometry(application_->GetXcbConnection(), window);
    auto reply = FreeLater(xcb_get_geometry_reply(
        application_->GetXcbConnection(), cookie, nullptr));
    result.x += reply->x;
    result.y += reply->y;

    auto tree_cookie = xcb_query_tree(application_->GetXcbConnection(), window);
    auto tree_reply = FreeLater(xcb_query_tree_reply(
        application_->GetXcbConnection(), tree_cookie, nullptr));
    window = tree_reply->parent;
    // TODO: Multi-screen offset?
    if (tree_reply->root == window || window == XCB_WINDOW_NONE) {
      break;
    }
  }

  return result;
}

}  // namespace cru::platform::gui::xcb