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