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