-
-
Notifications
You must be signed in to change notification settings - Fork 21.1k
/
display_server_x11.cpp
5160 lines (4308 loc) · 154 KB
/
display_server_x11.cpp
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
/*************************************************************************/
/* display_server_x11.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "display_server_x11.h"
#ifdef X11_ENABLED
#include "core/config/project_settings.h"
#include "core/math/math_funcs.h"
#include "core/string/print_string.h"
#include "core/string/ustring.h"
#include "detect_prime_x11.h"
#include "key_mapping_x11.h"
#include "main/main.h"
#include "scene/resources/texture.h"
#if defined(VULKAN_ENABLED)
#include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
#endif
#if defined(GLES3_ENABLED)
#include "drivers/gles3/rasterizer_gles3.h"
#endif
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xinerama.h>
#include <X11/extensions/shape.h>
// ICCCM
#define WM_NormalState 1L // window normal state
#define WM_IconicState 3L // window minimized
// EWMH
#define _NET_WM_STATE_REMOVE 0L // remove/unset property
#define _NET_WM_STATE_ADD 1L // add/set property
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
//stupid linux.h
#ifdef KEY_TAB
#undef KEY_TAB
#endif
#undef CursorShape
#include <X11/XKBlib.h>
// 2.2 is the first release with multitouch
#define XINPUT_CLIENT_VERSION_MAJOR 2
#define XINPUT_CLIENT_VERSION_MINOR 2
#define VALUATOR_ABSX 0
#define VALUATOR_ABSY 1
#define VALUATOR_PRESSURE 2
#define VALUATOR_TILTX 3
#define VALUATOR_TILTY 4
//#define DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
#ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
#define DEBUG_LOG_X11(...) printf(__VA_ARGS__)
#else
#define DEBUG_LOG_X11(...)
#endif
static const double abs_resolution_mult = 10000.0;
static const double abs_resolution_range_mult = 10.0;
// Hints for X11 fullscreen
struct Hints {
unsigned long flags = 0;
unsigned long functions = 0;
unsigned long decorations = 0;
long inputMode = 0;
unsigned long status = 0;
};
static String get_atom_name(Display *p_disp, Atom p_atom) {
char *name = XGetAtomName(p_disp, p_atom);
ERR_FAIL_NULL_V_MSG(name, String(), "Atom is invalid.");
String ret;
ret.parse_utf8(name);
XFree(name);
return ret;
}
bool DisplayServerX11::has_feature(Feature p_feature) const {
switch (p_feature) {
case FEATURE_SUBWINDOWS:
#ifdef TOUCH_ENABLED
case FEATURE_TOUCHSCREEN:
#endif
case FEATURE_MOUSE:
case FEATURE_MOUSE_WARP:
case FEATURE_CLIPBOARD:
case FEATURE_CURSOR_SHAPE:
case FEATURE_CUSTOM_CURSOR_SHAPE:
case FEATURE_IME:
case FEATURE_WINDOW_TRANSPARENCY:
//case FEATURE_HIDPI:
case FEATURE_ICON:
case FEATURE_NATIVE_ICON:
case FEATURE_SWAP_BUFFERS:
#ifdef DBUS_ENABLED
case FEATURE_KEEP_SCREEN_ON:
#endif
case FEATURE_CLIPBOARD_PRIMARY:
case FEATURE_TEXT_TO_SPEECH:
return true;
default: {
}
}
return false;
}
String DisplayServerX11::get_name() const {
return "X11";
}
void DisplayServerX11::_update_real_mouse_position(const WindowData &wd) {
Window root_return, child_return;
int root_x, root_y, win_x, win_y;
unsigned int mask_return;
Bool xquerypointer_result = XQueryPointer(x11_display, wd.x11_window, &root_return, &child_return, &root_x, &root_y,
&win_x, &win_y, &mask_return);
if (xquerypointer_result) {
if (win_x > 0 && win_y > 0 && win_x <= wd.size.width && win_y <= wd.size.height) {
last_mouse_pos.x = win_x;
last_mouse_pos.y = win_y;
last_mouse_pos_valid = true;
Input::get_singleton()->set_mouse_position(last_mouse_pos);
}
}
}
bool DisplayServerX11::_refresh_device_info() {
int event_base, error_base;
print_verbose("XInput: Refreshing devices.");
if (!XQueryExtension(x11_display, "XInputExtension", &xi.opcode, &event_base, &error_base)) {
print_verbose("XInput extension not available. Please upgrade your distribution.");
return false;
}
int xi_major_query = XINPUT_CLIENT_VERSION_MAJOR;
int xi_minor_query = XINPUT_CLIENT_VERSION_MINOR;
if (XIQueryVersion(x11_display, &xi_major_query, &xi_minor_query) != Success) {
print_verbose(vformat("XInput 2 not available (server supports %d.%d).", xi_major_query, xi_minor_query));
xi.opcode = 0;
return false;
}
if (xi_major_query < XINPUT_CLIENT_VERSION_MAJOR || (xi_major_query == XINPUT_CLIENT_VERSION_MAJOR && xi_minor_query < XINPUT_CLIENT_VERSION_MINOR)) {
print_verbose(vformat("XInput %d.%d not available (server supports %d.%d). Touch input unavailable.",
XINPUT_CLIENT_VERSION_MAJOR, XINPUT_CLIENT_VERSION_MINOR, xi_major_query, xi_minor_query));
}
xi.absolute_devices.clear();
xi.touch_devices.clear();
xi.pen_inverted_devices.clear();
int dev_count;
XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count);
for (int i = 0; i < dev_count; i++) {
XIDeviceInfo *dev = &info[i];
if (!dev->enabled) {
continue;
}
if (!(dev->use == XISlavePointer || dev->use == XIFloatingSlave)) {
continue;
}
bool direct_touch = false;
bool absolute_mode = false;
int resolution_x = 0;
int resolution_y = 0;
double abs_x_min = 0;
double abs_x_max = 0;
double abs_y_min = 0;
double abs_y_max = 0;
double pressure_min = 0;
double pressure_max = 0;
double tilt_x_min = 0;
double tilt_x_max = 0;
double tilt_y_min = 0;
double tilt_y_max = 0;
for (int j = 0; j < dev->num_classes; j++) {
#ifdef TOUCH_ENABLED
if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) {
direct_touch = true;
}
#endif
if (dev->classes[j]->type == XIValuatorClass) {
XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)dev->classes[j];
if (class_info->number == VALUATOR_ABSX && class_info->mode == XIModeAbsolute) {
resolution_x = class_info->resolution;
abs_x_min = class_info->min;
abs_x_max = class_info->max;
absolute_mode = true;
} else if (class_info->number == VALUATOR_ABSY && class_info->mode == XIModeAbsolute) {
resolution_y = class_info->resolution;
abs_y_min = class_info->min;
abs_y_max = class_info->max;
absolute_mode = true;
} else if (class_info->number == VALUATOR_PRESSURE && class_info->mode == XIModeAbsolute) {
pressure_min = class_info->min;
pressure_max = class_info->max;
} else if (class_info->number == VALUATOR_TILTX && class_info->mode == XIModeAbsolute) {
tilt_x_min = class_info->min;
tilt_x_max = class_info->max;
} else if (class_info->number == VALUATOR_TILTY && class_info->mode == XIModeAbsolute) {
tilt_y_min = class_info->min;
tilt_y_max = class_info->max;
}
}
}
if (direct_touch) {
xi.touch_devices.push_back(dev->deviceid);
print_verbose("XInput: Using touch device: " + String(dev->name));
}
if (absolute_mode) {
// If no resolution was reported, use the min/max ranges.
if (resolution_x <= 0) {
resolution_x = (abs_x_max - abs_x_min) * abs_resolution_range_mult;
}
if (resolution_y <= 0) {
resolution_y = (abs_y_max - abs_y_min) * abs_resolution_range_mult;
}
xi.absolute_devices[dev->deviceid] = Vector2(abs_resolution_mult / resolution_x, abs_resolution_mult / resolution_y);
print_verbose("XInput: Absolute pointing device: " + String(dev->name));
}
xi.pressure = 0;
xi.pen_pressure_range[dev->deviceid] = Vector2(pressure_min, pressure_max);
xi.pen_tilt_x_range[dev->deviceid] = Vector2(tilt_x_min, tilt_x_max);
xi.pen_tilt_y_range[dev->deviceid] = Vector2(tilt_y_min, tilt_y_max);
xi.pen_inverted_devices[dev->deviceid] = String(dev->name).findn("eraser") > 0;
}
XIFreeDeviceInfo(info);
#ifdef TOUCH_ENABLED
if (!xi.touch_devices.size()) {
print_verbose("XInput: No touch devices found.");
}
#endif
return true;
}
void DisplayServerX11::_flush_mouse_motion() {
// Block events polling while flushing motion events.
MutexLock mutex_lock(events_mutex);
for (uint32_t event_index = 0; event_index < polled_events.size(); ++event_index) {
XEvent &event = polled_events[event_index];
if (XGetEventData(x11_display, &event.xcookie) && event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) {
XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
if (event_data->evtype == XI_RawMotion) {
XFreeEventData(x11_display, &event.xcookie);
polled_events.remove_at(event_index--);
continue;
}
XFreeEventData(x11_display, &event.xcookie);
break;
}
}
xi.relative_motion.x = 0;
xi.relative_motion.y = 0;
}
#ifdef SPEECHD_ENABLED
bool DisplayServerX11::tts_is_speaking() const {
ERR_FAIL_COND_V(!tts, false);
return tts->is_speaking();
}
bool DisplayServerX11::tts_is_paused() const {
ERR_FAIL_COND_V(!tts, false);
return tts->is_paused();
}
TypedArray<Dictionary> DisplayServerX11::tts_get_voices() const {
ERR_FAIL_COND_V(!tts, TypedArray<Dictionary>());
return tts->get_voices();
}
void DisplayServerX11::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
ERR_FAIL_COND(!tts);
tts->speak(p_text, p_voice, p_volume, p_pitch, p_rate, p_utterance_id, p_interrupt);
}
void DisplayServerX11::tts_pause() {
ERR_FAIL_COND(!tts);
tts->pause();
}
void DisplayServerX11::tts_resume() {
ERR_FAIL_COND(!tts);
tts->resume();
}
void DisplayServerX11::tts_stop() {
ERR_FAIL_COND(!tts);
tts->stop();
}
#endif
#ifdef DBUS_ENABLED
bool DisplayServerX11::is_dark_mode_supported() const {
return portal_desktop->is_supported();
}
bool DisplayServerX11::is_dark_mode() const {
switch (portal_desktop->get_appearance_color_scheme()) {
case 1:
// Prefers dark theme.
return true;
case 2:
// Prefers light theme.
return false;
default:
// Preference unknown.
return false;
}
}
#endif
void DisplayServerX11::mouse_set_mode(MouseMode p_mode) {
_THREAD_SAFE_METHOD_
if (p_mode == mouse_mode) {
return;
}
if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
XUngrabPointer(x11_display, CurrentTime);
}
// The only modes that show a cursor are VISIBLE and CONFINED
bool showCursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED);
for (const KeyValue<WindowID, WindowData> &E : windows) {
if (showCursor) {
XDefineCursor(x11_display, E.value.x11_window, cursors[current_cursor]); // show cursor
} else {
XDefineCursor(x11_display, E.value.x11_window, null_cursor); // hide cursor
}
}
mouse_mode = p_mode;
if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
//flush pending motion events
_flush_mouse_motion();
WindowID window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID;
WindowData &window = windows[window_id];
if (XGrabPointer(
x11_display, window.x11_window, True,
ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
GrabModeAsync, GrabModeAsync, window.x11_window, None, CurrentTime) != GrabSuccess) {
ERR_PRINT("NO GRAB");
}
if (mouse_mode == MOUSE_MODE_CAPTURED) {
center.x = window.size.width / 2;
center.y = window.size.height / 2;
XWarpPointer(x11_display, None, window.x11_window,
0, 0, 0, 0, (int)center.x, (int)center.y);
Input::get_singleton()->set_mouse_position(center);
}
} else {
do_mouse_warp = false;
}
XFlush(x11_display);
}
DisplayServerX11::MouseMode DisplayServerX11::mouse_get_mode() const {
return mouse_mode;
}
void DisplayServerX11::warp_mouse(const Point2i &p_position) {
_THREAD_SAFE_METHOD_
if (mouse_mode == MOUSE_MODE_CAPTURED) {
last_mouse_pos = p_position;
} else {
WindowID window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID;
XWarpPointer(x11_display, None, windows[window_id].x11_window,
0, 0, 0, 0, (int)p_position.x, (int)p_position.y);
}
}
Point2i DisplayServerX11::mouse_get_position() const {
int number_of_screens = XScreenCount(x11_display);
for (int i = 0; i < number_of_screens; i++) {
Window root, child;
int root_x, root_y, win_x, win_y;
unsigned int mask;
if (XQueryPointer(x11_display, XRootWindow(x11_display, i), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask)) {
XWindowAttributes root_attrs;
XGetWindowAttributes(x11_display, root, &root_attrs);
return Vector2i(root_attrs.x + root_x, root_attrs.y + root_y);
}
}
return Vector2i();
}
MouseButton DisplayServerX11::mouse_get_button_state() const {
return last_button_state;
}
void DisplayServerX11::clipboard_set(const String &p_text) {
_THREAD_SAFE_METHOD_
{
// The clipboard content can be accessed while polling for events.
MutexLock mutex_lock(events_mutex);
internal_clipboard = p_text;
}
XSetSelectionOwner(x11_display, XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
}
void DisplayServerX11::clipboard_set_primary(const String &p_text) {
_THREAD_SAFE_METHOD_
if (!p_text.is_empty()) {
{
// The clipboard content can be accessed while polling for events.
MutexLock mutex_lock(events_mutex);
internal_clipboard_primary = p_text;
}
XSetSelectionOwner(x11_display, XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
XSetSelectionOwner(x11_display, XInternAtom(x11_display, "PRIMARY", 0), windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
}
}
Bool DisplayServerX11::_predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg) {
if (event->type == SelectionNotify && event->xselection.requestor == *(Window *)arg) {
return True;
} else {
return False;
}
}
Bool DisplayServerX11::_predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg) {
if (event->type == PropertyNotify && event->xproperty.state == PropertyNewValue) {
return True;
} else {
return False;
}
}
String DisplayServerX11::_clipboard_get_impl(Atom p_source, Window x11_window, Atom target) const {
String ret;
Window selection_owner = XGetSelectionOwner(x11_display, p_source);
if (selection_owner == x11_window) {
static const char *target_type = "PRIMARY";
if (p_source != None && get_atom_name(x11_display, p_source) == target_type) {
return internal_clipboard_primary;
} else {
return internal_clipboard;
}
}
if (selection_owner != None) {
// Block events polling while processing selection events.
MutexLock mutex_lock(events_mutex);
Atom selection = XA_PRIMARY;
XConvertSelection(x11_display, p_source, target, selection,
x11_window, CurrentTime);
XFlush(x11_display);
// Blocking wait for predicate to be True and remove the event from the queue.
XEvent event;
XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window);
// Do not get any data, see how much data is there.
Atom type;
int format, result;
unsigned long len, bytes_left, dummy;
unsigned char *data;
XGetWindowProperty(x11_display, x11_window,
selection, // Tricky..
0, 0, // offset - len
0, // Delete 0==FALSE
AnyPropertyType, // flag
&type, // return type
&format, // return format
&len, &bytes_left, // data length
&data);
if (data) {
XFree(data);
}
if (type == XInternAtom(x11_display, "INCR", 0)) {
// Data is going to be received incrementally.
DEBUG_LOG_X11("INCR selection started.\n");
LocalVector<uint8_t> incr_data;
uint32_t data_size = 0;
bool success = false;
// Delete INCR property to notify the owner.
XDeleteProperty(x11_display, x11_window, type);
// Process events from the queue.
bool done = false;
while (!done) {
if (!_wait_for_events()) {
// Error or timeout, abort.
break;
}
// Non-blocking wait for next event and remove it from the queue.
XEvent ev;
while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, nullptr)) {
result = XGetWindowProperty(x11_display, x11_window,
selection, // selection type
0, LONG_MAX, // offset - len
True, // delete property to notify the owner
AnyPropertyType, // flag
&type, // return type
&format, // return format
&len, &bytes_left, // data length
&data);
DEBUG_LOG_X11("PropertyNotify: len=%lu, format=%i\n", len, format);
if (result == Success) {
if (data && (len > 0)) {
uint32_t prev_size = incr_data.size();
if (prev_size == 0) {
// First property contains initial data size.
unsigned long initial_size = *(unsigned long *)data;
incr_data.resize(initial_size);
} else {
// New chunk, resize to be safe and append data.
incr_data.resize(MAX(data_size + len, prev_size));
memcpy(incr_data.ptr() + data_size, data, len);
data_size += len;
}
} else {
// Last chunk, process finished.
done = true;
success = true;
}
} else {
printf("Failed to get selection data chunk.\n");
done = true;
}
if (data) {
XFree(data);
}
if (done) {
break;
}
}
}
if (success && (data_size > 0)) {
ret.parse_utf8((const char *)incr_data.ptr(), data_size);
}
} else if (bytes_left > 0) {
// Data is ready and can be processed all at once.
result = XGetWindowProperty(x11_display, x11_window,
selection, 0, bytes_left, 0,
AnyPropertyType, &type, &format,
&len, &dummy, &data);
if (result == Success) {
ret.parse_utf8((const char *)data);
} else {
printf("Failed to get selection data.\n");
}
if (data) {
XFree(data);
}
}
}
return ret;
}
String DisplayServerX11::_clipboard_get(Atom p_source, Window x11_window) const {
String ret;
Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True);
if (utf8_atom != None) {
ret = _clipboard_get_impl(p_source, x11_window, utf8_atom);
}
if (ret.is_empty()) {
ret = _clipboard_get_impl(p_source, x11_window, XA_STRING);
}
return ret;
}
String DisplayServerX11::clipboard_get() const {
_THREAD_SAFE_METHOD_
String ret;
ret = _clipboard_get(XInternAtom(x11_display, "CLIPBOARD", 0), windows[MAIN_WINDOW_ID].x11_window);
if (ret.is_empty()) {
ret = _clipboard_get(XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window);
}
return ret;
}
String DisplayServerX11::clipboard_get_primary() const {
_THREAD_SAFE_METHOD_
String ret;
ret = _clipboard_get(XInternAtom(x11_display, "PRIMARY", 0), windows[MAIN_WINDOW_ID].x11_window);
if (ret.is_empty()) {
ret = _clipboard_get(XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window);
}
return ret;
}
Bool DisplayServerX11::_predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg) {
if (event->xany.window == *(Window *)arg) {
return (event->type == SelectionRequest) ||
(event->type == SelectionNotify);
} else {
return False;
}
}
void DisplayServerX11::_clipboard_transfer_ownership(Atom p_source, Window x11_window) const {
_THREAD_SAFE_METHOD_
Window selection_owner = XGetSelectionOwner(x11_display, p_source);
if (selection_owner != x11_window) {
return;
}
// Block events polling while processing selection events.
MutexLock mutex_lock(events_mutex);
Atom clipboard_manager = XInternAtom(x11_display, "CLIPBOARD_MANAGER", False);
Atom save_targets = XInternAtom(x11_display, "SAVE_TARGETS", False);
XConvertSelection(x11_display, clipboard_manager, save_targets, None,
x11_window, CurrentTime);
// Process events from the queue.
while (true) {
if (!_wait_for_events()) {
// Error or timeout, abort.
break;
}
// Non-blocking wait for next event and remove it from the queue.
XEvent ev;
while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_save_targets, (XPointer)&x11_window)) {
switch (ev.type) {
case SelectionRequest:
_handle_selection_request_event(&(ev.xselectionrequest));
break;
case SelectionNotify: {
if (ev.xselection.target == save_targets) {
// Once SelectionNotify is received, we're done whether it succeeded or not.
return;
}
break;
}
}
}
}
}
int DisplayServerX11::get_screen_count() const {
_THREAD_SAFE_METHOD_
int count = 0;
// Using Xinerama Extension
int event_base, error_base;
if (XineramaQueryExtension(x11_display, &event_base, &error_base)) {
XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
XFree(xsi);
} else {
count = XScreenCount(x11_display);
}
return count;
}
Rect2i DisplayServerX11::_screen_get_rect(int p_screen) const {
Rect2i rect(0, 0, 0, 0);
if (p_screen == SCREEN_OF_MAIN_WINDOW) {
p_screen = window_get_current_screen();
}
ERR_FAIL_COND_V(p_screen < 0, rect);
// Using Xinerama Extension.
int event_base, error_base;
if (XineramaQueryExtension(x11_display, &event_base, &error_base)) {
int count;
XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
// Check if screen is valid.
if (p_screen < count) {
rect.position.x = xsi[p_screen].x_org;
rect.position.y = xsi[p_screen].y_org;
rect.size.width = xsi[p_screen].width;
rect.size.height = xsi[p_screen].height;
} else {
ERR_PRINT("Invalid screen index: " + itos(p_screen) + "(count: " + itos(count) + ").");
}
if (xsi) {
XFree(xsi);
}
} else {
int count = XScreenCount(x11_display);
if (p_screen < count) {
Window root = XRootWindow(x11_display, p_screen);
XWindowAttributes xwa;
XGetWindowAttributes(x11_display, root, &xwa);
rect.position.x = xwa.x;
rect.position.y = xwa.y;
rect.size.width = xwa.width;
rect.size.height = xwa.height;
} else {
ERR_PRINT("Invalid screen index: " + itos(p_screen) + "(count: " + itos(count) + ").");
}
}
return rect;
}
Point2i DisplayServerX11::screen_get_position(int p_screen) const {
_THREAD_SAFE_METHOD_
return _screen_get_rect(p_screen).position;
}
Size2i DisplayServerX11::screen_get_size(int p_screen) const {
_THREAD_SAFE_METHOD_
return _screen_get_rect(p_screen).size;
}
bool g_bad_window = false;
int bad_window_error_handler(Display *display, XErrorEvent *error) {
if (error->error_code == BadWindow) {
g_bad_window = true;
} else {
ERR_PRINT("Unhandled XServer error code: " + itos(error->error_code));
}
return 0;
}
Rect2i DisplayServerX11::screen_get_usable_rect(int p_screen) const {
_THREAD_SAFE_METHOD_
if (p_screen == SCREEN_OF_MAIN_WINDOW) {
p_screen = window_get_current_screen();
}
int screen_count = get_screen_count();
// Check if screen is valid.
ERR_FAIL_INDEX_V(p_screen, screen_count, Rect2i(0, 0, 0, 0));
bool is_multiscreen = screen_count > 1;
// Use full monitor size as fallback.
Rect2i rect = _screen_get_rect(p_screen);
// There's generally only one screen reported by xlib even in multi-screen setup,
// in this case it's just one virtual screen composed of all physical monitors.
int x11_screen_count = ScreenCount(x11_display);
Window x11_window = RootWindow(x11_display, p_screen < x11_screen_count ? p_screen : 0);
Atom type;
int format = 0;
unsigned long remaining = 0;
// Find active desktop for the root window.
unsigned int desktop_index = 0;
Atom desktop_prop = XInternAtom(x11_display, "_NET_CURRENT_DESKTOP", True);
if (desktop_prop != None) {
unsigned long desktop_len = 0;
unsigned char *desktop_data = nullptr;
if (XGetWindowProperty(x11_display, x11_window, desktop_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &desktop_len, &remaining, &desktop_data) == Success) {
if ((format == 32) && (desktop_len > 0) && desktop_data) {
desktop_index = (unsigned int)desktop_data[0];
}
if (desktop_data) {
XFree(desktop_data);
}
}
}
bool use_simple_method = true;
// First check for GTK work area, which is more accurate for multi-screen setup.
if (is_multiscreen) {
// Use already calculated work area when available.
Atom gtk_workareas_prop = XInternAtom(x11_display, "_GTK_WORKAREAS", False);
if (gtk_workareas_prop != None) {
char gtk_workarea_prop_name[32];
snprintf(gtk_workarea_prop_name, 32, "_GTK_WORKAREAS_D%d", desktop_index);
Atom gtk_workarea_prop = XInternAtom(x11_display, gtk_workarea_prop_name, True);
if (gtk_workarea_prop != None) {
unsigned long workarea_len = 0;
unsigned char *workarea_data = nullptr;
if (XGetWindowProperty(x11_display, x11_window, gtk_workarea_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &workarea_len, &remaining, &workarea_data) == Success) {
if ((format == 32) && (workarea_len % 4 == 0) && workarea_data) {
long *rect_data = (long *)workarea_data;
for (uint32_t data_offset = 0; data_offset < workarea_len; data_offset += 4) {
Rect2i workarea_rect;
workarea_rect.position.x = rect_data[data_offset];
workarea_rect.position.y = rect_data[data_offset + 1];
workarea_rect.size.x = rect_data[data_offset + 2];
workarea_rect.size.y = rect_data[data_offset + 3];
// Intersect with actual monitor size to find the correct area,
// because areas are not in the same order as screens from Xinerama.
if (rect.grow(-1).intersects(workarea_rect)) {
rect = rect.intersection(workarea_rect);
XFree(workarea_data);
return rect;
}
}
}
}
if (workarea_data) {
XFree(workarea_data);
}
}
}
// Fallback to calculating work area by hand from struts.
Atom client_list_prop = XInternAtom(x11_display, "_NET_CLIENT_LIST", True);
if (client_list_prop != None) {
unsigned long clients_len = 0;
unsigned char *clients_data = nullptr;
if (XGetWindowProperty(x11_display, x11_window, client_list_prop, 0, LONG_MAX, False, XA_WINDOW, &type, &format, &clients_len, &remaining, &clients_data) == Success) {
if ((format == 32) && (clients_len > 0) && clients_data) {
Window *windows_data = (Window *)clients_data;
Rect2i desktop_rect;
bool desktop_valid = false;
// Get full desktop size.
{
Atom desktop_geometry_prop = XInternAtom(x11_display, "_NET_DESKTOP_GEOMETRY", True);
if (desktop_geometry_prop != None) {
unsigned long geom_len = 0;
unsigned char *geom_data = nullptr;
if (XGetWindowProperty(x11_display, x11_window, desktop_geometry_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &geom_len, &remaining, &geom_data) == Success) {
if ((format == 32) && (geom_len >= 2) && geom_data) {
desktop_valid = true;
long *size_data = (long *)geom_data;
desktop_rect.size.x = size_data[0];
desktop_rect.size.y = size_data[1];
}
}
if (geom_data) {
XFree(geom_data);
}
}
}
// Get full desktop position.
if (desktop_valid) {
Atom desktop_viewport_prop = XInternAtom(x11_display, "_NET_DESKTOP_VIEWPORT", True);
if (desktop_viewport_prop != None) {
unsigned long viewport_len = 0;
unsigned char *viewport_data = nullptr;
if (XGetWindowProperty(x11_display, x11_window, desktop_viewport_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &viewport_len, &remaining, &viewport_data) == Success) {
if ((format == 32) && (viewport_len >= 2) && viewport_data) {
desktop_valid = true;
long *pos_data = (long *)viewport_data;
desktop_rect.position.x = pos_data[0];
desktop_rect.position.y = pos_data[1];
}
}
if (viewport_data) {
XFree(viewport_data);
}
}
}
if (desktop_valid) {
use_simple_method = false;
// Handle bad window errors silently because there's no other way to check
// that one of the windows has been destroyed in the meantime.
int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&bad_window_error_handler);
for (unsigned long win_index = 0; win_index < clients_len; ++win_index) {
g_bad_window = false;
// Remove strut size from desktop size to get a more accurate result.
bool strut_found = false;
unsigned long strut_len = 0;
unsigned char *strut_data = nullptr;
Atom strut_partial_prop = XInternAtom(x11_display, "_NET_WM_STRUT_PARTIAL", True);
if (strut_partial_prop != None) {
if (XGetWindowProperty(x11_display, windows_data[win_index], strut_partial_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &strut_len, &remaining, &strut_data) == Success) {
strut_found = true;
}
}
// Fallback to older strut property.
if (!g_bad_window && !strut_found) {
Atom strut_prop = XInternAtom(x11_display, "_NET_WM_STRUT", True);
if (strut_prop != None) {
if (XGetWindowProperty(x11_display, windows_data[win_index], strut_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &strut_len, &remaining, &strut_data) == Success) {
strut_found = true;
}
}
}
if (!g_bad_window && strut_found && (format == 32) && (strut_len >= 4) && strut_data) {
long *struts = (long *)strut_data;
long left = struts[0];
long right = struts[1];
long top = struts[2];
long bottom = struts[3];
long left_start_y, left_end_y, right_start_y, right_end_y;
long top_start_x, top_end_x, bottom_start_x, bottom_end_x;
if (strut_len >= 12) {
left_start_y = struts[4];
left_end_y = struts[5];
right_start_y = struts[6];
right_end_y = struts[7];
top_start_x = struts[8];
top_end_x = struts[9];
bottom_start_x = struts[10];
bottom_end_x = struts[11];