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