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