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