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