Defer window activation if the window hasn't beenn mapped yet.
[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     updateNetWmUserTime(connection()->time());
553
554     Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
555     xcb_flush(xcb_connection());
556
557     connection()->sync();
558 }
559
560 void QXcbWindow::hide()
561 {
562     Q_XCB_CALL(xcb_unmap_window(xcb_connection(), m_window));
563
564     // send synthetic UnmapNotify event according to icccm 4.1.4
565     xcb_unmap_notify_event_t event;
566     event.response_type = XCB_UNMAP_NOTIFY;
567     event.event = m_screen->root();
568     event.window = m_window;
569     event.from_configure = false;
570     Q_XCB_CALL(xcb_send_event(xcb_connection(), false, m_screen->root(),
571                               XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
572
573     xcb_flush(xcb_connection());
574
575     m_mapped = false;
576 }
577
578 struct QtMotifWmHints {
579     quint32 flags, functions, decorations;
580     qint32 input_mode;
581     quint32 status;
582 };
583
584 enum {
585     MWM_HINTS_FUNCTIONS   = (1L << 0),
586
587     MWM_FUNC_ALL      = (1L << 0),
588     MWM_FUNC_RESIZE   = (1L << 1),
589     MWM_FUNC_MOVE     = (1L << 2),
590     MWM_FUNC_MINIMIZE = (1L << 3),
591     MWM_FUNC_MAXIMIZE = (1L << 4),
592     MWM_FUNC_CLOSE    = (1L << 5),
593
594     MWM_HINTS_DECORATIONS = (1L << 1),
595
596     MWM_DECOR_ALL      = (1L << 0),
597     MWM_DECOR_BORDER   = (1L << 1),
598     MWM_DECOR_RESIZEH  = (1L << 2),
599     MWM_DECOR_TITLE    = (1L << 3),
600     MWM_DECOR_MENU     = (1L << 4),
601     MWM_DECOR_MINIMIZE = (1L << 5),
602     MWM_DECOR_MAXIMIZE = (1L << 6),
603
604     MWM_HINTS_INPUT_MODE = (1L << 2),
605
606     MWM_INPUT_MODELESS                  = 0L,
607     MWM_INPUT_PRIMARY_APPLICATION_MODAL = 1L,
608     MWM_INPUT_FULL_APPLICATION_MODAL    = 3L
609 };
610
611 static QtMotifWmHints getMotifWmHints(QXcbConnection *c, xcb_window_t window)
612 {
613     QtMotifWmHints hints;
614
615     xcb_get_property_cookie_t get_cookie =
616         xcb_get_property(c->xcb_connection(), 0, window, c->atom(QXcbAtom::_MOTIF_WM_HINTS),
617                          c->atom(QXcbAtom::_MOTIF_WM_HINTS), 0, 20);
618
619     xcb_generic_error_t *error;
620
621     xcb_get_property_reply_t *reply =
622         xcb_get_property_reply(c->xcb_connection(), get_cookie, &error);
623
624     if (reply && reply->format == 32 && reply->type == c->atom(QXcbAtom::_MOTIF_WM_HINTS)) {
625         hints = *((QtMotifWmHints *)xcb_get_property_value(reply));
626     } else if (error) {
627         c->handleXcbError(error);
628         free(error);
629
630         hints.flags = 0L;
631         hints.functions = MWM_FUNC_ALL;
632         hints.decorations = MWM_DECOR_ALL;
633         hints.input_mode = 0L;
634         hints.status = 0L;
635     }
636
637     free(reply);
638
639     return hints;
640 }
641
642 static void setMotifWmHints(QXcbConnection *c, xcb_window_t window, const QtMotifWmHints &hints)
643 {
644     if (hints.flags != 0l) {
645         Q_XCB_CALL2(xcb_change_property(c->xcb_connection(),
646                                        XCB_PROP_MODE_REPLACE,
647                                        window,
648                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
649                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
650                                        32,
651                                        5,
652                                        &hints), c);
653     } else {
654         Q_XCB_CALL2(xcb_delete_property(c->xcb_connection(), window, c->atom(QXcbAtom::_MOTIF_WM_HINTS)), c);
655     }
656 }
657
658 void QXcbWindow::printNetWmState(const QVector<xcb_atom_t> &state)
659 {
660     printf("_NET_WM_STATE (%d): ", state.size());
661     for (int i = 0; i < state.size(); ++i) {
662 #define CHECK_WM_STATE(state_atom) \
663         if (state.at(i) == atom(QXcbAtom::state_atom))\
664             printf(#state_atom " ");
665         CHECK_WM_STATE(_NET_WM_STATE_ABOVE)
666         CHECK_WM_STATE(_NET_WM_STATE_BELOW)
667         CHECK_WM_STATE(_NET_WM_STATE_FULLSCREEN)
668         CHECK_WM_STATE(_NET_WM_STATE_MAXIMIZED_HORZ)
669         CHECK_WM_STATE(_NET_WM_STATE_MAXIMIZED_VERT)
670         CHECK_WM_STATE(_NET_WM_STATE_MODAL)
671         CHECK_WM_STATE(_NET_WM_STATE_STAYS_ON_TOP)
672         CHECK_WM_STATE(_NET_WM_STATE_DEMANDS_ATTENTION)
673 #undef CHECK_WM_STATE
674     }
675     printf("\n");
676 }
677
678 QVector<xcb_atom_t> QXcbWindow::getNetWmState()
679 {
680     QVector<xcb_atom_t> result;
681
682     xcb_get_property_cookie_t get_cookie =
683         xcb_get_property(xcb_connection(), 0, m_window, atom(QXcbAtom::_NET_WM_STATE),
684                          XCB_ATOM_ATOM, 0, 1024);
685
686     xcb_generic_error_t *error;
687
688     xcb_get_property_reply_t *reply =
689         xcb_get_property_reply(xcb_connection(), get_cookie, &error);
690
691     if (reply && reply->format == 32 && reply->type == XCB_ATOM_ATOM) {
692         result.resize(reply->length);
693
694         memcpy(result.data(), xcb_get_property_value(reply), reply->length * sizeof(xcb_atom_t));
695
696 #ifdef NET_WM_STATE_DEBUG
697         printf("getting net wm state (%x)\n", m_window);
698         printNetWmState(result);
699 #endif
700
701         free(reply);
702     } else if (error) {
703         connection()->handleXcbError(error);
704         free(error);
705     } else {
706 #ifdef NET_WM_STATE_DEBUG
707         printf("getting net wm state (%x), empty\n", m_window);
708 #endif
709     }
710
711     return result;
712 }
713
714 void QXcbWindow::setNetWmState(const QVector<xcb_atom_t> &atoms)
715 {
716     if (atoms.isEmpty()) {
717         Q_XCB_CALL(xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_STATE)));
718     } else {
719         Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
720                                        atom(QXcbAtom::_NET_WM_STATE), XCB_ATOM_ATOM, 32,
721                                        atoms.count(), atoms.constData()));
722     }
723     xcb_flush(xcb_connection());
724 }
725
726
727 Qt::WindowFlags QXcbWindow::setWindowFlags(Qt::WindowFlags flags)
728 {
729     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
730
731     if (type == Qt::ToolTip)
732         flags |= Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint;
733     if (type == Qt::Popup)
734         flags |= Qt::X11BypassWindowManagerHint;
735
736     if (flags & Qt::WindowTransparentForInput) {
737         uint32_t mask = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_VISIBILITY_CHANGE
738                  | XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_RESIZE_REDIRECT
739                 | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT
740                 | XCB_EVENT_MASK_FOCUS_CHANGE  | XCB_EVENT_MASK_PROPERTY_CHANGE
741                 | XCB_EVENT_MASK_COLOR_MAP_CHANGE | XCB_EVENT_MASK_OWNER_GRAB_BUTTON;
742         xcb_change_window_attributes(xcb_connection(), xcb_window(), XCB_CW_EVENT_MASK, &mask);
743     }
744
745     setNetWmWindowFlags(flags);
746     setMotifWindowFlags(flags);
747
748     setTransparentForMouseEvents(flags & Qt::WindowTransparentForInput);
749     updateDoesNotAcceptFocus(flags & Qt::WindowDoesNotAcceptFocus);
750
751     return flags;
752 }
753
754 void QXcbWindow::setMotifWindowFlags(Qt::WindowFlags flags)
755 {
756     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
757
758     QtMotifWmHints mwmhints;
759     mwmhints.flags = 0L;
760     mwmhints.functions = 0L;
761     mwmhints.decorations = 0;
762     mwmhints.input_mode = 0L;
763     mwmhints.status = 0L;
764
765     if (type != Qt::SplashScreen) {
766         mwmhints.flags |= MWM_HINTS_DECORATIONS;
767
768         bool customize = flags & Qt::CustomizeWindowHint;
769         if (!(flags & Qt::FramelessWindowHint) && !(customize && !(flags & Qt::WindowTitleHint))) {
770             mwmhints.decorations |= MWM_DECOR_BORDER;
771             mwmhints.decorations |= MWM_DECOR_RESIZEH;
772
773             if (flags & Qt::WindowTitleHint)
774                 mwmhints.decorations |= MWM_DECOR_TITLE;
775
776             if (flags & Qt::WindowSystemMenuHint)
777                 mwmhints.decorations |= MWM_DECOR_MENU;
778
779             if (flags & Qt::WindowMinimizeButtonHint) {
780                 mwmhints.decorations |= MWM_DECOR_MINIMIZE;
781                 mwmhints.functions |= MWM_FUNC_MINIMIZE;
782             }
783
784             if (flags & Qt::WindowMaximizeButtonHint) {
785                 mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
786                 mwmhints.functions |= MWM_FUNC_MAXIMIZE;
787             }
788
789             if (flags & Qt::WindowCloseButtonHint)
790                 mwmhints.functions |= MWM_FUNC_CLOSE;
791         }
792     } else {
793         // if type == Qt::SplashScreen
794         mwmhints.decorations = MWM_DECOR_ALL;
795     }
796
797     if (mwmhints.functions != 0) {
798         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
799         mwmhints.functions |= MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
800     } else {
801         mwmhints.functions = MWM_FUNC_ALL;
802     }
803
804     if (!(flags & Qt::FramelessWindowHint)
805         && flags & Qt::CustomizeWindowHint
806         && flags & Qt::WindowTitleHint
807         && !(flags &
808              (Qt::WindowMinimizeButtonHint
809               | Qt::WindowMaximizeButtonHint
810               | Qt::WindowCloseButtonHint)))
811     {
812         // a special case - only the titlebar without any button
813         mwmhints.flags = MWM_HINTS_FUNCTIONS;
814         mwmhints.functions = MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
815         mwmhints.decorations = 0;
816     }
817
818     setMotifWmHints(connection(), m_window, mwmhints);
819 }
820
821 void QXcbWindow::changeNetWmState(bool set, xcb_atom_t one, xcb_atom_t two)
822 {
823     xcb_client_message_event_t event;
824
825     event.response_type = XCB_CLIENT_MESSAGE;
826     event.format = 32;
827     event.window = m_window;
828     event.type = atom(QXcbAtom::_NET_WM_STATE);
829     event.data.data32[0] = set ? 1 : 0;
830     event.data.data32[1] = one;
831     event.data.data32[2] = two;
832     event.data.data32[3] = 0;
833     event.data.data32[4] = 0;
834
835     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));
836 }
837
838 Qt::WindowState QXcbWindow::setWindowState(Qt::WindowState state)
839 {
840     if (state == m_windowState)
841         return state;
842
843     // unset old state
844     switch (m_windowState) {
845     case Qt::WindowMinimized:
846         Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
847         break;
848     case Qt::WindowMaximized:
849         changeNetWmState(false,
850                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
851                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
852         break;
853     case Qt::WindowFullScreen:
854         changeNetWmState(false, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
855         break;
856     default:
857         break;
858     }
859
860     // set new state
861     switch (state) {
862     case Qt::WindowMinimized:
863         {
864             xcb_client_message_event_t event;
865
866             event.response_type = XCB_CLIENT_MESSAGE;
867             event.format = 32;
868             event.window = m_window;
869             event.type = atom(QXcbAtom::WM_CHANGE_STATE);
870             event.data.data32[0] = XCB_WM_STATE_ICONIC;
871             event.data.data32[1] = 0;
872             event.data.data32[2] = 0;
873             event.data.data32[3] = 0;
874             event.data.data32[4] = 0;
875
876             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));
877         }
878         break;
879     case Qt::WindowMaximized:
880         changeNetWmState(true,
881                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
882                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
883         break;
884     case Qt::WindowFullScreen:
885         changeNetWmState(true, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
886         break;
887     case Qt::WindowNoState:
888         break;
889     default:
890         break;
891     }
892
893     connection()->sync();
894
895     m_windowState = state;
896     return m_windowState;
897 }
898
899 void QXcbWindow::setNetWmWindowFlags(Qt::WindowFlags flags)
900 {
901     // in order of decreasing priority
902     QVector<uint> windowTypes;
903
904     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
905
906     switch (type) {
907     case Qt::Dialog:
908     case Qt::Sheet:
909         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_DIALOG));
910         break;
911     case Qt::Tool:
912     case Qt::Drawer:
913         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_UTILITY));
914         break;
915     case Qt::ToolTip:
916         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_TOOLTIP));
917         break;
918     case Qt::SplashScreen:
919         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_SPLASH));
920         break;
921     default:
922         break;
923     }
924
925     if (flags & Qt::FramelessWindowHint)
926         windowTypes.append(atom(QXcbAtom::_KDE_NET_WM_WINDOW_TYPE_OVERRIDE));
927
928     windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_NORMAL));
929
930     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
931                                    atom(QXcbAtom::_NET_WM_WINDOW_TYPE), XCB_ATOM_ATOM, 32,
932                                    windowTypes.count(), windowTypes.constData()));
933 }
934
935 void QXcbWindow::updateMotifWmHintsBeforeMap()
936 {
937     QtMotifWmHints mwmhints = getMotifWmHints(connection(), m_window);
938
939     if (window()->windowModality() != Qt::NonModal) {
940         switch (window()->windowModality()) {
941         case Qt::WindowModal:
942             mwmhints.input_mode = MWM_INPUT_PRIMARY_APPLICATION_MODAL;
943             break;
944         case Qt::ApplicationModal:
945         default:
946             mwmhints.input_mode = MWM_INPUT_FULL_APPLICATION_MODAL;
947             break;
948         }
949         mwmhints.flags |= MWM_HINTS_INPUT_MODE;
950     } else {
951         mwmhints.input_mode = MWM_INPUT_MODELESS;
952         mwmhints.flags &= ~MWM_HINTS_INPUT_MODE;
953     }
954
955     if (window()->minimumSize() == window()->maximumSize()) {
956         // fixed size, remove the resize handle (since mwm/dtwm
957         // isn't smart enough to do it itself)
958         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
959         if (mwmhints.functions == MWM_FUNC_ALL) {
960             mwmhints.functions = MWM_FUNC_MOVE;
961         } else {
962             mwmhints.functions &= ~MWM_FUNC_RESIZE;
963         }
964
965         if (mwmhints.decorations == MWM_DECOR_ALL) {
966             mwmhints.flags |= MWM_HINTS_DECORATIONS;
967             mwmhints.decorations = (MWM_DECOR_BORDER
968                                     | MWM_DECOR_TITLE
969                                     | MWM_DECOR_MENU);
970         } else {
971             mwmhints.decorations &= ~MWM_DECOR_RESIZEH;
972         }
973     }
974
975     if (window()->windowFlags() & Qt::WindowMinimizeButtonHint) {
976         mwmhints.flags |= MWM_HINTS_DECORATIONS;
977         mwmhints.decorations |= MWM_DECOR_MINIMIZE;
978         mwmhints.functions |= MWM_FUNC_MINIMIZE;
979     }
980     if (window()->windowFlags() & Qt::WindowMaximizeButtonHint) {
981         mwmhints.flags |= MWM_HINTS_DECORATIONS;
982         mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
983         mwmhints.functions |= MWM_FUNC_MAXIMIZE;
984     }
985     if (window()->windowFlags() & Qt::WindowCloseButtonHint)
986         mwmhints.functions |= MWM_FUNC_CLOSE;
987
988     setMotifWmHints(connection(), m_window, mwmhints);
989 }
990
991 void QXcbWindow::updateNetWmStateBeforeMap()
992 {
993     QVector<xcb_atom_t> netWmState;
994
995     Qt::WindowFlags flags = window()->windowFlags();
996     if (flags & Qt::WindowStaysOnTopHint) {
997         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_ABOVE));
998         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_STAYS_ON_TOP));
999     } else if (flags & Qt::WindowStaysOnBottomHint) {
1000         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_BELOW));
1001     }
1002
1003     if (window()->windowState() & Qt::WindowFullScreen) {
1004         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
1005     }
1006
1007     if (window()->windowState() & Qt::WindowMaximized) {
1008         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ));
1009         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
1010     }
1011
1012     if (window()->windowModality() != Qt::NonModal) {
1013         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_MODAL));
1014     }
1015
1016     setNetWmState(netWmState);
1017 }
1018
1019 void QXcbWindow::updateNetWmUserTime(xcb_timestamp_t timestamp)
1020 {
1021     xcb_window_t wid = m_window;
1022
1023     const bool isSupportedByWM = connection()->wmSupport()->isSupportedByWM(atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
1024     if (m_netWmUserTimeWindow || isSupportedByWM) {
1025         if (!m_netWmUserTimeWindow) {
1026             m_netWmUserTimeWindow = xcb_generate_id(xcb_connection());
1027             Q_XCB_CALL(xcb_create_window(xcb_connection(),
1028                                          XCB_COPY_FROM_PARENT,            // depth -- same as root
1029                                          m_netWmUserTimeWindow,                        // window id
1030                                          m_window,                   // parent window id
1031                                          -1, -1, 1, 1,
1032                                          0,                               // border width
1033                                          XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
1034                                          m_visualId,                      // visual
1035                                          0,                               // value mask
1036                                          0));                             // value list
1037             wid = m_netWmUserTimeWindow;
1038             xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW),
1039                                 XCB_ATOM_WINDOW, 32, 1, &m_netWmUserTimeWindow);
1040             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME));
1041         } else if (!isSupportedByWM) {
1042             // WM no longer supports it, then we should remove the
1043             // _NET_WM_USER_TIME_WINDOW atom.
1044             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
1045             xcb_destroy_window(xcb_connection(), m_netWmUserTimeWindow);
1046             m_netWmUserTimeWindow = XCB_NONE;
1047         } else {
1048             wid = m_netWmUserTimeWindow;
1049         }
1050     }
1051     xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, wid, atom(QXcbAtom::_NET_WM_USER_TIME),
1052                         XCB_ATOM_CARDINAL, 32, 1, &timestamp);
1053 }
1054
1055 void QXcbWindow::setTransparentForMouseEvents(bool transparent)
1056 {
1057     if (transparent == m_transparent)
1058         return;
1059
1060     xcb_rectangle_t rectangle;
1061
1062     xcb_rectangle_t *rect = 0;
1063     int nrect = 0;
1064
1065     if (!transparent) {
1066         rectangle.x = 0;
1067         rectangle.y = 0;
1068         rectangle.width = geometry().width();
1069         rectangle.height = geometry().height();
1070         rect = &rectangle;
1071         nrect = 1;
1072     }
1073
1074     xcb_xfixes_region_t region = xcb_generate_id(xcb_connection());
1075     xcb_xfixes_create_region(xcb_connection(), region, nrect, rect);
1076     xcb_xfixes_set_window_shape_region_checked(xcb_connection(), m_window, XCB_SHAPE_SK_INPUT, 0, 0, region);
1077     xcb_xfixes_destroy_region(xcb_connection(), region);
1078
1079     m_transparent = transparent;
1080 }
1081
1082 void QXcbWindow::updateDoesNotAcceptFocus(bool doesNotAcceptFocus)
1083 {
1084     xcb_get_property_cookie_t cookie = xcb_get_wm_hints(xcb_connection(), m_window);
1085
1086     xcb_generic_error_t *error;
1087
1088     xcb_wm_hints_t hints;
1089     xcb_get_wm_hints_reply(xcb_connection(), cookie, &hints, &error);
1090
1091     if (error) {
1092         connection()->handleXcbError(error);
1093         free(error);
1094         return;
1095     }
1096
1097     xcb_wm_hints_set_input(&hints, !doesNotAcceptFocus);
1098     xcb_set_wm_hints(xcb_connection(), m_window, &hints);
1099 }
1100
1101 WId QXcbWindow::winId() const
1102 {
1103     return m_window;
1104 }
1105
1106 void QXcbWindow::setParent(const QPlatformWindow *parent)
1107 {
1108     // re-create for compatibility
1109     create();
1110
1111     QPoint topLeft = geometry().topLeft();
1112
1113     xcb_window_t xcb_parent_id = parent ? static_cast<const QXcbWindow *>(parent)->xcb_window() : m_screen->root();
1114     Q_XCB_CALL(xcb_reparent_window(xcb_connection(), xcb_window(), xcb_parent_id, topLeft.x(), topLeft.y()));
1115 }
1116
1117 void QXcbWindow::setWindowTitle(const QString &title)
1118 {
1119     QByteArray ba = title.toUtf8();
1120     Q_XCB_CALL(xcb_change_property(xcb_connection(),
1121                                    XCB_PROP_MODE_REPLACE,
1122                                    m_window,
1123                                    atom(QXcbAtom::_NET_WM_NAME),
1124                                    atom(QXcbAtom::UTF8_STRING),
1125                                    8,
1126                                    ba.length(),
1127                                    ba.constData()));
1128 }
1129
1130 void QXcbWindow::raise()
1131 {
1132     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1133     const quint32 values[] = { XCB_STACK_MODE_ABOVE };
1134     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1135 }
1136
1137 void QXcbWindow::lower()
1138 {
1139     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1140     const quint32 values[] = { XCB_STACK_MODE_BELOW };
1141     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1142 }
1143
1144 void QXcbWindow::propagateSizeHints()
1145 {
1146     // update WM_NORMAL_HINTS
1147     xcb_size_hints_t hints;
1148     memset(&hints, 0, sizeof(hints));
1149
1150     QRect rect = geometry();
1151
1152     QWindow *win = window();
1153
1154     xcb_size_hints_set_position(&hints, true, rect.x(), rect.y());
1155     xcb_size_hints_set_size(&hints, true, rect.width(), rect.height());
1156     xcb_size_hints_set_win_gravity(&hints, qt_window_private(win)->positionPolicy == QWindowPrivate::WindowFrameInclusive
1157                                            ? XCB_GRAVITY_NORTH_WEST : XCB_GRAVITY_STATIC);
1158
1159     QSize minimumSize = win->minimumSize();
1160     QSize maximumSize = win->maximumSize();
1161     QSize baseSize = win->baseSize();
1162     QSize sizeIncrement = win->sizeIncrement();
1163
1164     if (minimumSize.width() > 0 || minimumSize.height() > 0)
1165         xcb_size_hints_set_min_size(&hints, minimumSize.width(), minimumSize.height());
1166
1167     if (maximumSize.width() < QWINDOWSIZE_MAX || maximumSize.height() < QWINDOWSIZE_MAX)
1168         xcb_size_hints_set_max_size(&hints,
1169                                     qMin(XCOORD_MAX, maximumSize.width()),
1170                                     qMin(XCOORD_MAX, maximumSize.height()));
1171
1172     if (sizeIncrement.width() > 0 || sizeIncrement.height() > 0) {
1173         xcb_size_hints_set_base_size(&hints, baseSize.width(), baseSize.height());
1174         xcb_size_hints_set_resize_inc(&hints, sizeIncrement.width(), sizeIncrement.height());
1175     }
1176
1177     xcb_set_wm_normal_hints(xcb_connection(), m_window, &hints);
1178 }
1179
1180 void QXcbWindow::requestActivateWindow()
1181 {
1182     if (!m_mapped) {
1183         m_deferredActivation = true;
1184         return;
1185     }
1186     m_deferredActivation = false;
1187
1188     updateNetWmUserTime(connection()->time());
1189
1190     if (window()->isTopLevel()
1191         && connection()->wmSupport()->isSupportedByWM(atom(QXcbAtom::_NET_ACTIVE_WINDOW))) {
1192         xcb_client_message_event_t event;
1193
1194         event.response_type = XCB_CLIENT_MESSAGE;
1195         event.format = 32;
1196         event.window = m_window;
1197         event.type = atom(QXcbAtom::_NET_ACTIVE_WINDOW);
1198         event.data.data32[0] = 1;
1199         event.data.data32[1] = connection()->time();
1200         QWindow *focusWindow = QGuiApplication::focusWindow();
1201         event.data.data32[2] = focusWindow ? focusWindow->winId() : XCB_NONE;
1202         event.data.data32[3] = 0;
1203         event.data.data32[4] = 0;
1204
1205         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));
1206     } else {
1207         Q_XCB_CALL(xcb_set_input_focus(xcb_connection(), XCB_INPUT_FOCUS_PARENT, m_window, connection()->time()));
1208     }
1209
1210     connection()->sync();
1211 }
1212
1213 #if XCB_USE_MAEMO_WINDOW_PROPERTIES
1214 void QXcbWindow::setOrientation(Qt::ScreenOrientation orientation)
1215 {
1216     int angle = 0;
1217     switch (orientation) {
1218         case Qt::PortraitOrientation: angle = 270; break;
1219         case Qt::LandscapeOrientation: angle = 0; break;
1220         case Qt::InvertedPortraitOrientation: angle = 90; break;
1221         case Qt::InvertedLandscapeOrientation: angle = 180; break;
1222         case Qt::PrimaryOrientation: break;
1223     }
1224     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
1225                                    atom(QXcbAtom::MeegoTouchOrientationAngle), XCB_ATOM_CARDINAL, 32,
1226                                    1, &angle));
1227 }
1228 #endif
1229
1230 QSurfaceFormat QXcbWindow::format() const
1231 {
1232     // ### return actual format
1233     return m_format;
1234 }
1235
1236 #if defined(XCB_USE_EGL)
1237 QXcbEGLSurface *QXcbWindow::eglSurface() const
1238 {
1239     if (!m_eglSurface) {
1240         EGLDisplay display = connection()->egl_display();
1241         EGLConfig config = q_configFromGLFormat(display, window()->requestedFormat(), true);
1242         EGLSurface surface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)m_window, 0);
1243
1244         m_eglSurface = new QXcbEGLSurface(display, surface);
1245     }
1246
1247     return m_eglSurface;
1248 }
1249 #endif
1250
1251 void QXcbWindow::handleExposeEvent(const xcb_expose_event_t *event)
1252 {
1253     QRect rect(event->x, event->y, event->width, event->height);
1254
1255     if (m_exposeRegion.isEmpty())
1256         m_exposeRegion = rect;
1257     else
1258         m_exposeRegion |= rect;
1259
1260     // if count is non-zero there are more expose events pending
1261     if (event->count == 0) {
1262         QWindowSystemInterface::handleSynchronousExposeEvent(window(), m_exposeRegion);
1263         m_exposeRegion = QRegion();
1264     }
1265 }
1266
1267 void QXcbWindow::handleClientMessageEvent(const xcb_client_message_event_t *event)
1268 {
1269     if (event->format != 32)
1270         return;
1271
1272     if (event->type == atom(QXcbAtom::WM_PROTOCOLS)) {
1273         if (event->data.data32[0] == atom(QXcbAtom::WM_DELETE_WINDOW)) {
1274             QWindowSystemInterface::handleCloseEvent(window());
1275         } else if (event->data.data32[0] == atom(QXcbAtom::WM_TAKE_FOCUS)) {
1276             connection()->setTime(event->data.data32[1]);
1277         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_PING)) {
1278             xcb_client_message_event_t reply = *event;
1279
1280             reply.response_type = XCB_CLIENT_MESSAGE;
1281             reply.window = m_screen->root();
1282
1283             xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&reply);
1284             xcb_flush(xcb_connection());
1285         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_SYNC_REQUEST)) {
1286             connection()->setTime(event->data.data32[1]);
1287             m_syncValue.lo = event->data.data32[2];
1288             m_syncValue.hi = event->data.data32[3];
1289         } else {
1290             qWarning() << "QXcbWindow: Unhandled WM_PROTOCOLS message:" << connection()->atomName(event->data.data32[0]);
1291         }
1292     } else if (event->type == atom(QXcbAtom::XdndEnter)) {
1293         connection()->drag()->handleEnter(window(), event);
1294     } else if (event->type == atom(QXcbAtom::XdndPosition)) {
1295         connection()->drag()->handlePosition(window(), event);
1296     } else if (event->type == atom(QXcbAtom::XdndLeave)) {
1297         connection()->drag()->handleLeave(window(), event);
1298     } else if (event->type == atom(QXcbAtom::XdndDrop)) {
1299         connection()->drag()->handleDrop(window(), event);
1300     } else {
1301         qWarning() << "QXcbWindow: Unhandled client message:" << connection()->atomName(event->type);
1302     }
1303 }
1304
1305 void QXcbWindow::handleConfigureNotifyEvent(const xcb_configure_notify_event_t *event)
1306 {
1307     bool fromSendEvent = (event->response_type & 0x80);
1308     QPoint pos(event->x, event->y);
1309     if (!fromSendEvent) {
1310         // Do not trust the position, query it instead.
1311         xcb_translate_coordinates_cookie_t cookie = xcb_translate_coordinates(xcb_connection(), xcb_window(),
1312                                                                               m_screen->root(), 0, 0);
1313         xcb_generic_error_t *error;
1314         xcb_translate_coordinates_reply_t *reply = xcb_translate_coordinates_reply(xcb_connection(), cookie, &error);
1315         if (reply) {
1316             pos.setX(reply->dst_x);
1317             pos.setY(reply->dst_y);
1318             free(reply);
1319         } else if (error) {
1320             free(error);
1321         }
1322     }
1323
1324     QRect rect(pos, QSize(event->width, event->height));
1325
1326     QPlatformWindow::setGeometry(rect);
1327     QWindowSystemInterface::handleGeometryChange(window(), rect);
1328
1329     m_dirtyFrameMargins = true;
1330
1331 #if XCB_USE_DRI2
1332     if (m_context)
1333         static_cast<QDri2Context *>(m_context)->resize(rect.size());
1334 #endif
1335 }
1336
1337 void QXcbWindow::handleMapNotifyEvent(const xcb_map_notify_event_t *event)
1338 {
1339     if (event->window == m_window) {
1340         m_mapped = true;
1341         if (m_deferredActivation)
1342             requestActivateWindow();
1343         QWindowSystemInterface::handleMapEvent(window());
1344     }
1345 }
1346
1347 void QXcbWindow::handleUnmapNotifyEvent(const xcb_unmap_notify_event_t *event)
1348 {
1349     if (event->window == m_window) {
1350         m_mapped = false;
1351         QWindowSystemInterface::handleUnmapEvent(window());
1352     }
1353 }
1354
1355 static Qt::MouseButtons translateMouseButtons(int s)
1356 {
1357     Qt::MouseButtons ret = 0;
1358     if (s & XCB_BUTTON_MASK_1)
1359         ret |= Qt::LeftButton;
1360     if (s & XCB_BUTTON_MASK_2)
1361         ret |= Qt::MidButton;
1362     if (s & XCB_BUTTON_MASK_3)
1363         ret |= Qt::RightButton;
1364     return ret;
1365 }
1366
1367 static Qt::MouseButton translateMouseButton(xcb_button_t s)
1368 {
1369     switch (s) {
1370     case 1: return Qt::LeftButton;
1371     case 2: return Qt::MidButton;
1372     case 3: return Qt::RightButton;
1373     // Button values 4-7 were already handled as Wheel events, and won't occur here.
1374     case 8: return Qt::BackButton;      // Also known as Qt::ExtraButton1
1375     case 9: return Qt::ForwardButton;   // Also known as Qt::ExtraButton2
1376     case 10: return Qt::ExtraButton3;
1377     case 11: return Qt::ExtraButton4;
1378     case 12: return Qt::ExtraButton5;
1379     case 13: return Qt::ExtraButton6;
1380     case 14: return Qt::ExtraButton7;
1381     case 15: return Qt::ExtraButton8;
1382     case 16: return Qt::ExtraButton9;
1383     case 17: return Qt::ExtraButton10;
1384     case 18: return Qt::ExtraButton11;
1385     case 19: return Qt::ExtraButton12;
1386     case 20: return Qt::ExtraButton13;
1387     case 21: return Qt::ExtraButton14;
1388     case 22: return Qt::ExtraButton15;
1389     case 23: return Qt::ExtraButton16;
1390     case 24: return Qt::ExtraButton17;
1391     case 25: return Qt::ExtraButton18;
1392     case 26: return Qt::ExtraButton19;
1393     case 27: return Qt::ExtraButton20;
1394     case 28: return Qt::ExtraButton21;
1395     case 29: return Qt::ExtraButton22;
1396     case 30: return Qt::ExtraButton23;
1397     case 31: return Qt::ExtraButton24;
1398     default: return Qt::NoButton;
1399     }
1400 }
1401
1402 void QXcbWindow::handleButtonPressEvent(const xcb_button_press_event_t *event)
1403 {
1404     updateNetWmUserTime(event->time);
1405
1406     QPoint local(event->event_x, event->event_y);
1407     QPoint global(event->root_x, event->root_y);
1408
1409     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1410
1411     if (event->detail >= 4 && event->detail <= 7) {
1412         // Logic borrowed from qapplication_x11.cpp
1413         int delta = 120 * ((event->detail == 4 || event->detail == 6) ? 1 : -1);
1414         bool hor = (((event->detail == 4 || event->detail == 5)
1415                      && (modifiers & Qt::AltModifier))
1416                     || (event->detail == 6 || event->detail == 7));
1417
1418         QWindowSystemInterface::handleWheelEvent(window(), event->time,
1419                                                  local, global, delta, hor ? Qt::Horizontal : Qt::Vertical, modifiers);
1420         return;
1421     }
1422
1423     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1424 }
1425
1426 void QXcbWindow::handleButtonReleaseEvent(const xcb_button_release_event_t *event)
1427 {
1428     QPoint local(event->event_x, event->event_y);
1429     QPoint global(event->root_x, event->root_y);
1430     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1431
1432     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1433 }
1434
1435 void QXcbWindow::handleMotionNotifyEvent(const xcb_motion_notify_event_t *event)
1436 {
1437     QPoint local(event->event_x, event->event_y);
1438     QPoint global(event->root_x, event->root_y);
1439     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1440
1441     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1442 }
1443
1444 void QXcbWindow::handleMouseEvent(xcb_button_t detail, uint16_t state, xcb_timestamp_t time, const QPoint &local, const QPoint &global, Qt::KeyboardModifiers modifiers)
1445 {
1446     connection()->setTime(time);
1447
1448     Qt::MouseButtons buttons = translateMouseButtons(state);
1449     Qt::MouseButton button = translateMouseButton(detail);
1450
1451     buttons ^= button; // X event uses state *before*, Qt uses state *after*
1452
1453     QWindowSystemInterface::handleMouseEvent(window(), time, local, global, buttons, modifiers);
1454 }
1455
1456 void QXcbWindow::handleEnterNotifyEvent(const xcb_enter_notify_event_t *event)
1457 {
1458     connection()->setTime(event->time);
1459
1460     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1461         || event->detail == XCB_NOTIFY_DETAIL_VIRTUAL
1462         || event->detail == XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL)
1463     {
1464         return;
1465     }
1466
1467     QWindowSystemInterface::handleEnterEvent(window());
1468 }
1469
1470 void QXcbWindow::handleLeaveNotifyEvent(const xcb_leave_notify_event_t *event)
1471 {
1472     connection()->setTime(event->time);
1473
1474     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1475         || event->detail == XCB_NOTIFY_DETAIL_INFERIOR)
1476     {
1477         return;
1478     }
1479
1480     QWindowSystemInterface::handleLeaveEvent(window());
1481 }
1482
1483 void QXcbWindow::handlePropertyNotifyEvent(const xcb_property_notify_event_t *event)
1484 {
1485     connection()->setTime(event->time);
1486
1487     bool propertyDeleted = event->state == XCB_PROPERTY_DELETE;
1488
1489     if (event->atom == atom(QXcbAtom::_NET_WM_STATE) || event->atom == atom(QXcbAtom::WM_STATE)) {
1490         if (propertyDeleted)
1491             return;
1492
1493         xcb_get_property_cookie_t get_cookie =
1494             xcb_get_property(xcb_connection(), 0, m_window, atom(QXcbAtom::WM_STATE),
1495                              XCB_ATOM_ANY, 0, 1024);
1496
1497         xcb_generic_error_t *error;
1498
1499         xcb_get_property_reply_t *reply =
1500             xcb_get_property_reply(xcb_connection(), get_cookie, &error);
1501
1502         xcb_atom_t wm_state = XCB_WM_STATE_WITHDRAWN;
1503         if (reply && reply->format == 32 && reply->type == atom(QXcbAtom::WM_STATE)) {
1504             if (reply->length != 0)
1505                 wm_state = ((long *)xcb_get_property_value(reply))[0];
1506             free(reply);
1507         } else if (error) {
1508             connection()->handleXcbError(error);
1509             free(error);
1510         }
1511
1512         QVector<xcb_atom_t> netWmState = getNetWmState();
1513
1514         bool maximized = netWmState.contains(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ))
1515             && netWmState.contains(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
1516         bool fullscreen = netWmState.contains(atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
1517
1518         Qt::WindowState state = Qt::WindowNoState;
1519         if (wm_state == XCB_WM_STATE_ICONIC)
1520             state = Qt::WindowMinimized;
1521         else if (maximized)
1522             state = Qt::WindowMaximized;
1523         else if (fullscreen)
1524             state = Qt::WindowFullScreen;
1525
1526         QWindowSystemInterface::handleWindowStateChanged(window(), state);
1527     }
1528 }
1529
1530 void QXcbWindow::handleFocusInEvent(const xcb_focus_in_event_t *)
1531 {
1532     QWindowSystemInterface::handleWindowActivated(window());
1533 }
1534
1535 static bool focusInPeeker(xcb_generic_event_t *event)
1536 {
1537     if (!event) {
1538         // FocusIn event is not in the queue, proceed with FocusOut normally.
1539         QWindowSystemInterface::handleWindowActivated(0);
1540         return true;
1541     }
1542     uint response_type = event->response_type & ~0x80;
1543     return response_type == XCB_FOCUS_IN;
1544 }
1545
1546 void QXcbWindow::handleFocusOutEvent(const xcb_focus_out_event_t *)
1547 {
1548     // Do not set the active window to 0 if there is a FocusIn coming.
1549     // There is however no equivalent for XPutBackEvent so register a
1550     // callback for QXcbConnection instead.
1551     connection()->addPeekFunc(focusInPeeker);
1552 }
1553
1554 void QXcbWindow::updateSyncRequestCounter()
1555 {
1556     if (m_screen->syncRequestSupported() && (m_syncValue.lo != 0 || m_syncValue.hi != 0)) {
1557         Q_XCB_CALL(xcb_sync_set_counter(xcb_connection(), m_syncCounter, m_syncValue));
1558         xcb_flush(xcb_connection());
1559         connection()->sync();
1560
1561         m_syncValue.lo = 0;
1562         m_syncValue.hi = 0;
1563     }
1564 }
1565
1566 bool QXcbWindow::setKeyboardGrabEnabled(bool grab)
1567 {
1568     if (!grab) {
1569         xcb_ungrab_keyboard(xcb_connection(), XCB_TIME_CURRENT_TIME);
1570         return true;
1571     }
1572     xcb_grab_keyboard_cookie_t cookie = xcb_grab_keyboard(xcb_connection(), false,
1573                                                           m_window, XCB_TIME_CURRENT_TIME,
1574                                                           XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
1575     xcb_generic_error_t *err;
1576     xcb_grab_keyboard_reply_t *reply = xcb_grab_keyboard_reply(xcb_connection(), cookie, &err);
1577     bool result = !(err || !reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1578     free(reply);
1579     free(err);
1580     return result;
1581 }
1582
1583 bool QXcbWindow::setMouseGrabEnabled(bool grab)
1584 {
1585     if (!grab) {
1586         xcb_ungrab_pointer(xcb_connection(), XCB_TIME_CURRENT_TIME);
1587         return true;
1588     }
1589     xcb_grab_pointer_cookie_t cookie = xcb_grab_pointer(xcb_connection(), false, m_window,
1590                                                         (XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE
1591                                                          | XCB_EVENT_MASK_BUTTON_MOTION | XCB_EVENT_MASK_ENTER_WINDOW
1592                                                          | XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_POINTER_MOTION),
1593                                                         XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
1594                                                         XCB_WINDOW_NONE, XCB_CURSOR_NONE,
1595                                                         XCB_TIME_CURRENT_TIME);
1596     xcb_generic_error_t *err;
1597     xcb_grab_pointer_reply_t *reply = xcb_grab_pointer_reply(xcb_connection(), cookie, &err);
1598     bool result = !(err || !reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1599     free(reply);
1600     free(err);
1601     return result;
1602 }
1603
1604 void QXcbWindow::setCursor(xcb_cursor_t cursor)
1605 {
1606     xcb_change_window_attributes(xcb_connection(), m_window, XCB_CW_CURSOR, &cursor);
1607     xcb_flush(xcb_connection());
1608 }
1609
1610 QT_END_NAMESPACE