/
WindowImplX11.cpp
1271 lines (1109 loc) · 45.6 KB
/
WindowImplX11.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
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/WindowStyle.hpp> // important to be included first (conflict with None)
#include <SFML/Window/Unix/WindowImplX11.hpp>
#include <SFML/Window/Unix/Display.hpp>
#include <SFML/System/Utf.hpp>
#include <SFML/System/Err.hpp>
#include <xcb/xcb_atom.h>
#include <xcb/xcb_icccm.h>
#include <xcb/xcb_image.h>
#include <xcb/xcb_util.h>
#include <xcb/randr.h>
#include <unistd.h>
#include <libgen.h>
#include <cstring>
#include <sstream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
#include <iostream>
#ifdef SFML_OPENGL_ES
#include <SFML/Window/EglContext.hpp>
typedef sf::priv::EglContext ContextType;
#else
#include <SFML/Window/Unix/GlxContext.hpp>
typedef sf::priv::GlxContext ContextType;
#endif
////////////////////////////////////////////////////////////
// Private data
////////////////////////////////////////////////////////////
namespace
{
sf::priv::WindowImplX11* fullscreenWindow = NULL;
std::vector<sf::priv::WindowImplX11*> allWindows;
unsigned long eventMask = FocusChangeMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask |
PointerMotionMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask |
EnterWindowMask | LeaveWindowMask;
// Find the name of the current executable
void findExecutableName(char* buffer, std::size_t bufferSize)
{
//Default fallback name
const char* executableName = "sfml";
std::size_t length = readlink("/proc/self/exe", buffer, bufferSize);
if ((length > 0) && (length < bufferSize))
{
// Remove the path to keep the executable name only
buffer[length] = '\0';
executableName = basename(buffer);
}
std::memmove(buffer, executableName, std::strlen(executableName) + 1);
}
}
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
WindowImplX11::WindowImplX11(WindowHandle handle) :
m_window (0),
m_inputMethod (NULL),
m_inputContext(NULL),
m_isExternal (true),
m_atomClose (0),
m_oldVideoMode(-1),
m_hiddenCursor(0),
m_keyRepeat (true),
m_previousSize(-1, -1),
m_useSizeHints(false)
{
// Open a connection with the X server
m_display = OpenDisplay();
XSetEventQueueOwner(m_display, XCBOwnsEventQueue);
m_connection = XGetXCBConnection(m_display);
if (!m_connection)
{
err() << "Failed cast Display object to an XCB connection object" << std::endl;
return;
}
// Get connection info.
const xcb_setup_t* setup = xcb_get_setup(m_connection);
xcb_screen_iterator_t screenIter = xcb_setup_roots_iterator(setup);
m_screen = screenIter.data;
// Save the window handle
m_window = handle;
if (m_window)
{
// Make sure the window is listening to all the required events
const uint32_t value_list[] = {static_cast<uint32_t>(eventMask)};
xcb_change_window_attributes(m_connection,
m_window,
XCB_CW_EVENT_MASK,
value_list);
// Do some common initializations
initialize();
}
}
////////////////////////////////////////////////////////////
WindowImplX11::WindowImplX11(VideoMode mode, const String& title, unsigned long style, const ContextSettings& /*settings*/) :
m_window (0),
m_inputMethod (NULL),
m_inputContext(NULL),
m_isExternal (false),
m_atomClose (0),
m_oldVideoMode(-1),
m_hiddenCursor(0),
m_keyRepeat (true),
m_previousSize(-1, -1),
m_useSizeHints(false)
{
// Open a connection with the X server
m_display = OpenDisplay();
XSetEventQueueOwner(m_display, XCBOwnsEventQueue);
m_connection = XGetXCBConnection(m_display);
if (!m_connection)
{
err() << "Failed cast Display object to an XCB connection object" << std::endl;
return;
}
// Get connection info.
const xcb_setup_t* setup = xcb_get_setup(m_connection);
xcb_screen_iterator_t screenIter = xcb_setup_roots_iterator(setup);
m_screen = screenIter.data;
// Compute position and size
int left, top;
bool fullscreen = (style & Style::Fullscreen) != 0;
if (!fullscreen)
{
left = (m_screen->width_in_pixels - mode.width) / 2;
top = (m_screen->height_in_pixels - mode.height) / 2;
}
else
{
left = 0;
top = 0;
}
int width = mode.width;
int height = mode.height;
// Switch to fullscreen if necessary
if (fullscreen)
switchToFullscreen(mode);
// Define the window attributes
const uint32_t value_list[] = {fullscreen, static_cast<uint32_t>(eventMask)};
// Create the window
m_window = xcb_generate_id(m_connection);
xcb_void_cookie_t cookie = xcb_create_window_checked(
m_connection,
XCB_COPY_FROM_PARENT,
m_window,
m_screen->root,
left, top,
width, height,
0,
XCB_WINDOW_CLASS_INPUT_OUTPUT,
XCB_COPY_FROM_PARENT,
XCB_CW_EVENT_MASK | XCB_CW_OVERRIDE_REDIRECT,
value_list);
xcb_generic_error_t* errptr = xcb_request_check(m_connection, cookie);
bool createWindowFailed = (errptr != NULL);
free(errptr);
if (createWindowFailed)
{
err() << "Failed to create window" << std::endl;
return;
}
// Set the window's name
setTitle(title);
// Set the window's style (tell the windows manager to change our window's decorations and functions according to the requested style)
if (!fullscreen)
{
static const std::string MOTIF_WM_HINTS = "_MOTIF_WM_HINTS";
xcb_intern_atom_cookie_t hintsAtomRequest = xcb_intern_atom(
m_connection,
0,
MOTIF_WM_HINTS.size(),
MOTIF_WM_HINTS.c_str()
);
xcb_intern_atom_reply_t* hintsAtomReply = xcb_intern_atom_reply(
m_connection,
hintsAtomRequest,
NULL
);
if (hintsAtomReply)
{
static const unsigned long MWM_HINTS_FUNCTIONS = 1 << 0;
static const unsigned long MWM_HINTS_DECORATIONS = 1 << 1;
//static const unsigned long MWM_DECOR_ALL = 1 << 0;
static const unsigned long MWM_DECOR_BORDER = 1 << 1;
static const unsigned long MWM_DECOR_RESIZEH = 1 << 2;
static const unsigned long MWM_DECOR_TITLE = 1 << 3;
static const unsigned long MWM_DECOR_MENU = 1 << 4;
static const unsigned long MWM_DECOR_MINIMIZE = 1 << 5;
static const unsigned long MWM_DECOR_MAXIMIZE = 1 << 6;
//static const unsigned long MWM_FUNC_ALL = 1 << 0;
static const unsigned long MWM_FUNC_RESIZE = 1 << 1;
static const unsigned long MWM_FUNC_MOVE = 1 << 2;
static const unsigned long MWM_FUNC_MINIMIZE = 1 << 3;
static const unsigned long MWM_FUNC_MAXIMIZE = 1 << 4;
static const unsigned long MWM_FUNC_CLOSE = 1 << 5;
struct WMHints
{
uint32_t flags;
uint32_t functions;
uint32_t decorations;
int32_t inputMode;
uint32_t state;
};
WMHints hints;
hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
hints.decorations = 0;
hints.functions = 0;
if (style & Style::Titlebar)
{
hints.decorations |= MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MINIMIZE | MWM_DECOR_MENU;
hints.functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE;
}
if (style & Style::Resize)
{
hints.decorations |= MWM_DECOR_MAXIMIZE | MWM_DECOR_RESIZEH;
hints.functions |= MWM_FUNC_MAXIMIZE | MWM_FUNC_RESIZE;
}
if (style & Style::Close)
{
hints.decorations |= 0;
hints.functions |= MWM_FUNC_CLOSE;
}
const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&hints);
xcb_change_property(m_connection, XCB_PROP_MODE_REPLACE, m_window,
hintsAtomReply->atom, XCB_ATOM_WM_HINTS, 32, 5, ptr);
free(hintsAtomReply);
}
// This is a hack to force some windows managers to disable resizing
if (!(style & Style::Resize))
{
m_useSizeHints = true;
xcb_size_hints_t sizeHints;
sizeHints.flags = XCB_ICCCM_SIZE_HINT_P_MIN_SIZE | XCB_ICCCM_SIZE_HINT_P_MAX_SIZE;
sizeHints.min_width = sizeHints.max_width = width;
sizeHints.min_height = sizeHints.max_height = height;
xcb_icccm_set_wm_normal_hints(m_connection, m_window, &sizeHints);
}
}
// Set the window's WM class (this can be used by window managers)
char windowClass[512];
findExecutableName(windowClass, sizeof(windowClass));
xcb_icccm_set_wm_class_checked(m_connection, m_window, std::strlen(windowClass), windowClass);
// Do some common initializations
initialize();
// In fullscreen mode, we must grab keyboard and mouse inputs
if (fullscreen)
{
xcb_grab_pointer(m_connection, True, m_window, 0, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, m_window, XCB_NONE, XCB_CURRENT_TIME);
xcb_grab_keyboard(m_connection, True, m_window, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
}
}
////////////////////////////////////////////////////////////
WindowImplX11::~WindowImplX11()
{
// Cleanup graphical resources
cleanup();
// Destroy the cursor
if (m_hiddenCursor)
xcb_free_cursor(m_connection, m_hiddenCursor);
// Destroy the input context
if (m_inputContext)
XDestroyIC(m_inputContext);
// Destroy the window
if (m_window && !m_isExternal)
{
xcb_destroy_window(m_connection, m_window);
xcb_flush(m_connection);
}
// Close the input method
if (m_inputMethod)
XCloseIM(m_inputMethod);
// Close the connection with the X server
CloseDisplay(m_display);
// Remove this window from the global list of windows (required for focus request)
allWindows.erase(std::find(allWindows.begin(), allWindows.end(), this));
}
////////////////////////////////////////////////////////////
WindowHandle WindowImplX11::getSystemHandle() const
{
return m_window;
}
////////////////////////////////////////////////////////////
void WindowImplX11::processEvents()
{
// Key repeat workaround: If key repeat is enabled, XCB will spawn two
// events for each repeat interval: key release and key press. Both have
// the same timestamp and key code. We are holding back the release event
// to check for the matching key press event and if so, discard the release
// event.
xcb_generic_event_t* event = NULL;
xcb_key_release_event_t* lastKeyReleaseEvent = NULL;
uint8_t eventType = 0;
while((event = xcb_poll_for_event(m_connection)))
{
eventType = event->response_type & ~0x80;
// Key was pressed and one has been released prior to that.
if (eventType == XCB_KEY_PRESS && lastKeyReleaseEvent)
{
// If the key press event matches the held back key release event,
// then we have a key repeat and discard the held back release
// event.
if (lastKeyReleaseEvent->time == reinterpret_cast<xcb_key_press_event_t*>(event)->time &&
lastKeyReleaseEvent->detail == reinterpret_cast<xcb_key_press_event_t*>(event)->detail)
{
free(lastKeyReleaseEvent);
lastKeyReleaseEvent = NULL;
}
}
// If there's still a key release event held back, process it now.
if (lastKeyReleaseEvent)
{
processEvent(reinterpret_cast<xcb_generic_event_t*>(lastKeyReleaseEvent));
free(lastKeyReleaseEvent);
lastKeyReleaseEvent = NULL;
}
if (eventType == XCB_KEY_RELEASE)
{
// Remember this key release event.
lastKeyReleaseEvent = reinterpret_cast<xcb_key_release_event_t*>(event);
event = NULL; // For safety reasons.
}
else
{
processEvent(event);
free(event);
}
}
// Process any held back release event.
if (lastKeyReleaseEvent)
{
processEvent(reinterpret_cast<xcb_generic_event_t*>(lastKeyReleaseEvent));
free(lastKeyReleaseEvent);
lastKeyReleaseEvent = NULL;
}
}
////////////////////////////////////////////////////////////
Vector2i WindowImplX11::getPosition() const
{
::Window topLevelWindow = m_window;
::Window nextWindow = topLevelWindow;
xcb_query_tree_cookie_t treeCookie;
xcb_query_tree_reply_t* treeReply = NULL;
// Get "top level" window, i.e. the window with the root window as its parent.
while (nextWindow != m_screen->root)
{
topLevelWindow = nextWindow;
treeCookie = xcb_query_tree(m_connection, topLevelWindow);
treeReply = xcb_query_tree_reply(m_connection, treeCookie, NULL);
nextWindow = treeReply->parent;
free(treeReply);
}
xcb_get_geometry_cookie_t geometryCookie = xcb_get_geometry(m_connection, topLevelWindow);
xcb_get_geometry_reply_t* geometryReply = xcb_get_geometry_reply(m_connection, geometryCookie, NULL);
sf::Vector2i result(geometryReply->x, geometryReply->y);
free(geometryReply);
return result;
}
////////////////////////////////////////////////////////////
void WindowImplX11::setPosition(const Vector2i& position)
{
uint32_t values[] = {static_cast<uint32_t>(position.x), static_cast<uint32_t>(position.y)};
xcb_configure_window(m_connection, m_window,
XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y,
values);
xcb_flush(m_connection);
}
////////////////////////////////////////////////////////////
Vector2u WindowImplX11::getSize() const
{
xcb_get_geometry_reply_t* reply = xcb_get_geometry_reply(m_connection, xcb_get_geometry(m_connection, m_window), NULL);
Vector2u result(reply->width, reply->height);
free(reply);
return result;
}
////////////////////////////////////////////////////////////
void WindowImplX11::setSize(const Vector2u& size)
{
// If resizing is disable for the window we have to update the size hints (required by some window managers).
if( m_useSizeHints ) {
xcb_size_hints_t sizeHints;
sizeHints.flags = XCB_ICCCM_SIZE_HINT_P_MIN_SIZE | XCB_ICCCM_SIZE_HINT_P_MAX_SIZE;
sizeHints.min_width = sizeHints.max_width = size.x;
sizeHints.min_height = sizeHints.max_height = size.y;
xcb_icccm_set_wm_normal_hints(m_connection, m_window, &sizeHints);
}
uint32_t values[] = {size.x, size.y};
xcb_configure_window(m_connection, m_window,
XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT,
values);
xcb_flush(m_connection);
}
////////////////////////////////////////////////////////////
void WindowImplX11::setTitle(const String& title)
{
// XCB takes UTF-8-encoded strings.
std::basic_string<sf::Uint8> utf8String;
sf::Utf<32>::toUtf8(
title.begin(), title.end(),
std::back_inserter( utf8String )
);
xcb_change_property(m_connection, XCB_PROP_MODE_REPLACE, m_window,
XCB_ATOM_WM_NAME, XCB_ATOM_STRING,
8, utf8String.length(), utf8String.c_str());
xcb_flush(m_connection);
}
////////////////////////////////////////////////////////////
void WindowImplX11::setIcon(unsigned int width, unsigned int height, const Uint8* pixels)
{
// X11 wants BGRA pixels: swap red and blue channels
Uint8 iconPixels[width * height * 4];
for (std::size_t i = 0; i < width * height; ++i)
{
iconPixels[i * 4 + 0] = pixels[i * 4 + 2];
iconPixels[i * 4 + 1] = pixels[i * 4 + 1];
iconPixels[i * 4 + 2] = pixels[i * 4 + 0];
iconPixels[i * 4 + 3] = pixels[i * 4 + 3];
}
// Create the icon pixmap
xcb_pixmap_t iconPixmap = xcb_generate_id(m_connection);
xcb_create_pixmap(m_connection, m_screen->root_depth, iconPixmap, m_screen->root,
width, height);
xcb_gcontext_t iconGC = xcb_generate_id(m_connection);
xcb_create_gc(m_connection, iconGC, iconPixmap, 0, NULL);
xcb_void_cookie_t cookie = xcb_put_image_checked(
m_connection, XCB_IMAGE_FORMAT_Z_PIXMAP, iconPixmap, iconGC,
width, height, 0, 0, 0, m_screen->root_depth, sizeof(iconPixels), iconPixels);
xcb_free_gc(m_connection, iconGC);
xcb_generic_error_t* errptr = xcb_request_check(m_connection, cookie);
if (errptr)
{
err() << "Failed to set the window's icon: Error code " << static_cast<int>(errptr->error_code) << std::endl;
free(errptr);
return;
}
// Create the mask pixmap (must have 1 bit depth)
std::size_t pitch = (width + 7) / 8;
static std::vector<Uint8> maskPixels(pitch * height, 0);
for (std::size_t j = 0; j < height; ++j)
{
for (std::size_t i = 0; i < pitch; ++i)
{
for (std::size_t k = 0; k < 8; ++k)
{
if (i * 8 + k < width)
{
Uint8 opacity = (pixels[(i * 8 + k + j * width) * 4 + 3] > 0) ? 1 : 0;
maskPixels[i + j * pitch] |= (opacity << k);
}
}
}
}
xcb_pixmap_t maskPixmap = xcb_create_pixmap_from_bitmap_data(m_connection, m_window, (Uint8*)&maskPixels[0], width, height, 1, 0, 1, NULL);
// Send our new icon to the window through the WMHints
xcb_icccm_wm_hints_t hints;
hints.flags = XCB_ICCCM_WM_HINT_ICON_PIXMAP | XCB_ICCCM_WM_HINT_ICON_MASK;
hints.icon_pixmap = iconPixmap;
hints.icon_mask = maskPixmap;
xcb_icccm_set_wm_hints(m_connection, m_window, &hints);
xcb_flush(m_connection);
}
////////////////////////////////////////////////////////////
void WindowImplX11::setVisible(bool visible)
{
if (visible)
xcb_map_window(m_connection, m_window);
else
xcb_unmap_window(m_connection, m_window);
xcb_flush(m_connection);
}
////////////////////////////////////////////////////////////
void WindowImplX11::setMouseCursorVisible(bool visible)
{
const uint32_t values = visible ? XCB_NONE : m_hiddenCursor;
xcb_change_window_attributes(m_connection, m_window, XCB_CW_CURSOR, &values);
xcb_flush(m_connection);
}
////////////////////////////////////////////////////////////
void WindowImplX11::setKeyRepeatEnabled(bool enabled)
{
m_keyRepeat = enabled;
}
////////////////////////////////////////////////////////////
void WindowImplX11::requestFocus()
{
// Focus is only stolen among SFML windows, not between applications
// Check the global list of windows to find out whether an SFML window has the focus
// Note: can't handle console and other non-SFML windows belonging to the application.
bool sfmlWindowFocused = false;
for (std::vector<WindowImplX11*>::iterator itr = allWindows.begin(); itr != allWindows.end(); ++itr)
{
if ((*itr)->hasFocus())
{
sfmlWindowFocused = true;
break;
}
}
// Check if window is viewable (not on other desktop, ...)
// TODO: Check also if minimized
xcb_get_window_attributes_cookie_t attribCookie = xcb_get_window_attributes(m_connection, m_window);
xcb_get_window_attributes_reply_t* attributes = xcb_get_window_attributes_reply(m_connection,
attribCookie,
NULL);
if (!attributes)
{
sf::err() << "Failed to check if window is viewable while requesting focus" << std::endl;
return; // error getting attribute
}
bool windowViewable = (attributes->map_state == XCB_MAP_STATE_VIEWABLE);
free(attributes);
if (sfmlWindowFocused && windowViewable)
{
// Another SFML window of this application has the focus and the current window is viewable:
// steal focus (i.e. bring window to the front and give it input focus)
xcb_set_input_focus(m_connection, XCB_INPUT_FOCUS_POINTER_ROOT, m_window, XCB_CURRENT_TIME);
const uint32_t values[] = {XCB_STACK_MODE_ABOVE};
xcb_configure_window(m_connection, m_window, XCB_CONFIG_WINDOW_STACK_MODE, values);
}
else
{
// Get current WM hints.
xcb_get_property_cookie_t hintsCookie = xcb_icccm_get_wm_hints_unchecked(m_connection, m_window);
xcb_icccm_wm_hints_t hints;
xcb_icccm_get_wm_hints_reply(m_connection, hintsCookie, &hints, NULL);
// Even if no hints were returned, we can simply set the proper flags we need and go on. This is
// different from Xlib where XAllocWMHints() has to be called.
hints.flags |= XCB_ICCCM_WM_HINT_X_URGENCY;
xcb_icccm_set_wm_hints_checked(m_connection, m_window, &hints);
}
}
////////////////////////////////////////////////////////////
bool WindowImplX11::hasFocus() const
{
xcb_get_input_focus_cookie_t cookie = xcb_get_input_focus_unchecked(m_connection);
xcb_get_input_focus_reply_t* reply = xcb_get_input_focus_reply(m_connection, cookie, NULL);
bool focussed = (reply->focus == m_window);
free(reply);
return focussed;
}
////////////////////////////////////////////////////////////
void WindowImplX11::switchToFullscreen(const VideoMode& mode)
{
// Check if the XRandR extension is present
xcb_query_extension_reply_t* randr_ext =
xcb_query_extension_reply(m_connection, xcb_query_extension(m_connection, 5, "RANDR"), NULL);
if (randr_ext->present)
{
// Get the current configuration
xcb_generic_error_t* errors;
xcb_randr_get_screen_info_reply_t* config =
xcb_randr_get_screen_info_reply(m_connection,
xcb_randr_get_screen_info(m_connection, m_screen->root),
&errors);
if (! errors)
{
// Save the current video mode before we switch to fullscreen
m_oldVideoMode = config->sizeID;
// Get the available screen sizes
xcb_randr_screen_size_t* sizes = xcb_randr_get_screen_info_sizes(config);
if (sizes && (config->nSizes > 0))
{
// Search a matching size
for (int i = 0; i < config->nSizes; ++i)
{
if ((sizes[i].width == static_cast<int>(mode.width)) && (sizes[i].height == static_cast<int>(mode.height)))
{
// Switch to fullscreen mode
xcb_randr_set_screen_config(m_connection,
m_screen->root,
config->timestamp,
config->config_timestamp,
i, config->rotation, config->rate);
// Set "this" as the current fullscreen window
fullscreenWindow = this;
break;
}
}
}
}
else
{
// Failed to get the screen configuration
err() << "Failed to get the current screen configuration for fullscreen mode, switching to window mode" << std::endl;
}
free(errors);
free(config);
}
else
{
// XRandr extension is not supported: we cannot use fullscreen mode
err() << "Fullscreen is not supported, switching to window mode" << std::endl;
}
free(randr_ext);
}
////////////////////////////////////////////////////////////
void WindowImplX11::initialize()
{
// Get the atoms for registering the close event
static const std::string WM_DELETE_WINDOW_NAME = "WM_DELETE_WINDOW";
xcb_intern_atom_cookie_t deleteWindowAtomRequest = xcb_intern_atom(
m_connection,
0,
WM_DELETE_WINDOW_NAME.size(),
WM_DELETE_WINDOW_NAME.c_str()
);
xcb_intern_atom_reply_t* deleteWindowAtomReply = xcb_intern_atom_reply(
m_connection,
deleteWindowAtomRequest,
NULL
);
static const std::string WM_PROTOCOLS_NAME = "WM_PROTOCOLS";
xcb_intern_atom_cookie_t protocolsAtomRequest = xcb_intern_atom(
m_connection,
0,
WM_PROTOCOLS_NAME.size(),
WM_PROTOCOLS_NAME.c_str()
);
xcb_intern_atom_reply_t* protocolsAtomReply = xcb_intern_atom_reply(
m_connection,
protocolsAtomRequest,
NULL
);
if (protocolsAtomReply && deleteWindowAtomReply)
{
xcb_icccm_set_wm_protocols(
m_connection,
m_window,
protocolsAtomReply->atom,
1,
&deleteWindowAtomReply->atom
);
m_atomClose = deleteWindowAtomReply->atom;
}
else
{
// Should not happen, but better safe than sorry.
std::cerr << "Failed to request WM_PROTOCOLS/WM_DELETE_WINDOW_NAME atoms." << std::endl;
}
free(protocolsAtomReply);
free(deleteWindowAtomReply);
// Create the input context
m_inputMethod = XOpenIM(m_display, NULL, NULL, NULL);
if (m_inputMethod)
{
m_inputContext = XCreateIC(m_inputMethod,
XNClientWindow, m_window,
XNFocusWindow, m_window,
XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
(void*)NULL);
}
else
{
m_inputContext = NULL;
}
if (!m_inputContext)
err() << "Failed to create input context for window -- TextEntered event won't be able to return unicode" << std::endl;
// Show the window
xcb_map_window(m_connection, m_window);
xcb_flush(m_connection);
// Create the hidden cursor
createHiddenCursor();
// Flush the commands queue
xcb_flush(m_connection);
// Add this window to the global list of windows (required for focus request)
allWindows.push_back(this);
}
////////////////////////////////////////////////////////////
void WindowImplX11::createHiddenCursor()
{
xcb_pixmap_t cursorPixmap = xcb_generate_id(m_connection);
m_hiddenCursor = xcb_generate_id(m_connection);
// Create the cursor's pixmap (1x1 pixels)
xcb_create_pixmap(m_connection, 1, cursorPixmap, m_window, 1, 1);
// Create the cursor, using the pixmap as both the shape and the mask of the cursor
xcb_create_cursor(m_connection, m_hiddenCursor, cursorPixmap, cursorPixmap,
0, 0, 0, // Fore color
0, 0, 0, // Back color
0, 0);
// We don't need the pixmap any longer, free it
xcb_free_pixmap(m_connection, cursorPixmap);
}
////////////////////////////////////////////////////////////
void WindowImplX11::cleanup()
{
// Restore the previous video mode (in case we were running in fullscreen)
if (fullscreenWindow == this)
{
// Get current screen info
xcb_generic_error_t* errors;
xcb_randr_get_screen_info_reply_t* config = xcb_randr_get_screen_info_reply(
m_connection, xcb_randr_get_screen_info(m_connection, m_screen->root), &errors);
if (!errors)
{
// Reset the video mode
xcb_randr_set_screen_config(m_connection,
m_screen->root,
CurrentTime,
config->config_timestamp,
m_oldVideoMode,
config->rotation, config->rate);
// Free the configuration instance
free(config);
}
free(errors);
// Reset the fullscreen window
fullscreenWindow = NULL;
}
// Unhide the mouse cursor (in case it was hidden)
setMouseCursorVisible(true);
}
////////////////////////////////////////////////////////////
bool WindowImplX11::processEvent(xcb_generic_event_t* windowEvent)
{
// Convert the X11 event to a sf::Event
switch (windowEvent->response_type & ~0x80)
{
// Destroy event
case XCB_DESTROY_NOTIFY:
{
// The window is about to be destroyed: we must cleanup resources
cleanup();
break;
}
// Gain focus event
case XCB_FOCUS_IN:
{
// Update the input context
if (m_inputContext)
XSetICFocus(m_inputContext);
Event event;
event.type = Event::GainedFocus;
pushEvent(event);
// If the window has been previously marked urgent (notification) as a result of a focus request, undo that
xcb_get_property_cookie_t hintsCookie = xcb_icccm_get_wm_hints_unchecked(m_connection, m_window);
xcb_icccm_wm_hints_t hints;
xcb_icccm_get_wm_hints_reply(m_connection, hintsCookie, &hints, NULL);
// Remove urgency (notification) flag from hints
hints.flags &= ~XUrgencyHint;
xcb_icccm_set_wm_hints_checked(m_connection, m_window, &hints);
break;
}
// Lost focus event
case XCB_FOCUS_OUT:
{
// Update the input context
if (m_inputContext)
XUnsetICFocus(m_inputContext);
Event event;
event.type = Event::LostFocus;
pushEvent(event);
break;
}
// Resize event
case XCB_CONFIGURE_NOTIFY:
{
xcb_configure_notify_event_t* e = reinterpret_cast<xcb_configure_notify_event_t*>(windowEvent);
Event event;
event.type = Event::Resized;
event.size.width = e->width;
event.size.height = e->height;
pushEvent(event);
break;
}
// Close event
case XCB_CLIENT_MESSAGE:
{
xcb_client_message_event_t* e = reinterpret_cast<xcb_client_message_event_t*>(windowEvent);
if ((e->format == 32) && (e->data.data32[0]) == static_cast<long>(m_atomClose))
{
Event event;
event.type = Event::Closed;
pushEvent(event);
}
break;
}
// Key down event
case XCB_KEY_PRESS:
{
xcb_key_press_event_t* e = reinterpret_cast<xcb_key_press_event_t*>(windowEvent);
// Get the keysym of the key that has been pressed
static XComposeStatus keyboard;
char buffer[32];
KeySym symbol;
// There is no xcb equivalent of XLookupString, so the xcb event
// has to be converted to an XEvent
XEvent fake_event;
fake_event.type = KeyPress;
fake_event.xany.display = m_display;
fake_event.xany.window = e->event;
fake_event.xkey.state = e->state;
fake_event.xkey.keycode = e->detail;
XLookupString(&fake_event.xkey, buffer, sizeof(buffer), &symbol, &keyboard);
// Fill the event parameters
// TODO: if modifiers are wrong, use XGetModifierMapping to retrieve the actual modifiers mapping
Event event;
event.type = Event::KeyPressed;
event.key.code = keysymToSF(symbol);
event.key.alt = e->state & XCB_MOD_MASK_1;
event.key.control = e->state & XCB_MOD_MASK_CONTROL;
event.key.shift = e->state & XCB_MOD_MASK_SHIFT;
event.key.system = e->state & XCB_MOD_MASK_4;
pushEvent(event);
// Generate a TextEntered event
if (!XFilterEvent(&fake_event, None))
{
#ifdef X_HAVE_UTF8_STRING
if (m_inputContext)
{
Status status;
Uint8 keyBuffer[16];
int length = Xutf8LookupString(m_inputContext, &fake_event.xkey, reinterpret_cast<char*>(keyBuffer), sizeof(keyBuffer), NULL, &status);
if (length > 0)
{
Uint32 unicode = 0;
Utf8::decode(keyBuffer, keyBuffer + length, unicode, 0);
if (unicode != 0)
{
Event textEvent;
textEvent.type = Event::TextEntered;
textEvent.text.unicode = unicode;
pushEvent(textEvent);
}
}
}
else
#endif
{
static XComposeStatus status;
char keyBuffer[16];
if (XLookupString(&fake_event.xkey, keyBuffer, sizeof(keyBuffer), NULL, &status))
{
Event textEvent;
textEvent.type = Event::TextEntered;
textEvent.text.unicode = static_cast<Uint32>(keyBuffer[0]);