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