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