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