Properly handle position in non-synthetic ConfigureNotify with xcb
[profile/ivi/qtbase.git] / src / plugins / platforms / xcb / qxcbwindow.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the plugins of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qxcbwindow.h"
43
44 #include <QtDebug>
45 #include <QScreen>
46
47 #include "qxcbconnection.h"
48 #include "qxcbscreen.h"
49 #include "qxcbdrag.h"
50 #include "qxcbkeyboard.h"
51 #include "qxcbwmsupport.h"
52
53 #ifdef XCB_USE_DRI2
54 #include "qdri2context.h"
55 #endif
56
57 // FIXME This workaround can be removed for xcb-icccm > 3.8
58 #define class class_name
59 #include <xcb/xcb_icccm.h>
60 #undef class
61 #include <xcb/xfixes.h>
62
63 // xcb-icccm 3.8 support
64 #ifdef XCB_ICCCM_NUM_WM_SIZE_HINTS_ELEMENTS
65 #define xcb_get_wm_hints_reply xcb_icccm_get_wm_hints_reply
66 #define xcb_get_wm_hints xcb_icccm_get_wm_hints
67 #define xcb_set_wm_hints xcb_icccm_set_wm_hints
68 #define xcb_set_wm_normal_hints xcb_icccm_set_wm_normal_hints
69 #define xcb_size_hints_set_base_size xcb_icccm_size_hints_set_base_size
70 #define xcb_size_hints_set_max_size xcb_icccm_size_hints_set_max_size
71 #define xcb_size_hints_set_min_size xcb_icccm_size_hints_set_min_size
72 #define xcb_size_hints_set_position xcb_icccm_size_hints_set_position
73 #define xcb_size_hints_set_resize_inc xcb_icccm_size_hints_set_resize_inc
74 #define xcb_size_hints_set_size xcb_icccm_size_hints_set_size
75 #define xcb_size_hints_set_win_gravity xcb_icccm_size_hints_set_win_gravity
76 #define xcb_wm_hints_set_iconic xcb_icccm_wm_hints_set_iconic
77 #define xcb_wm_hints_set_normal xcb_icccm_wm_hints_set_normal
78 #define xcb_wm_hints_t xcb_icccm_wm_hints_t
79 #define XCB_WM_STATE_ICONIC XCB_ICCCM_WM_STATE_ICONIC
80 #define XCB_WM_STATE_WITHDRAWN XCB_ICCCM_WM_STATE_WITHDRAWN
81 #endif
82
83 #include <private/qguiapplication_p.h>
84 #include <private/qwindow_p.h>
85
86 #include <QtGui/QPlatformBackingStore>
87 #include <QtGui/QWindowSystemInterface>
88
89 #include <stdio.h>
90
91 #ifdef XCB_USE_XLIB
92 #include <X11/Xlib.h>
93 #include <X11/Xutil.h>
94 #endif
95
96 #ifdef XCB_USE_XINPUT2_MAEMO
97 #include <X11/extensions/XInput2.h>
98 #endif
99
100 #if defined(XCB_USE_GLX)
101 #include "qglxintegration.h"
102 #include <QtPlatformSupport/private/qglxconvenience_p.h>
103 #elif defined(XCB_USE_EGL)
104 #include "qxcbeglsurface.h"
105 #include <QtPlatformSupport/private/qeglconvenience_p.h>
106 #include <QtPlatformSupport/private/qxlibeglintegration_p.h>
107 #endif
108
109 #define XCOORD_MAX 16383
110
111 //#ifdef NET_WM_STATE_DEBUG
112
113 QT_BEGIN_NAMESPACE
114
115 // Returns true if we should set WM_TRANSIENT_FOR on \a w
116 static inline bool isTransient(const QWindow *w)
117 {
118     return w->windowType() == Qt::Dialog
119            || w->windowType() == Qt::Sheet
120            || w->windowType() == Qt::Tool
121            || w->windowType() == Qt::SplashScreen
122            || w->windowType() == Qt::ToolTip
123            || w->windowType() == Qt::Drawer
124            || w->windowType() == Qt::Popup;
125 }
126
127 static inline QImage::Format imageFormatForDepth(int depth)
128 {
129     switch (depth) {
130         case 32: return QImage::Format_ARGB32_Premultiplied;
131         case 24: return QImage::Format_RGB32;
132         case 16: return QImage::Format_RGB16;
133         default: break;
134     }
135     qFatal("Unsupported display depth %d", depth);
136     return QImage::Format_Invalid;
137 }
138
139 QXcbWindow::QXcbWindow(QWindow *window)
140     : QPlatformWindow(window)
141     , m_window(0)
142     , m_syncCounter(0)
143     , m_mapped(false)
144     , m_transparent(false)
145     , m_netWmUserTimeWindow(XCB_NONE)
146 #if defined(XCB_USE_EGL)
147     , m_eglSurface(0)
148 #endif
149 {
150     m_screen = static_cast<QXcbScreen *>(window->screen()->handle());
151
152     setConnection(m_screen->connection());
153
154     create();
155 }
156
157 void QXcbWindow::create()
158 {
159     destroy();
160
161     m_windowState = Qt::WindowNoState;
162
163     Qt::WindowType type = window()->windowType();
164
165     if (type == Qt::Desktop) {
166         m_window = m_screen->root();
167         m_depth = m_screen->screen()->root_depth;
168         m_imageFormat = imageFormatForDepth(m_depth);
169         connection()->addWindow(m_window, this);
170         return;
171     }
172
173     const quint32 mask = XCB_CW_BACK_PIXMAP | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_SAVE_UNDER | XCB_CW_EVENT_MASK;
174     const quint32 values[] = {
175         // XCB_CW_BACK_PIXMAP
176         XCB_NONE,
177         // XCB_CW_OVERRIDE_REDIRECT
178         type == Qt::Popup || type == Qt::ToolTip,
179         // XCB_CW_SAVE_UNDER
180         type == Qt::Popup || type == Qt::Tool || type == Qt::SplashScreen || type == Qt::ToolTip || type == Qt::Drawer,
181         // XCB_CW_EVENT_MASK
182         XCB_EVENT_MASK_EXPOSURE
183         | XCB_EVENT_MASK_STRUCTURE_NOTIFY
184         | XCB_EVENT_MASK_KEY_PRESS
185         | XCB_EVENT_MASK_KEY_RELEASE
186         | XCB_EVENT_MASK_BUTTON_PRESS
187         | XCB_EVENT_MASK_BUTTON_RELEASE
188         | XCB_EVENT_MASK_BUTTON_MOTION
189         | XCB_EVENT_MASK_ENTER_WINDOW
190         | XCB_EVENT_MASK_LEAVE_WINDOW
191         | XCB_EVENT_MASK_POINTER_MOTION
192         | XCB_EVENT_MASK_PROPERTY_CHANGE
193         | XCB_EVENT_MASK_FOCUS_CHANGE
194     };
195
196     QRect rect = window()->geometry();
197     QPlatformWindow::setGeometry(rect);
198
199     rect.setWidth(qBound(1, rect.width(), XCOORD_MAX));
200     rect.setHeight(qBound(1, rect.height(), XCOORD_MAX));
201
202     xcb_window_t xcb_parent_id = m_screen->root();
203     if (parent())
204         xcb_parent_id = static_cast<QXcbWindow *>(parent())->xcb_window();
205
206     m_requestedFormat = window()->format();
207
208 #if (defined(XCB_USE_GLX) || defined(XCB_USE_EGL)) && defined(XCB_USE_XLIB)
209     if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::OpenGL)
210         || window()->format().hasAlpha())
211     {
212 #if defined(XCB_USE_GLX)
213         XVisualInfo *visualInfo = qglx_findVisualInfo(DISPLAY_FROM_XCB(m_screen),m_screen->screenNumber(), window()->format());
214
215 #elif defined(XCB_USE_EGL)
216         EGLDisplay eglDisplay = connection()->egl_display();
217         EGLConfig eglConfig = q_configFromGLFormat(eglDisplay, window()->format(), true);
218         VisualID id = QXlibEglIntegration::getCompatibleVisualId(DISPLAY_FROM_XCB(this), eglDisplay, eglConfig);
219
220         XVisualInfo visualInfoTemplate;
221         memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
222         visualInfoTemplate.visualid = id;
223
224         XVisualInfo *visualInfo;
225         int matchingCount = 0;
226         visualInfo = XGetVisualInfo(DISPLAY_FROM_XCB(this), VisualIDMask, &visualInfoTemplate, &matchingCount);
227 #endif //XCB_USE_GLX
228         if (visualInfo) {
229             m_depth = visualInfo->depth;
230             m_imageFormat = imageFormatForDepth(m_depth);
231             Colormap cmap = XCreateColormap(DISPLAY_FROM_XCB(this), xcb_parent_id, visualInfo->visual, AllocNone);
232
233             XSetWindowAttributes a;
234             a.background_pixel = WhitePixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
235             a.border_pixel = BlackPixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
236             a.colormap = cmap;
237
238             m_visualId = visualInfo->visualid;
239
240             m_window = XCreateWindow(DISPLAY_FROM_XCB(this), xcb_parent_id, rect.x(), rect.y(), rect.width(), rect.height(),
241                                       0, visualInfo->depth, InputOutput, visualInfo->visual,
242                                       CWBackPixel|CWBorderPixel|CWColormap, &a);
243         } else {
244             qFatal("no window!");
245         }
246     } else
247 #endif //defined(XCB_USE_GLX) || defined(XCB_USE_EGL)
248     {
249         m_window = xcb_generate_id(xcb_connection());
250         m_depth = m_screen->screen()->root_depth;
251         m_imageFormat = imageFormatForDepth(m_depth);
252         m_visualId = m_screen->screen()->root_visual;
253
254         Q_XCB_CALL(xcb_create_window(xcb_connection(),
255                                      XCB_COPY_FROM_PARENT,            // depth -- same as root
256                                      m_window,                        // window id
257                                      xcb_parent_id,                   // parent window id
258                                      rect.x(),
259                                      rect.y(),
260                                      rect.width(),
261                                      rect.height(),
262                                      0,                               // border width
263                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
264                                      m_visualId,                      // visual
265                                      0,                               // value mask
266                                      0));                             // value list
267     }
268
269     connection()->addWindow(m_window, this);
270
271     Q_XCB_CALL(xcb_change_window_attributes(xcb_connection(), m_window, mask, values));
272
273     propagateSizeHints();
274
275     xcb_atom_t properties[4];
276     int propertyCount = 0;
277     properties[propertyCount++] = atom(QXcbAtom::WM_DELETE_WINDOW);
278     properties[propertyCount++] = atom(QXcbAtom::WM_TAKE_FOCUS);
279     properties[propertyCount++] = atom(QXcbAtom::_NET_WM_PING);
280
281     if (m_screen->syncRequestSupported())
282         properties[propertyCount++] = atom(QXcbAtom::_NET_WM_SYNC_REQUEST);
283
284     if (window()->windowFlags() & Qt::WindowContextHelpButtonHint)
285         properties[propertyCount++] = atom(QXcbAtom::_NET_WM_CONTEXT_HELP);
286
287     Q_XCB_CALL(xcb_change_property(xcb_connection(),
288                                    XCB_PROP_MODE_REPLACE,
289                                    m_window,
290                                    atom(QXcbAtom::WM_PROTOCOLS),
291                                    XCB_ATOM_ATOM,
292                                    32,
293                                    propertyCount,
294                                    properties));
295     m_syncValue.hi = 0;
296     m_syncValue.lo = 0;
297
298     if (m_screen->syncRequestSupported()) {
299         m_syncCounter = xcb_generate_id(xcb_connection());
300         Q_XCB_CALL(xcb_sync_create_counter(xcb_connection(), m_syncCounter, m_syncValue));
301
302         Q_XCB_CALL(xcb_change_property(xcb_connection(),
303                                        XCB_PROP_MODE_REPLACE,
304                                        m_window,
305                                        atom(QXcbAtom::_NET_WM_SYNC_REQUEST_COUNTER),
306                                        XCB_ATOM_CARDINAL,
307                                        32,
308                                        1,
309                                        &m_syncCounter));
310     }
311
312     // set the PID to let the WM kill the application if unresponsive
313     long pid = getpid();
314     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
315                                    atom(QXcbAtom::_NET_WM_PID), XCB_ATOM_CARDINAL, 32,
316                                    1, &pid));
317
318     xcb_wm_hints_t hints;
319     memset(&hints, 0, sizeof(hints));
320     xcb_wm_hints_set_normal(&hints);
321
322     xcb_set_wm_hints(xcb_connection(), m_window, &hints);
323
324     xcb_window_t leader = m_screen->clientLeader();
325     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
326                                    atom(QXcbAtom::WM_CLIENT_LEADER), XCB_ATOM_WINDOW, 32,
327                                    1, &leader));
328
329 #ifdef XCB_USE_XINPUT2_MAEMO
330     if (connection()->isUsingXInput2()) {
331         XIEventMask xieventmask;
332         uchar bitmask[2] = { 0, 0 };
333
334         xieventmask.deviceid = XIAllMasterDevices;
335         xieventmask.mask = bitmask;
336         xieventmask.mask_len = sizeof(bitmask);
337
338         XISetMask(bitmask, XI_ButtonPress);
339         XISetMask(bitmask, XI_ButtonRelease);
340         XISetMask(bitmask, XI_Motion);
341
342         XISelectEvents(DISPLAY_FROM_XCB(this), m_window, &xieventmask, 1);
343     }
344 #endif
345
346     setWindowFlags(window()->windowFlags());
347     setWindowTitle(window()->windowTitle());
348     setWindowState(window()->windowState());
349
350     if (window()->windowFlags() & Qt::WindowTransparentForInput)
351         setTransparentForMouseEvents(true);
352
353     connection()->drag()->dndEnable(this, true);
354 }
355
356 QXcbWindow::~QXcbWindow()
357 {
358     destroy();
359 }
360
361 void QXcbWindow::destroy()
362 {
363     if (m_syncCounter && m_screen->syncRequestSupported())
364         Q_XCB_CALL(xcb_sync_destroy_counter(xcb_connection(), m_syncCounter));
365     if (m_window) {
366         connection()->removeWindow(m_window);
367         Q_XCB_CALL(xcb_destroy_window(xcb_connection(), m_window));
368     }
369     m_mapped = false;
370
371 #if defined(XCB_USE_EGL)
372     delete m_eglSurface;
373     m_eglSurface = 0;
374 #endif
375 }
376
377 void QXcbWindow::setGeometry(const QRect &rect)
378 {
379     QPlatformWindow::setGeometry(rect);
380
381     propagateSizeHints();
382
383     const quint32 mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
384     const quint32 values[] = { rect.x(),
385                                rect.y(),
386                                qBound(1, rect.width(), XCOORD_MAX),
387                                qBound(1, rect.height(), XCOORD_MAX) };
388
389     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
390
391     xcb_flush(xcb_connection());
392 }
393
394 QMargins QXcbWindow::frameMargins() const
395 {
396     if (m_dirtyFrameMargins) {
397         xcb_window_t window = m_window;
398         xcb_window_t parent = m_window;
399
400         bool foundRoot = false;
401
402         const QVector<xcb_window_t> &virtualRoots =
403             connection()->wmSupport()->virtualRoots();
404
405         while (!foundRoot) {
406             xcb_query_tree_cookie_t cookie = xcb_query_tree(xcb_connection(), parent);
407
408             xcb_generic_error_t *error;
409             xcb_query_tree_reply_t *reply = xcb_query_tree_reply(xcb_connection(), cookie, &error);
410             if (reply) {
411                 if (reply->root == reply->parent || virtualRoots.indexOf(reply->parent) != -1) {
412                     foundRoot = true;
413                 } else {
414                     window = parent;
415                     parent = reply->parent;
416                 }
417
418                 free(reply);
419             } else {
420                 if (error) {
421                     connection()->handleXcbError(error);
422                     free(error);
423                 }
424
425                 m_dirtyFrameMargins = false;
426                 m_frameMargins = QMargins();
427                 return m_frameMargins;
428             }
429         }
430
431         QPoint offset;
432
433         xcb_generic_error_t *error;
434         xcb_translate_coordinates_reply_t *reply =
435             xcb_translate_coordinates_reply(
436                 xcb_connection(),
437                 xcb_translate_coordinates(xcb_connection(), window, parent, 0, 0),
438                 &error);
439
440         if (reply) {
441             offset = QPoint(reply->dst_x, reply->dst_y);
442             free(reply);
443         } else if (error) {
444             free(error);
445         }
446
447         xcb_get_geometry_reply_t *geom =
448             xcb_get_geometry_reply(
449                 xcb_connection(),
450                 xcb_get_geometry(xcb_connection(), parent),
451                 &error);
452
453         if (geom) {
454             // --
455             // add the border_width for the window managers frame... some window managers
456             // do not use a border_width of zero for their frames, and if we the left and
457             // top strut, we ensure that pos() is absolutely correct.  frameGeometry()
458             // will still be incorrect though... perhaps i should have foffset as well, to
459             // indicate the frame offset (equal to the border_width on X).
460             // - Brad
461             // -- copied from qwidget_x11.cpp
462
463             int left = offset.x() + geom->border_width;
464             int top = offset.y() + geom->border_width;
465             int right = geom->width + geom->border_width - geometry().width() - offset.x();
466             int bottom = geom->height + geom->border_width - geometry().height() - offset.y();
467
468             m_frameMargins = QMargins(left, top, right, bottom);
469
470             free(geom);
471         } else if (error) {
472             free(error);
473         }
474
475         m_dirtyFrameMargins = false;
476     }
477
478     return m_frameMargins;
479 }
480
481 void QXcbWindow::setVisible(bool visible)
482 {
483     if (visible)
484         show();
485     else
486         hide();
487 }
488
489 void QXcbWindow::show()
490 {
491     if (window()->isTopLevel()) {
492         xcb_get_property_cookie_t cookie = xcb_get_wm_hints(xcb_connection(), m_window);
493
494         xcb_generic_error_t *error;
495
496         xcb_wm_hints_t hints;
497         xcb_get_wm_hints_reply(xcb_connection(), cookie, &hints, &error);
498
499         if (error) {
500             connection()->handleXcbError(error);
501             free(error);
502         }
503
504         if (window()->windowState() & Qt::WindowMinimized)
505             xcb_wm_hints_set_iconic(&hints);
506         else
507             xcb_wm_hints_set_normal(&hints);
508
509         xcb_set_wm_hints(xcb_connection(), m_window, &hints);
510
511         // update WM_NORMAL_HINTS
512         propagateSizeHints();
513
514         // update WM_TRANSIENT_FOR
515         if (window()->transientParent() && isTransient(window())) {
516             QXcbWindow *transientXcbParent = static_cast<QXcbWindow *>(window()->transientParent()->handle());
517             if (transientXcbParent) {
518                 // ICCCM 4.1.2.6
519                 xcb_window_t parentWindow = transientXcbParent->xcb_window();
520
521                 // todo: set transient for group (wm_client_leader) if no parent, a la qwidget_x11.cpp
522                 Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
523                                                XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 32,
524                                                1, &parentWindow));
525             }
526         }
527
528         // update _MOTIF_WM_HINTS
529         updateMotifWmHintsBeforeMap();
530
531         // update _NET_WM_STATE
532         updateNetWmStateBeforeMap();
533     }
534
535     Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
536     xcb_flush(xcb_connection());
537
538     connection()->sync();
539 }
540
541 void QXcbWindow::hide()
542 {
543     Q_XCB_CALL(xcb_unmap_window(xcb_connection(), m_window));
544
545     // send synthetic UnmapNotify event according to icccm 4.1.4
546     xcb_unmap_notify_event_t event;
547     event.response_type = XCB_UNMAP_NOTIFY;
548     event.event = m_screen->root();
549     event.window = m_window;
550     event.from_configure = false;
551     Q_XCB_CALL(xcb_send_event(xcb_connection(), false, m_screen->root(),
552                               XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
553
554     xcb_flush(xcb_connection());
555
556     m_mapped = false;
557 }
558
559 struct QtMotifWmHints {
560     quint32 flags, functions, decorations;
561     qint32 input_mode;
562     quint32 status;
563 };
564
565 enum {
566     MWM_HINTS_FUNCTIONS   = (1L << 0),
567
568     MWM_FUNC_ALL      = (1L << 0),
569     MWM_FUNC_RESIZE   = (1L << 1),
570     MWM_FUNC_MOVE     = (1L << 2),
571     MWM_FUNC_MINIMIZE = (1L << 3),
572     MWM_FUNC_MAXIMIZE = (1L << 4),
573     MWM_FUNC_CLOSE    = (1L << 5),
574
575     MWM_HINTS_DECORATIONS = (1L << 1),
576
577     MWM_DECOR_ALL      = (1L << 0),
578     MWM_DECOR_BORDER   = (1L << 1),
579     MWM_DECOR_RESIZEH  = (1L << 2),
580     MWM_DECOR_TITLE    = (1L << 3),
581     MWM_DECOR_MENU     = (1L << 4),
582     MWM_DECOR_MINIMIZE = (1L << 5),
583     MWM_DECOR_MAXIMIZE = (1L << 6),
584
585     MWM_HINTS_INPUT_MODE = (1L << 2),
586
587     MWM_INPUT_MODELESS                  = 0L,
588     MWM_INPUT_PRIMARY_APPLICATION_MODAL = 1L,
589     MWM_INPUT_FULL_APPLICATION_MODAL    = 3L
590 };
591
592 static QtMotifWmHints getMotifWmHints(QXcbConnection *c, xcb_window_t window)
593 {
594     QtMotifWmHints hints;
595
596     xcb_get_property_cookie_t get_cookie =
597         xcb_get_property(c->xcb_connection(), 0, window, c->atom(QXcbAtom::_MOTIF_WM_HINTS),
598                          c->atom(QXcbAtom::_MOTIF_WM_HINTS), 0, 20);
599
600     xcb_generic_error_t *error;
601
602     xcb_get_property_reply_t *reply =
603         xcb_get_property_reply(c->xcb_connection(), get_cookie, &error);
604
605     if (reply && reply->format == 32 && reply->type == c->atom(QXcbAtom::_MOTIF_WM_HINTS)) {
606         hints = *((QtMotifWmHints *)xcb_get_property_value(reply));
607     } else if (error) {
608         c->handleXcbError(error);
609         free(error);
610
611         hints.flags = 0L;
612         hints.functions = MWM_FUNC_ALL;
613         hints.decorations = MWM_DECOR_ALL;
614         hints.input_mode = 0L;
615         hints.status = 0L;
616     }
617
618     free(reply);
619
620     return hints;
621 }
622
623 static void setMotifWmHints(QXcbConnection *c, xcb_window_t window, const QtMotifWmHints &hints)
624 {
625     if (hints.flags != 0l) {
626         Q_XCB_CALL2(xcb_change_property(c->xcb_connection(),
627                                        XCB_PROP_MODE_REPLACE,
628                                        window,
629                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
630                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
631                                        32,
632                                        5,
633                                        &hints), c);
634     } else {
635         Q_XCB_CALL2(xcb_delete_property(c->xcb_connection(), window, c->atom(QXcbAtom::_MOTIF_WM_HINTS)), c);
636     }
637 }
638
639 void QXcbWindow::printNetWmState(const QVector<xcb_atom_t> &state)
640 {
641     printf("_NET_WM_STATE (%d): ", state.size());
642     for (int i = 0; i < state.size(); ++i) {
643 #define CHECK_WM_STATE(state_atom) \
644         if (state.at(i) == atom(QXcbAtom::state_atom))\
645             printf(#state_atom " ");
646         CHECK_WM_STATE(_NET_WM_STATE_ABOVE)
647         CHECK_WM_STATE(_NET_WM_STATE_BELOW)
648         CHECK_WM_STATE(_NET_WM_STATE_FULLSCREEN)
649         CHECK_WM_STATE(_NET_WM_STATE_MAXIMIZED_HORZ)
650         CHECK_WM_STATE(_NET_WM_STATE_MAXIMIZED_VERT)
651         CHECK_WM_STATE(_NET_WM_STATE_MODAL)
652         CHECK_WM_STATE(_NET_WM_STATE_STAYS_ON_TOP)
653         CHECK_WM_STATE(_NET_WM_STATE_DEMANDS_ATTENTION)
654 #undef CHECK_WM_STATE
655     }
656     printf("\n");
657 }
658
659 QVector<xcb_atom_t> QXcbWindow::getNetWmState()
660 {
661     QVector<xcb_atom_t> result;
662
663     xcb_get_property_cookie_t get_cookie =
664         xcb_get_property(xcb_connection(), 0, m_window, atom(QXcbAtom::_NET_WM_STATE),
665                          XCB_ATOM_ATOM, 0, 1024);
666
667     xcb_generic_error_t *error;
668
669     xcb_get_property_reply_t *reply =
670         xcb_get_property_reply(xcb_connection(), get_cookie, &error);
671
672     if (reply && reply->format == 32 && reply->type == XCB_ATOM_ATOM) {
673         result.resize(reply->length);
674
675         memcpy(result.data(), xcb_get_property_value(reply), reply->length * sizeof(xcb_atom_t));
676
677 #ifdef NET_WM_STATE_DEBUG
678         printf("getting net wm state (%x)\n", m_window);
679         printNetWmState(result);
680 #endif
681
682         free(reply);
683     } else if (error) {
684         connection()->handleXcbError(error);
685         free(error);
686     } else {
687 #ifdef NET_WM_STATE_DEBUG
688         printf("getting net wm state (%x), empty\n", m_window);
689 #endif
690     }
691
692     return result;
693 }
694
695 void QXcbWindow::setNetWmState(const QVector<xcb_atom_t> &atoms)
696 {
697     if (atoms.isEmpty()) {
698         Q_XCB_CALL(xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_STATE)));
699     } else {
700         Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
701                                        atom(QXcbAtom::_NET_WM_STATE), XCB_ATOM_ATOM, 32,
702                                        atoms.count(), atoms.constData()));
703     }
704     xcb_flush(xcb_connection());
705 }
706
707
708 Qt::WindowFlags QXcbWindow::setWindowFlags(Qt::WindowFlags flags)
709 {
710     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
711
712     if (type == Qt::ToolTip)
713         flags |= Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint;
714     if (type == Qt::Popup)
715         flags |= Qt::X11BypassWindowManagerHint;
716
717     if (flags & Qt::WindowTransparentForInput) {
718         uint32_t mask = XCB_EVENT_MASK_NO_EVENT;
719         xcb_change_window_attributes(xcb_connection(), xcb_window(), XCB_CW_EVENT_MASK, &mask);
720     }
721
722     setNetWmWindowFlags(flags);
723     setMotifWindowFlags(flags);
724
725     setTransparentForMouseEvents(flags & Qt::WindowTransparentForInput);
726
727     return flags;
728 }
729
730 void QXcbWindow::setMotifWindowFlags(Qt::WindowFlags flags)
731 {
732     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
733
734     QtMotifWmHints mwmhints;
735     mwmhints.flags = 0L;
736     mwmhints.functions = 0L;
737     mwmhints.decorations = 0;
738     mwmhints.input_mode = 0L;
739     mwmhints.status = 0L;
740
741     if (type != Qt::SplashScreen) {
742         mwmhints.flags |= MWM_HINTS_DECORATIONS;
743
744         bool customize = flags & Qt::CustomizeWindowHint;
745         if (!(flags & Qt::FramelessWindowHint) && !(customize && !(flags & Qt::WindowTitleHint))) {
746             mwmhints.decorations |= MWM_DECOR_BORDER;
747             mwmhints.decorations |= MWM_DECOR_RESIZEH;
748
749             if (flags & Qt::WindowTitleHint)
750                 mwmhints.decorations |= MWM_DECOR_TITLE;
751
752             if (flags & Qt::WindowSystemMenuHint)
753                 mwmhints.decorations |= MWM_DECOR_MENU;
754
755             if (flags & Qt::WindowMinimizeButtonHint) {
756                 mwmhints.decorations |= MWM_DECOR_MINIMIZE;
757                 mwmhints.functions |= MWM_FUNC_MINIMIZE;
758             }
759
760             if (flags & Qt::WindowMaximizeButtonHint) {
761                 mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
762                 mwmhints.functions |= MWM_FUNC_MAXIMIZE;
763             }
764
765             if (flags & Qt::WindowCloseButtonHint)
766                 mwmhints.functions |= MWM_FUNC_CLOSE;
767         }
768     } else {
769         // if type == Qt::SplashScreen
770         mwmhints.decorations = MWM_DECOR_ALL;
771     }
772
773     if (mwmhints.functions != 0) {
774         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
775         mwmhints.functions |= MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
776     } else {
777         mwmhints.functions = MWM_FUNC_ALL;
778     }
779
780     if (!(flags & Qt::FramelessWindowHint)
781         && flags & Qt::CustomizeWindowHint
782         && flags & Qt::WindowTitleHint
783         && !(flags &
784              (Qt::WindowMinimizeButtonHint
785               | Qt::WindowMaximizeButtonHint
786               | Qt::WindowCloseButtonHint)))
787     {
788         // a special case - only the titlebar without any button
789         mwmhints.flags = MWM_HINTS_FUNCTIONS;
790         mwmhints.functions = MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
791         mwmhints.decorations = 0;
792     }
793
794     setMotifWmHints(connection(), m_window, mwmhints);
795 }
796
797 void QXcbWindow::changeNetWmState(bool set, xcb_atom_t one, xcb_atom_t two)
798 {
799     xcb_client_message_event_t event;
800
801     event.response_type = XCB_CLIENT_MESSAGE;
802     event.format = 32;
803     event.window = m_window;
804     event.type = atom(QXcbAtom::_NET_WM_STATE);
805     event.data.data32[0] = set ? 1 : 0;
806     event.data.data32[1] = one;
807     event.data.data32[2] = two;
808     event.data.data32[3] = 0;
809     event.data.data32[4] = 0;
810
811     Q_XCB_CALL(xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
812 }
813
814 Qt::WindowState QXcbWindow::setWindowState(Qt::WindowState state)
815 {
816     if (state == m_windowState)
817         return state;
818
819     // unset old state
820     switch (m_windowState) {
821     case Qt::WindowMinimized:
822         Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
823         break;
824     case Qt::WindowMaximized:
825         changeNetWmState(false,
826                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
827                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
828         break;
829     case Qt::WindowFullScreen:
830         changeNetWmState(false, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
831         break;
832     default:
833         break;
834     }
835
836     // set new state
837     switch (state) {
838     case Qt::WindowMinimized:
839         {
840             xcb_client_message_event_t event;
841
842             event.response_type = XCB_CLIENT_MESSAGE;
843             event.format = 32;
844             event.window = m_window;
845             event.type = atom(QXcbAtom::WM_CHANGE_STATE);
846             event.data.data32[0] = XCB_WM_STATE_ICONIC;
847             event.data.data32[1] = 0;
848             event.data.data32[2] = 0;
849             event.data.data32[3] = 0;
850             event.data.data32[4] = 0;
851
852             Q_XCB_CALL(xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
853         }
854         break;
855     case Qt::WindowMaximized:
856         changeNetWmState(true,
857                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
858                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
859         break;
860     case Qt::WindowFullScreen:
861         changeNetWmState(true, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
862         break;
863     case Qt::WindowNoState:
864         break;
865     default:
866         break;
867     }
868
869     connection()->sync();
870
871     m_windowState = state;
872     return m_windowState;
873 }
874
875 void QXcbWindow::setNetWmWindowFlags(Qt::WindowFlags flags)
876 {
877     // in order of decreasing priority
878     QVector<uint> windowTypes;
879
880     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
881
882     switch (type) {
883     case Qt::Dialog:
884     case Qt::Sheet:
885         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_DIALOG));
886         break;
887     case Qt::Tool:
888     case Qt::Drawer:
889         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_UTILITY));
890         break;
891     case Qt::ToolTip:
892         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_TOOLTIP));
893         break;
894     case Qt::SplashScreen:
895         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_SPLASH));
896         break;
897     default:
898         break;
899     }
900
901     if (flags & Qt::FramelessWindowHint)
902         windowTypes.append(atom(QXcbAtom::_KDE_NET_WM_WINDOW_TYPE_OVERRIDE));
903
904     windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_NORMAL));
905
906     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
907                                    atom(QXcbAtom::_NET_WM_WINDOW_TYPE), XCB_ATOM_ATOM, 32,
908                                    windowTypes.count(), windowTypes.constData()));
909 }
910
911 void QXcbWindow::updateMotifWmHintsBeforeMap()
912 {
913     QtMotifWmHints mwmhints = getMotifWmHints(connection(), m_window);
914
915     if (window()->windowModality() != Qt::NonModal) {
916         switch (window()->windowModality()) {
917         case Qt::WindowModal:
918             mwmhints.input_mode = MWM_INPUT_PRIMARY_APPLICATION_MODAL;
919             break;
920         case Qt::ApplicationModal:
921         default:
922             mwmhints.input_mode = MWM_INPUT_FULL_APPLICATION_MODAL;
923             break;
924         }
925         mwmhints.flags |= MWM_HINTS_INPUT_MODE;
926     } else {
927         mwmhints.input_mode = MWM_INPUT_MODELESS;
928         mwmhints.flags &= ~MWM_HINTS_INPUT_MODE;
929     }
930
931     if (window()->minimumSize() == window()->maximumSize()) {
932         // fixed size, remove the resize handle (since mwm/dtwm
933         // isn't smart enough to do it itself)
934         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
935         if (mwmhints.functions == MWM_FUNC_ALL) {
936             mwmhints.functions = MWM_FUNC_MOVE;
937         } else {
938             mwmhints.functions &= ~MWM_FUNC_RESIZE;
939         }
940
941         if (mwmhints.decorations == MWM_DECOR_ALL) {
942             mwmhints.flags |= MWM_HINTS_DECORATIONS;
943             mwmhints.decorations = (MWM_DECOR_BORDER
944                                     | MWM_DECOR_TITLE
945                                     | MWM_DECOR_MENU);
946         } else {
947             mwmhints.decorations &= ~MWM_DECOR_RESIZEH;
948         }
949     }
950
951     if (window()->windowFlags() & Qt::WindowMinimizeButtonHint) {
952         mwmhints.flags |= MWM_HINTS_DECORATIONS;
953         mwmhints.decorations |= MWM_DECOR_MINIMIZE;
954         mwmhints.functions |= MWM_FUNC_MINIMIZE;
955     }
956     if (window()->windowFlags() & Qt::WindowMaximizeButtonHint) {
957         mwmhints.flags |= MWM_HINTS_DECORATIONS;
958         mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
959         mwmhints.functions |= MWM_FUNC_MAXIMIZE;
960     }
961     if (window()->windowFlags() & Qt::WindowCloseButtonHint)
962         mwmhints.functions |= MWM_FUNC_CLOSE;
963
964     setMotifWmHints(connection(), m_window, mwmhints);
965 }
966
967 void QXcbWindow::updateNetWmStateBeforeMap()
968 {
969     QVector<xcb_atom_t> netWmState;
970
971     Qt::WindowFlags flags = window()->windowFlags();
972     if (flags & Qt::WindowStaysOnTopHint) {
973         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_ABOVE));
974         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_STAYS_ON_TOP));
975     } else if (flags & Qt::WindowStaysOnBottomHint) {
976         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_BELOW));
977     }
978
979     if (window()->windowState() & Qt::WindowFullScreen) {
980         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
981     }
982
983     if (window()->windowState() & Qt::WindowMaximized) {
984         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ));
985         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
986     }
987
988     if (window()->windowModality() != Qt::NonModal) {
989         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_MODAL));
990     }
991
992     setNetWmState(netWmState);
993 }
994
995 void QXcbWindow::updateNetWmUserTime(xcb_timestamp_t timestamp)
996 {
997     xcb_window_t wid = m_window;
998
999     const bool isSupportedByWM = connection()->wmSupport()->isSupportedByWM(atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
1000     if (m_netWmUserTimeWindow || isSupportedByWM) {
1001         if (!m_netWmUserTimeWindow) {
1002             m_netWmUserTimeWindow = xcb_generate_id(xcb_connection());
1003             Q_XCB_CALL(xcb_create_window(xcb_connection(),
1004                                          XCB_COPY_FROM_PARENT,            // depth -- same as root
1005                                          m_netWmUserTimeWindow,                        // window id
1006                                          m_window,                   // parent window id
1007                                          -1, -1, 1, 1,
1008                                          0,                               // border width
1009                                          XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
1010                                          m_visualId,                      // visual
1011                                          0,                               // value mask
1012                                          0));                             // value list
1013             wid = m_netWmUserTimeWindow;
1014             xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW),
1015                                 XCB_ATOM_WINDOW, 32, 1, &m_netWmUserTimeWindow);
1016             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME));
1017         } else if (!isSupportedByWM) {
1018             // WM no longer supports it, then we should remove the
1019             // _NET_WM_USER_TIME_WINDOW atom.
1020             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
1021             xcb_destroy_window(xcb_connection(), m_netWmUserTimeWindow);
1022             m_netWmUserTimeWindow = XCB_NONE;
1023         } else {
1024             wid = m_netWmUserTimeWindow;
1025         }
1026     }
1027     xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, wid, atom(QXcbAtom::_NET_WM_USER_TIME),
1028                         XCB_ATOM_CARDINAL, 32, 1, &timestamp);
1029 }
1030
1031 void QXcbWindow::setTransparentForMouseEvents(bool transparent)
1032 {
1033     if (transparent == m_transparent)
1034         return;
1035
1036     xcb_rectangle_t rectangle;
1037
1038     xcb_rectangle_t *rect = 0;
1039     int nrect = 0;
1040
1041     if (!transparent) {
1042         rectangle.x = 0;
1043         rectangle.y = 0;
1044         rectangle.width = geometry().width();
1045         rectangle.height = geometry().height();
1046         rect = &rectangle;
1047         nrect = 1;
1048     }
1049
1050     xcb_xfixes_region_t region = xcb_generate_id(xcb_connection());
1051     xcb_xfixes_create_region(xcb_connection(), region, nrect, rect);
1052     xcb_xfixes_set_window_shape_region_checked(xcb_connection(), m_window, XCB_SHAPE_SK_INPUT, 0, 0, region);
1053     xcb_xfixes_destroy_region(xcb_connection(), region);
1054
1055     m_transparent = transparent;
1056 }
1057
1058
1059 WId QXcbWindow::winId() const
1060 {
1061     return m_window;
1062 }
1063
1064 void QXcbWindow::setParent(const QPlatformWindow *parent)
1065 {
1066     // re-create for compatibility
1067     create();
1068
1069     QPoint topLeft = geometry().topLeft();
1070
1071     xcb_window_t xcb_parent_id = parent ? static_cast<const QXcbWindow *>(parent)->xcb_window() : m_screen->root();
1072     Q_XCB_CALL(xcb_reparent_window(xcb_connection(), xcb_window(), xcb_parent_id, topLeft.x(), topLeft.y()));
1073 }
1074
1075 void QXcbWindow::setWindowTitle(const QString &title)
1076 {
1077     QByteArray ba = title.toUtf8();
1078     Q_XCB_CALL(xcb_change_property(xcb_connection(),
1079                                    XCB_PROP_MODE_REPLACE,
1080                                    m_window,
1081                                    atom(QXcbAtom::_NET_WM_NAME),
1082                                    atom(QXcbAtom::UTF8_STRING),
1083                                    8,
1084                                    ba.length(),
1085                                    ba.constData()));
1086 }
1087
1088 void QXcbWindow::raise()
1089 {
1090     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1091     const quint32 values[] = { XCB_STACK_MODE_ABOVE };
1092     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1093 }
1094
1095 void QXcbWindow::lower()
1096 {
1097     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1098     const quint32 values[] = { XCB_STACK_MODE_BELOW };
1099     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1100 }
1101
1102 void QXcbWindow::propagateSizeHints()
1103 {
1104     // update WM_NORMAL_HINTS
1105     xcb_size_hints_t hints;
1106     memset(&hints, 0, sizeof(hints));
1107
1108     QRect rect = geometry();
1109
1110     QWindow *win = window();
1111
1112     xcb_size_hints_set_position(&hints, true, rect.x(), rect.y());
1113     xcb_size_hints_set_size(&hints, true, rect.width(), rect.height());
1114     xcb_size_hints_set_win_gravity(&hints, qt_window_private(win)->positionPolicy == QWindowPrivate::WindowFrameInclusive
1115                                            ? XCB_GRAVITY_NORTH_WEST : XCB_GRAVITY_STATIC);
1116
1117     QSize minimumSize = win->minimumSize();
1118     QSize maximumSize = win->maximumSize();
1119     QSize baseSize = win->baseSize();
1120     QSize sizeIncrement = win->sizeIncrement();
1121
1122     if (minimumSize.width() > 0 || minimumSize.height() > 0)
1123         xcb_size_hints_set_min_size(&hints, minimumSize.width(), minimumSize.height());
1124
1125     if (maximumSize.width() < QWINDOWSIZE_MAX || maximumSize.height() < QWINDOWSIZE_MAX)
1126         xcb_size_hints_set_max_size(&hints,
1127                                     qMin(XCOORD_MAX, maximumSize.width()),
1128                                     qMin(XCOORD_MAX, maximumSize.height()));
1129
1130     if (sizeIncrement.width() > 0 || sizeIncrement.height() > 0) {
1131         xcb_size_hints_set_base_size(&hints, baseSize.width(), baseSize.height());
1132         xcb_size_hints_set_resize_inc(&hints, sizeIncrement.width(), sizeIncrement.height());
1133     }
1134
1135     xcb_set_wm_normal_hints(xcb_connection(), m_window, &hints);
1136 }
1137
1138 void QXcbWindow::requestActivateWindow()
1139 {
1140     if (m_mapped){
1141         updateNetWmUserTime(connection()->time());
1142         Q_XCB_CALL(xcb_set_input_focus(xcb_connection(), XCB_INPUT_FOCUS_PARENT, m_window, connection()->time()));
1143     }
1144     connection()->sync();
1145 }
1146
1147 QSurfaceFormat QXcbWindow::format() const
1148 {
1149     // ### return actual format
1150     return m_requestedFormat;
1151 }
1152
1153 #if defined(XCB_USE_EGL)
1154 QXcbEGLSurface *QXcbWindow::eglSurface() const
1155 {
1156     if (!m_eglSurface) {
1157         EGLDisplay display = connection()->egl_display();
1158         EGLConfig config = q_configFromGLFormat(display, window()->format(), true);
1159         EGLSurface surface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)m_window, 0);
1160
1161         m_eglSurface = new QXcbEGLSurface(display, surface);
1162     }
1163
1164     return m_eglSurface;
1165 }
1166 #endif
1167
1168 void QXcbWindow::handleExposeEvent(const xcb_expose_event_t *event)
1169 {
1170     QRect rect(event->x, event->y, event->width, event->height);
1171
1172     if (m_exposeRegion.isEmpty())
1173         m_exposeRegion = rect;
1174     else
1175         m_exposeRegion |= rect;
1176
1177     // if count is non-zero there are more expose events pending
1178     if (event->count == 0) {
1179         QWindowSystemInterface::handleSynchronousExposeEvent(window(), m_exposeRegion);
1180         m_exposeRegion = QRegion();
1181     }
1182 }
1183
1184 void QXcbWindow::handleClientMessageEvent(const xcb_client_message_event_t *event)
1185 {
1186     if (event->format != 32)
1187         return;
1188
1189     if (event->type == atom(QXcbAtom::WM_PROTOCOLS)) {
1190         if (event->data.data32[0] == atom(QXcbAtom::WM_DELETE_WINDOW)) {
1191             QWindowSystemInterface::handleCloseEvent(window());
1192         } else if (event->data.data32[0] == atom(QXcbAtom::WM_TAKE_FOCUS)) {
1193             connection()->setTime(event->data.data32[1]);
1194         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_PING)) {
1195             xcb_client_message_event_t reply = *event;
1196
1197             reply.response_type = XCB_CLIENT_MESSAGE;
1198             reply.window = m_screen->root();
1199
1200             xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&reply);
1201             xcb_flush(xcb_connection());
1202         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_SYNC_REQUEST)) {
1203             connection()->setTime(event->data.data32[1]);
1204             m_syncValue.lo = event->data.data32[2];
1205             m_syncValue.hi = event->data.data32[3];
1206         } else {
1207             qWarning() << "unhandled WM_PROTOCOLS message:" << connection()->atomName(event->data.data32[0]);
1208         }
1209     } else if (event->type == atom(QXcbAtom::XdndEnter)) {
1210         connection()->drag()->handleEnter(window(), event);
1211     } else if (event->type == atom(QXcbAtom::XdndPosition)) {
1212         connection()->drag()->handlePosition(window(), event, false);
1213     } else if (event->type == atom(QXcbAtom::XdndLeave)) {
1214         connection()->drag()->handleLeave(window(), event, false);
1215     } else if (event->type == atom(QXcbAtom::XdndDrop)) {
1216         connection()->drag()->handleDrop(window(), event, false);
1217     } else {
1218         qWarning() << "unhandled client message:" << connection()->atomName(event->type);
1219     }
1220 }
1221
1222 void QXcbWindow::handleConfigureNotifyEvent(const xcb_configure_notify_event_t *event)
1223 {
1224     bool fromSendEvent = (event->response_type & 0x80);
1225     QPoint pos(event->x, event->y);
1226     if (!fromSendEvent) {
1227         // Do not trust the position, query it instead.
1228         xcb_translate_coordinates_cookie_t cookie = xcb_translate_coordinates(xcb_connection(), xcb_window(),
1229                                                                               m_screen->root(), 0, 0);
1230         xcb_generic_error_t *error;
1231         xcb_translate_coordinates_reply_t *reply = xcb_translate_coordinates_reply(xcb_connection(), cookie, &error);
1232         if (reply) {
1233             pos.setX(reply->dst_x);
1234             pos.setY(reply->dst_y);
1235             free(reply);
1236         } else if (error) {
1237             free(error);
1238         }
1239     }
1240
1241     QRect rect(pos, QSize(event->width, event->height));
1242
1243     QPlatformWindow::setGeometry(rect);
1244     QWindowSystemInterface::handleGeometryChange(window(), rect);
1245
1246     m_dirtyFrameMargins = true;
1247
1248 #if XCB_USE_DRI2
1249     if (m_context)
1250         static_cast<QDri2Context *>(m_context)->resize(rect.size());
1251 #endif
1252 }
1253
1254 void QXcbWindow::handleMapNotifyEvent(const xcb_map_notify_event_t *event)
1255 {
1256     if (event->window == m_window) {
1257         m_mapped = true;
1258         QWindowSystemInterface::handleMapEvent(window());
1259     }
1260 }
1261
1262 void QXcbWindow::handleUnmapNotifyEvent(const xcb_unmap_notify_event_t *event)
1263 {
1264     if (event->window == m_window) {
1265         m_mapped = false;
1266         QWindowSystemInterface::handleUnmapEvent(window());
1267     }
1268 }
1269
1270 static Qt::MouseButtons translateMouseButtons(int s)
1271 {
1272     Qt::MouseButtons ret = 0;
1273     if (s & XCB_BUTTON_MASK_1)
1274         ret |= Qt::LeftButton;
1275     if (s & XCB_BUTTON_MASK_2)
1276         ret |= Qt::MidButton;
1277     if (s & XCB_BUTTON_MASK_3)
1278         ret |= Qt::RightButton;
1279     return ret;
1280 }
1281
1282 static Qt::MouseButton translateMouseButton(xcb_button_t s)
1283 {
1284     switch (s) {
1285     case 1: return Qt::LeftButton;
1286     case 2: return Qt::MidButton;
1287     case 3: return Qt::RightButton;
1288     // Button values 4-7 were already handled as Wheel events, and won't occur here.
1289     case 8: return Qt::BackButton;      // Also known as Qt::ExtraButton1
1290     case 9: return Qt::ForwardButton;   // Also known as Qt::ExtraButton2
1291     case 10: return Qt::ExtraButton3;
1292     case 11: return Qt::ExtraButton4;
1293     case 12: return Qt::ExtraButton5;
1294     case 13: return Qt::ExtraButton6;
1295     case 14: return Qt::ExtraButton7;
1296     case 15: return Qt::ExtraButton8;
1297     case 16: return Qt::ExtraButton9;
1298     case 17: return Qt::ExtraButton10;
1299     case 18: return Qt::ExtraButton11;
1300     case 19: return Qt::ExtraButton12;
1301     case 20: return Qt::ExtraButton13;
1302     case 21: return Qt::ExtraButton14;
1303     case 22: return Qt::ExtraButton15;
1304     case 23: return Qt::ExtraButton16;
1305     case 24: return Qt::ExtraButton17;
1306     case 25: return Qt::ExtraButton18;
1307     case 26: return Qt::ExtraButton19;
1308     case 27: return Qt::ExtraButton20;
1309     case 28: return Qt::ExtraButton21;
1310     case 29: return Qt::ExtraButton22;
1311     case 30: return Qt::ExtraButton23;
1312     case 31: return Qt::ExtraButton24;
1313     default: return Qt::NoButton;
1314     }
1315 }
1316
1317 void QXcbWindow::handleButtonPressEvent(const xcb_button_press_event_t *event)
1318 {
1319     updateNetWmUserTime(event->time);
1320
1321     QPoint local(event->event_x, event->event_y);
1322     QPoint global(event->root_x, event->root_y);
1323
1324     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1325
1326     if (event->detail >= 4 && event->detail <= 7) {
1327         // Logic borrowed from qapplication_x11.cpp
1328         int delta = 120 * ((event->detail == 4 || event->detail == 6) ? 1 : -1);
1329         bool hor = (((event->detail == 4 || event->detail == 5)
1330                      && (modifiers & Qt::AltModifier))
1331                     || (event->detail == 6 || event->detail == 7));
1332
1333         QWindowSystemInterface::handleWheelEvent(window(), event->time,
1334                                                  local, global, delta, hor ? Qt::Horizontal : Qt::Vertical, modifiers);
1335         return;
1336     }
1337
1338     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1339 }
1340
1341 void QXcbWindow::handleButtonReleaseEvent(const xcb_button_release_event_t *event)
1342 {
1343     QPoint local(event->event_x, event->event_y);
1344     QPoint global(event->root_x, event->root_y);
1345     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1346
1347     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1348 }
1349
1350 void QXcbWindow::handleMotionNotifyEvent(const xcb_motion_notify_event_t *event)
1351 {
1352     QPoint local(event->event_x, event->event_y);
1353     QPoint global(event->root_x, event->root_y);
1354     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1355
1356     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1357 }
1358
1359 void QXcbWindow::handleMouseEvent(xcb_button_t detail, uint16_t state, xcb_timestamp_t time, const QPoint &local, const QPoint &global, Qt::KeyboardModifiers modifiers)
1360 {
1361     connection()->setTime(time);
1362
1363     Qt::MouseButtons buttons = translateMouseButtons(state);
1364     Qt::MouseButton button = translateMouseButton(detail);
1365
1366     buttons ^= button; // X event uses state *before*, Qt uses state *after*
1367
1368     QWindowSystemInterface::handleMouseEvent(window(), time, local, global, buttons, modifiers);
1369 }
1370
1371 void QXcbWindow::handleEnterNotifyEvent(const xcb_enter_notify_event_t *event)
1372 {
1373     connection()->setTime(event->time);
1374
1375     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1376         || event->detail == XCB_NOTIFY_DETAIL_VIRTUAL
1377         || event->detail == XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL)
1378     {
1379         return;
1380     }
1381
1382     QWindowSystemInterface::handleEnterEvent(window());
1383 }
1384
1385 void QXcbWindow::handleLeaveNotifyEvent(const xcb_leave_notify_event_t *event)
1386 {
1387     connection()->setTime(event->time);
1388
1389     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1390         || event->detail == XCB_NOTIFY_DETAIL_INFERIOR)
1391     {
1392         return;
1393     }
1394
1395     QWindowSystemInterface::handleLeaveEvent(window());
1396 }
1397
1398 void QXcbWindow::handlePropertyNotifyEvent(const xcb_property_notify_event_t *event)
1399 {
1400     connection()->setTime(event->time);
1401
1402     bool propertyDeleted = event->state == XCB_PROPERTY_DELETE;
1403
1404     if (event->atom == atom(QXcbAtom::_NET_WM_STATE) || event->atom == atom(QXcbAtom::WM_STATE)) {
1405         if (propertyDeleted)
1406             return;
1407
1408         xcb_get_property_cookie_t get_cookie =
1409             xcb_get_property(xcb_connection(), 0, m_window, atom(QXcbAtom::WM_STATE),
1410                              XCB_ATOM_ANY, 0, 1024);
1411
1412         xcb_generic_error_t *error;
1413
1414         xcb_get_property_reply_t *reply =
1415             xcb_get_property_reply(xcb_connection(), get_cookie, &error);
1416
1417         xcb_atom_t wm_state = XCB_WM_STATE_WITHDRAWN;
1418         if (reply && reply->format == 32 && reply->type == atom(QXcbAtom::WM_STATE)) {
1419             if (reply->length != 0)
1420                 wm_state = ((long *)xcb_get_property_value(reply))[0];
1421             free(reply);
1422         } else if (error) {
1423             connection()->handleXcbError(error);
1424             free(error);
1425         }
1426
1427         QVector<xcb_atom_t> netWmState = getNetWmState();
1428
1429         bool maximized = netWmState.contains(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ))
1430             && netWmState.contains(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
1431         bool fullscreen = netWmState.contains(atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
1432
1433         Qt::WindowState state = Qt::WindowNoState;
1434         if (wm_state == XCB_WM_STATE_ICONIC)
1435             state = Qt::WindowMinimized;
1436         else if (maximized)
1437             state = Qt::WindowMaximized;
1438         else if (fullscreen)
1439             state = Qt::WindowFullScreen;
1440
1441         QWindowSystemInterface::handleWindowStateChanged(window(), state);
1442     }
1443 }
1444
1445 void QXcbWindow::handleFocusInEvent(const xcb_focus_in_event_t *)
1446 {
1447     QWindowSystemInterface::handleWindowActivated(window());
1448 }
1449
1450 static bool focusInPeeker(xcb_generic_event_t *event)
1451 {
1452     if (!event) {
1453         // FocusIn event is not in the queue, proceed with FocusOut normally.
1454         QWindowSystemInterface::handleWindowActivated(0);
1455         return true;
1456     }
1457     uint response_type = event->response_type & ~0x80;
1458     return response_type == XCB_FOCUS_IN;
1459 }
1460
1461 void QXcbWindow::handleFocusOutEvent(const xcb_focus_out_event_t *)
1462 {
1463     // Do not set the active window to 0 if there is a FocusIn coming.
1464     // There is however no equivalent for XPutBackEvent so register a
1465     // callback for QXcbConnection instead.
1466     connection()->addPeekFunc(focusInPeeker);
1467 }
1468
1469 void QXcbWindow::updateSyncRequestCounter()
1470 {
1471     if (m_screen->syncRequestSupported() && (m_syncValue.lo != 0 || m_syncValue.hi != 0)) {
1472         Q_XCB_CALL(xcb_sync_set_counter(xcb_connection(), m_syncCounter, m_syncValue));
1473         xcb_flush(xcb_connection());
1474         connection()->sync();
1475
1476         m_syncValue.lo = 0;
1477         m_syncValue.hi = 0;
1478     }
1479 }
1480
1481 bool QXcbWindow::setKeyboardGrabEnabled(bool grab)
1482 {
1483     if (!grab) {
1484         xcb_ungrab_keyboard(xcb_connection(), XCB_TIME_CURRENT_TIME);
1485         return true;
1486     }
1487     xcb_grab_keyboard_cookie_t cookie = xcb_grab_keyboard(xcb_connection(), false,
1488                                                           m_window, XCB_TIME_CURRENT_TIME,
1489                                                           XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
1490     xcb_generic_error_t *err;
1491     xcb_grab_keyboard_reply_t *reply = xcb_grab_keyboard_reply(xcb_connection(), cookie, &err);
1492     bool result = !(err || !reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1493     free(reply);
1494     free(err);
1495     return result;
1496 }
1497
1498 bool QXcbWindow::setMouseGrabEnabled(bool grab)
1499 {
1500     if (!grab) {
1501         xcb_ungrab_pointer(xcb_connection(), XCB_TIME_CURRENT_TIME);
1502         return true;
1503     }
1504     xcb_grab_pointer_cookie_t cookie = xcb_grab_pointer(xcb_connection(), false, m_window,
1505                                                         (XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE
1506                                                          | XCB_EVENT_MASK_BUTTON_MOTION | XCB_EVENT_MASK_ENTER_WINDOW
1507                                                          | XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_POINTER_MOTION),
1508                                                         XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
1509                                                         XCB_WINDOW_NONE, XCB_CURSOR_NONE,
1510                                                         XCB_TIME_CURRENT_TIME);
1511     xcb_generic_error_t *err;
1512     xcb_grab_pointer_reply_t *reply = xcb_grab_pointer_reply(xcb_connection(), cookie, &err);
1513     bool result = !(err || !reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1514     free(reply);
1515     free(err);
1516     return result;
1517 }
1518
1519 void QXcbWindow::setCursor(xcb_cursor_t cursor)
1520 {
1521     xcb_change_window_attributes(xcb_connection(), m_window, XCB_CW_CURSOR, &cursor);
1522     xcb_flush(xcb_connection());
1523 }
1524
1525 QT_END_NAMESPACE