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