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