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