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