Revert "Move QWindowSystemInterface out of qpa."
[profile/ivi/qtbase.git] / src / plugins / platforms / xcb / qxcbdrag.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 QtGui module 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 "qxcbdrag.h"
43 #include <xcb/xcb.h>
44 #include "qxcbconnection.h"
45 #include "qxcbclipboard.h"
46 #include "qxcbmime.h"
47 #include "qxcbwindow.h"
48 #include "qxcbscreen.h"
49 #include "qwindow.h"
50 #include <private/qdnd_p.h>
51 #include <qdebug.h>
52 #include <qevent.h>
53 #include <qguiapplication.h>
54 #include <qrect.h>
55 #include <qpainter.h>
56
57 #include <qpa/qwindowsysteminterface.h>
58
59 #include <QtPlatformSupport/private/qshapedpixmapdndwindow_p.h>
60 #include <QtPlatformSupport/private/qsimpledrag_p.h>
61
62 QT_BEGIN_NAMESPACE
63
64 #ifndef QT_NO_DRAGANDDROP
65
66 //#define DND_DEBUG
67 #ifdef DND_DEBUG
68 #define DEBUG qDebug
69 #else
70 #define DEBUG if(0) qDebug
71 #endif
72
73 #ifdef DND_DEBUG
74 #define DNDDEBUG qDebug()
75 #else
76 #define DNDDEBUG if(0) qDebug()
77 #endif
78
79 const int xdnd_version = 5;
80
81 static inline xcb_window_t xcb_window(QWindow *w)
82 {
83     return static_cast<QXcbWindow *>(w->handle())->xcb_window();
84 }
85
86
87 static xcb_window_t xdndProxy(QXcbConnection *c, xcb_window_t w)
88 {
89     xcb_window_t proxy = XCB_NONE;
90
91     xcb_get_property_cookie_t cookie = Q_XCB_CALL2(xcb_get_property(c->xcb_connection(), false, w, c->atom(QXcbAtom::XdndProxy),
92                                                         XCB_ATOM_WINDOW, 0, 1), c);
93     xcb_get_property_reply_t *reply = xcb_get_property_reply(c->xcb_connection(), cookie, 0);
94
95     if (reply && reply->type == XCB_ATOM_WINDOW)
96         proxy = *((xcb_window_t *)xcb_get_property_value(reply));
97     free(reply);
98
99     if (proxy == XCB_NONE)
100         return proxy;
101
102     // exists and is real?
103     cookie = Q_XCB_CALL2(xcb_get_property(c->xcb_connection(), false, proxy, c->atom(QXcbAtom::XdndProxy),
104                                                         XCB_ATOM_WINDOW, 0, 1), c);
105     reply = xcb_get_property_reply(c->xcb_connection(), cookie, 0);
106
107     if (reply && reply->type == XCB_ATOM_WINDOW) {
108         xcb_window_t p = *((xcb_window_t *)xcb_get_property_value(reply));
109         if (proxy != p)
110             proxy = 0;
111     } else {
112         proxy = 0;
113     }
114
115     free(reply);
116
117     return proxy;
118 }
119
120 class QXcbDropData : public QXcbMime
121 {
122 public:
123     QXcbDropData(QXcbDrag *d);
124     ~QXcbDropData();
125
126 protected:
127     bool hasFormat_sys(const QString &mimeType) const;
128     QStringList formats_sys() const;
129     QVariant retrieveData_sys(const QString &mimeType, QVariant::Type type) const;
130
131     QVariant xdndObtainData(const QByteArray &format, QVariant::Type requestedType) const;
132
133     QXcbDrag *drag;
134 };
135
136
137 QXcbDrag::QXcbDrag(QXcbConnection *c) : QXcbObject(c)
138 {
139     dropData = new QXcbDropData(this);
140
141     init();
142     heartbeat = -1;
143
144     transaction_expiry_timer = -1;
145 }
146
147 QXcbDrag::~QXcbDrag()
148 {
149     delete dropData;
150 }
151
152 void QXcbDrag::init()
153 {
154     currentWindow.clear();
155
156     accepted_drop_action = Qt::IgnoreAction;
157
158     xdnd_dragsource = XCB_NONE;
159
160     waiting_for_status = false;
161     current_target = XCB_NONE;
162     current_proxy_target = XCB_NONE;
163
164     source_time = XCB_CURRENT_TIME;
165     target_time = XCB_CURRENT_TIME;
166
167     current_screen = 0;
168     drag_types.clear();
169 }
170
171 QMimeData *QXcbDrag::platformDropData()
172 {
173     return dropData;
174 }
175
176 void QXcbDrag::startDrag()
177 {
178     // #fixme enableEventFilter();
179
180     init();
181
182     heartbeat = startTimer(200);
183
184
185     xcb_set_selection_owner(xcb_connection(), connection()->clipboard()->owner(),
186                             atom(QXcbAtom::XdndSelection), connection()->time());
187
188     QStringList fmts = QXcbMime::formatsHelper(drag()->mimeData());
189     for (int i = 0; i < fmts.size(); ++i) {
190         QList<xcb_atom_t> atoms = QXcbMime::mimeAtomsForFormat(connection(), fmts.at(i));
191         for (int j = 0; j < atoms.size(); ++j) {
192             if (!drag_types.contains(atoms.at(j)))
193                 drag_types.append(atoms.at(j));
194         }
195     }
196     if (drag_types.size() > 3)
197         xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, connection()->clipboard()->owner(),
198                             atom(QXcbAtom::XdndTypelist),
199                             XCB_ATOM_ATOM, 32, drag_types.size(), (const void *)drag_types.constData());
200     QBasicDrag::startDrag();
201 }
202
203 void QXcbDrag::endDrag()
204 {
205     if (heartbeat != -1) {
206         killTimer(heartbeat);
207         heartbeat = -1;
208     }
209     QBasicDrag::endDrag();
210 }
211
212 static xcb_translate_coordinates_reply_t *
213 translateCoordinates(QXcbConnection *c, xcb_window_t from, xcb_window_t to, int x, int y)
214 {
215     xcb_translate_coordinates_cookie_t cookie =
216             xcb_translate_coordinates(c->xcb_connection(), from, to, x, y);
217     return xcb_translate_coordinates_reply(c->xcb_connection(), cookie, 0);
218 }
219
220 static
221 bool windowInteractsWithPosition(xcb_connection_t *connection, const QPoint & pos, xcb_window_t w, xcb_shape_sk_t shapeType)
222 {
223     bool interacts = false;
224     xcb_shape_get_rectangles_reply_t *reply = xcb_shape_get_rectangles_reply(connection, xcb_shape_get_rectangles(connection, w, shapeType), NULL);
225     if (reply) {
226         xcb_rectangle_t *rectangles = xcb_shape_get_rectangles_rectangles(reply);
227         if (rectangles) {
228             const int nRectangles = xcb_shape_get_rectangles_rectangles_length(reply);
229             for (int i = 0; !interacts && i < nRectangles; ++i) {
230                 interacts = QRect(rectangles[i].x, rectangles[i].y, rectangles[i].width, rectangles[i].height).contains(pos);
231             }
232         }
233         free(reply);
234     }
235
236     return interacts;
237 }
238
239 xcb_window_t QXcbDrag::findRealWindow(const QPoint & pos, xcb_window_t w, int md, bool ignoreNonXdndAwareWindows)
240 {
241     if (w == shapedPixmapWindow()->handle()->winId())
242         return 0;
243
244     if (md) {
245         xcb_get_window_attributes_cookie_t cookie = xcb_get_window_attributes(xcb_connection(), w);
246         xcb_get_window_attributes_reply_t *reply = xcb_get_window_attributes_reply(xcb_connection(), cookie, 0);
247         if (!reply)
248             return 0;
249
250         if (reply->map_state != XCB_MAP_STATE_VIEWABLE)
251             return 0;
252
253         xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(xcb_connection(), w);
254         xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(xcb_connection(), gcookie, 0);
255         if (reply && QRect(greply->x, greply->y, greply->width, greply->height).contains(pos)) {
256             bool windowContainsMouse = !ignoreNonXdndAwareWindows;
257             {
258                 xcb_get_property_cookie_t cookie =
259                         Q_XCB_CALL(xcb_get_property(xcb_connection(), false, w, connection()->atom(QXcbAtom::XdndAware),
260                                                     XCB_GET_PROPERTY_TYPE_ANY, 0, 0));
261                 xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0);
262
263                 bool isAware = reply && reply->type != XCB_NONE;
264                 free(reply);
265                 if (isAware) {
266                     const QPoint relPos = pos - QPoint(greply->x, greply->y);
267                     // When ShapeInput and ShapeBounding are not set they return a single rectangle with the geometry of the window, this is why we
268                     // need to check both here so that in the case one is set and the other is not we still get the correct result.
269                     if (connection()->hasInputShape())
270                         windowContainsMouse = windowInteractsWithPosition(xcb_connection(), relPos, w, XCB_SHAPE_SK_INPUT);
271                     if (windowContainsMouse && connection()->hasXShape())
272                         windowContainsMouse = windowInteractsWithPosition(xcb_connection(), relPos, w, XCB_SHAPE_SK_BOUNDING);
273                     if (!connection()->hasInputShape() && !connection()->hasXShape())
274                         windowContainsMouse = true;
275                     if (windowContainsMouse)
276                         return w;
277                 }
278             }
279
280             xcb_query_tree_cookie_t cookie = xcb_query_tree (xcb_connection(), w);
281             xcb_query_tree_reply_t *reply = xcb_query_tree_reply(xcb_connection(), cookie, 0);
282
283             if (!reply)
284                 return 0;
285             int nc = xcb_query_tree_children_length(reply);
286             xcb_window_t *c = xcb_query_tree_children(reply);
287
288             xcb_window_t r = 0;
289             for (uint i = nc; !r && i--;)
290                 r = findRealWindow(pos - QPoint(greply->x, greply->y), c[i], md-1, ignoreNonXdndAwareWindows);
291
292             free(reply);
293             if (r)
294                 return r;
295
296             // We didn't find a client window!  Just use the
297             // innermost window.
298
299             // No children!
300             if (!windowContainsMouse)
301                 return 0;
302             else
303                 return w;
304         }
305     }
306     return 0;
307 }
308
309 void QXcbDrag::move(const QMouseEvent *me)
310 {
311     QBasicDrag::move(me);
312     QPoint globalPos = me->globalPos();
313
314     if (source_sameanswer.contains(globalPos) && source_sameanswer.isValid())
315         return;
316
317     const QList<QXcbScreen *> &screens = connection()->screens();
318     QXcbScreen *screen = screens.at(connection()->primaryScreen());
319     for (int i = 0; i < screens.size(); ++i) {
320         if (screens.at(i)->geometry().contains(globalPos)) {
321             screen = screens.at(i);
322             break;
323         }
324     }
325     if (screen != current_screen) {
326         // ### need to recreate the shaped pixmap window?
327 //    int screen = QCursor::x11Screen();
328 //    if ((qt_xdnd_current_screen == -1 && screen != X11->defaultScreen) || (screen != qt_xdnd_current_screen)) {
329 //        // recreate the pixmap on the new screen...
330 //        delete xdnd_data.deco;
331 //        QWidget* parent = object->source()->window()->x11Info().screen() == screen
332 //            ? object->source()->window() : QApplication::desktop()->screen(screen);
333 //        xdnd_data.deco = new QShapedPixmapWidget(parent);
334 //        if (!QWidget::mouseGrabber()) {
335 //            updatePixmap();
336 //            xdnd_data.deco->grabMouse();
337 //        }
338 //    }
339 //    xdnd_data.deco->move(QCursor::pos() - xdnd_data.deco->pm_hot);
340         current_screen = screen;
341     }
342
343
344 //    qt_xdnd_current_screen = screen;
345     xcb_window_t rootwin = current_screen->root();
346     xcb_translate_coordinates_reply_t *translate =
347             ::translateCoordinates(connection(), rootwin, rootwin, globalPos.x(), globalPos.y());
348     if (!translate)
349         return;
350
351     xcb_window_t target = translate->child;
352     int lx = translate->dst_x;
353     int ly = translate->dst_y;
354     free (translate);
355
356     if (target && target != rootwin) {
357         xcb_window_t src = rootwin;
358         while (target != 0) {
359             DNDDEBUG << "checking target for XdndAware" << target << lx << ly;
360
361             // translate coordinates
362             translate = ::translateCoordinates(connection(), src, target, lx, ly);
363             if (!translate) {
364                 target = 0;
365                 break;
366             }
367             lx = translate->dst_x;
368             ly = translate->dst_y;
369             src = target;
370             xcb_window_t child = translate->child;
371             free(translate);
372
373             // check if it has XdndAware
374             xcb_get_property_cookie_t cookie = Q_XCB_CALL(xcb_get_property(xcb_connection(), false, target,
375                                                           atom(QXcbAtom::XdndAware), XCB_GET_PROPERTY_TYPE_ANY, 0, 0));
376             xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0);
377             bool aware = reply && reply->type != XCB_NONE;
378             free(reply);
379             if (aware) {
380                 DNDDEBUG << "Found XdndAware on " << target;
381                 break;
382             }
383
384             target = child;
385         }
386
387         if (!target || target == shapedPixmapWindow()->handle()->winId()) {
388             DNDDEBUG << "need to find real window";
389             target = findRealWindow(globalPos, rootwin, 6, true);
390             if (target == 0)
391                 target = findRealWindow(globalPos, rootwin, 6, false);
392             DNDDEBUG << "real window found" << target;
393         }
394     }
395
396     QXcbWindow *w = 0;
397     if (target) {
398         w = connection()->platformWindowFromId(target);
399         if (w && (w->window()->windowType() == Qt::Desktop) /*&& !w->acceptDrops()*/)
400             w = 0;
401     } else {
402         w = 0;
403         target = rootwin;
404     }
405
406     xcb_window_t proxy_target = xdndProxy(connection(), target);
407     if (!proxy_target)
408         proxy_target = target;
409     int target_version = 1;
410
411     if (proxy_target) {
412         xcb_get_property_cookie_t cookie = xcb_get_property(xcb_connection(), false, target,
413                                                             atom(QXcbAtom::XdndAware), XCB_GET_PROPERTY_TYPE_ANY, 0, 1);
414         xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0);
415         if (!reply || reply->type == XCB_NONE)
416             target = 0;
417         target_version = xcb_get_property_value_length(reply) == 1 ? *(uint32_t *)xcb_get_property_value(reply) : 1;
418         if (target_version > xdnd_version)
419             target_version = xdnd_version;
420
421         free(reply);
422     }
423
424     if (target != current_target) {
425         if (current_target)
426             send_leave();
427
428         current_target = target;
429         current_proxy_target = proxy_target;
430         if (target) {
431             int flags = target_version << 24;
432             if (drag_types.size() > 3)
433                 flags |= 0x0001;
434
435             xcb_client_message_event_t enter;
436             enter.response_type = XCB_CLIENT_MESSAGE;
437             enter.window = target;
438             enter.format = 32;
439             enter.type = atom(QXcbAtom::XdndEnter);
440             enter.data.data32[0] = connection()->clipboard()->owner();
441             enter.data.data32[1] = flags;
442             enter.data.data32[2] = drag_types.size()>0 ? drag_types.at(0) : 0;
443             enter.data.data32[3] = drag_types.size()>1 ? drag_types.at(1) : 0;
444             enter.data.data32[4] = drag_types.size()>2 ? drag_types.at(2) : 0;
445             // provisionally set the rectangle to 5x5 pixels...
446             source_sameanswer = QRect(globalPos.x() - 2, globalPos.y() -2 , 5, 5);
447
448             DEBUG() << "sending Xdnd enter source=" << enter.data.data32[0];
449             if (w)
450                 handleEnter(w->window(), &enter);
451             else if (target)
452                 xcb_send_event(xcb_connection(), false, proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&enter);
453             waiting_for_status = false;
454         }
455     }
456
457     if (waiting_for_status)
458         return;
459
460     if (target) {
461         waiting_for_status = true;
462
463         xcb_client_message_event_t move;
464         move.response_type = XCB_CLIENT_MESSAGE;
465         move.window = target;
466         move.format = 32;
467         move.type = atom(QXcbAtom::XdndPosition);
468         move.data.data32[0] = connection()->clipboard()->owner();
469         move.data.data32[1] = 0; // flags
470         move.data.data32[2] = (globalPos.x() << 16) + globalPos.y();
471         move.data.data32[3] = connection()->time();
472         move.data.data32[4] = toXdndAction(defaultAction(currentDrag()->supportedActions(), QGuiApplication::keyboardModifiers()));
473         DEBUG() << "sending Xdnd position source=" << move.data.data32[0] << "target=" << move.window;
474
475         source_time = connection()->time();
476
477         if (w)
478             handle_xdnd_position(w->window(), &move);
479         else
480             xcb_send_event(xcb_connection(), false, proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&move);
481     }
482 }
483
484 void QXcbDrag::drop(const QMouseEvent *event)
485 {
486     QBasicDrag::drop(event);
487     if (!current_target)
488         return;
489
490     xcb_client_message_event_t drop;
491     drop.response_type = XCB_CLIENT_MESSAGE;
492     drop.window = current_target;
493     drop.format = 32;
494     drop.type = atom(QXcbAtom::XdndDrop);
495     drop.data.data32[0] = connection()->clipboard()->owner();
496     drop.data.data32[1] = 0; // flags
497     drop.data.data32[2] = connection()->time();
498
499     drop.data.data32[3] = 0;
500     drop.data.data32[4] = currentDrag()->supportedActions();
501
502     QXcbWindow *w = connection()->platformWindowFromId(current_proxy_target);
503
504     if (w && (w->window()->windowType() == Qt::Desktop) /*&& !w->acceptDrops()*/)
505         w = 0;
506
507
508     Transaction t = {
509         connection()->time(),
510         current_target,
511         current_proxy_target,
512         (w ? w->window() : 0),
513 //        current_embedding_widget,
514         currentDrag()
515     };
516     transactions.append(t);
517     restartDropExpiryTimer();
518
519     if (w) {
520         handleDrop(w->window(), &drop);
521     } else {
522         xcb_send_event(xcb_connection(), false, current_proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&drop);
523     }
524
525     current_target = 0;
526     current_proxy_target = 0;
527     source_time = 0;
528 //    current_embedding_widget = 0;
529     // #fixme resetDndState(false);
530 }
531
532 Qt::DropAction QXcbDrag::toDropAction(xcb_atom_t a) const
533 {
534     if (a == atom(QXcbAtom::XdndActionCopy) || a == 0)
535         return Qt::CopyAction;
536     if (a == atom(QXcbAtom::XdndActionLink))
537         return Qt::LinkAction;
538     if (a == atom(QXcbAtom::XdndActionMove))
539         return Qt::MoveAction;
540     return Qt::CopyAction;
541 }
542
543 xcb_atom_t QXcbDrag::toXdndAction(Qt::DropAction a) const
544 {
545     switch (a) {
546     case Qt::CopyAction:
547         return atom(QXcbAtom::XdndActionCopy);
548     case Qt::LinkAction:
549         return atom(QXcbAtom::XdndActionLink);
550     case Qt::MoveAction:
551     case Qt::TargetMoveAction:
552         return atom(QXcbAtom::XdndActionMove);
553     case Qt::IgnoreAction:
554         return XCB_NONE;
555     default:
556         return atom(QXcbAtom::XdndActionCopy);
557     }
558 }
559
560 // timer used to discard old XdndDrop transactions
561 enum { XdndDropTransactionTimeout = 5000 }; // 5 seconds
562
563 void QXcbDrag::restartDropExpiryTimer()
564 {
565     if (transaction_expiry_timer != -1)
566         killTimer(transaction_expiry_timer);
567     transaction_expiry_timer = startTimer(XdndDropTransactionTimeout);
568 }
569
570 int QXcbDrag::findTransactionByWindow(xcb_window_t window)
571 {
572     int at = -1;
573     for (int i = 0; i < transactions.count(); ++i) {
574         const Transaction &t = transactions.at(i);
575         if (t.target == window || t.proxy_target == window) {
576             at = i;
577             break;
578         }
579     }
580     return at;
581 }
582
583 int QXcbDrag::findTransactionByTime(xcb_timestamp_t timestamp)
584 {
585     int at = -1;
586     for (int i = 0; i < transactions.count(); ++i) {
587         const Transaction &t = transactions.at(i);
588         if (t.timestamp == timestamp) {
589             at = i;
590             break;
591         }
592     }
593     return at;
594 }
595
596 #if 0
597
598 // find an ancestor with XdndAware on it
599 static Window findXdndAwareParent(Window window)
600 {
601     Window target = 0;
602     forever {
603         // check if window has XdndAware
604         Atom type = 0;
605         int f;
606         unsigned long n, a;
607         unsigned char *data = 0;
608         if (XGetWindowProperty(X11->display, window, ATOM(XdndAware), 0, 0, False,
609                                AnyPropertyType, &type, &f,&n,&a,&data) == Success) {
610             if (data)
611                 XFree(data);
612             if (type) {
613                 target = window;
614                 break;
615             }
616         }
617
618         // try window's parent
619         Window root;
620         Window parent;
621         Window *children;
622         uint unused;
623         if (!XQueryTree(X11->display, window, &root, &parent, &children, &unused))
624             break;
625         if (children)
626             XFree(children);
627         if (window == root)
628             break;
629         window = parent;
630     }
631     return target;
632 }
633
634
635 // for embedding only
636 static QWidget* current_embedding_widget  = 0;
637 static xcb_client_message_event_t last_enter_event;
638
639
640 static bool checkEmbedded(QWidget* w, const XEvent* xe)
641 {
642     if (!w)
643         return false;
644
645     if (current_embedding_widget != 0 && current_embedding_widget != w) {
646         current_target = ((QExtraWidget*)current_embedding_widget)->extraData()->xDndProxy;
647         current_proxy_target = current_target;
648         qt_xdnd_send_leave();
649         current_target = 0;
650         current_proxy_target = 0;
651         current_embedding_widget = 0;
652     }
653
654     QWExtra* extra = ((QExtraWidget*)w)->extraData();
655     if (extra && extra->xDndProxy != 0) {
656
657         if (current_embedding_widget != w) {
658
659             last_enter_event.xany.window = extra->xDndProxy;
660             XSendEvent(X11->display, extra->xDndProxy, False, NoEventMask, &last_enter_event);
661             current_embedding_widget = w;
662         }
663
664         ((XEvent*)xe)->xany.window = extra->xDndProxy;
665         XSendEvent(X11->display, extra->xDndProxy, False, NoEventMask, (XEvent*)xe);
666         if (currentWindow != w) {
667             currentWindow = w;
668         }
669         return true;
670     }
671     current_embedding_widget = 0;
672     return false;
673 }
674 #endif
675
676
677 void QXcbDrag::handleEnter(QWindow *window, const xcb_client_message_event_t *event)
678 {
679     Q_UNUSED(window);
680     DEBUG() << "handleEnter" << window;
681
682     xdnd_types.clear();
683 //    motifdnd_active = false;
684 //    last_enter_event.xclient = xe->xclient;
685
686     int version = (int)(event->data.data32[1] >> 24);
687     if (version > xdnd_version)
688         return;
689
690     xdnd_dragsource = event->data.data32[0];
691
692     if (event->data.data32[1] & 1) {
693         // get the types from XdndTypeList
694         xcb_get_property_cookie_t cookie = xcb_get_property(xcb_connection(), false, xdnd_dragsource,
695                                                             atom(QXcbAtom::XdndTypelist), XCB_ATOM_ATOM,
696                                                             0, xdnd_max_type);
697         xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0);
698         if (reply && reply->type != XCB_NONE && reply->format == 32) {
699             int length = xcb_get_property_value_length(reply) / 4;
700             if (length > xdnd_max_type)
701                 length = xdnd_max_type;
702
703             xcb_atom_t *atoms = (xcb_atom_t *)xcb_get_property_value(reply);
704             for (int i = 0; i < length; ++i)
705                 xdnd_types.append(atoms[i]);
706         }
707         free(reply);
708     } else {
709         // get the types from the message
710         for(int i = 2; i < 5; i++) {
711             if (event->data.data32[i])
712                 xdnd_types.append(event->data.data32[i]);
713         }
714     }
715     for(int i = 0; i < xdnd_types.length(); ++i)
716         DEBUG() << "    " << connection()->atomName(xdnd_types.at(i));
717 }
718
719 void QXcbDrag::handle_xdnd_position(QWindow *w, const xcb_client_message_event_t *e)
720 {
721     QPoint p((e->data.data32[2] & 0xffff0000) >> 16, e->data.data32[2] & 0x0000ffff);
722     Q_ASSERT(w);
723     QRect geometry = w->geometry();
724
725     p -= geometry.topLeft();
726
727     if (!w || (w->windowType() == Qt::Desktop))
728         return;
729
730     if (e->data.data32[0] != xdnd_dragsource) {
731         DEBUG("xdnd drag position from unexpected source (%x not %x)", e->data.data32[0], xdnd_dragsource);
732         return;
733     }
734
735     currentPosition = p;
736     currentWindow = w;
737
738     // timestamp from the source
739     if (e->data.data32[3] != XCB_NONE) {
740         target_time = e->data.data32[3];
741     }
742
743     QMimeData *dropData = 0;
744     Qt::DropActions supported_actions = Qt::IgnoreAction;
745     if (currentDrag()) {
746         dropData = currentDrag()->mimeData();
747         supported_actions = currentDrag()->supportedActions();
748     } else {
749         dropData = platformDropData();
750         supported_actions = Qt::DropActions(toDropAction(e->data.data32[4]));
751     }
752
753     QPlatformDragQtResponse qt_response = QWindowSystemInterface::handleDrag(w,dropData,p,supported_actions);
754     QRect answerRect(p + geometry.topLeft(), QSize(1,1));
755     answerRect = qt_response.answerRect().translated(geometry.topLeft()).intersected(geometry);
756
757     xcb_client_message_event_t response;
758     response.response_type = XCB_CLIENT_MESSAGE;
759     response.window = xdnd_dragsource;
760     response.format = 32;
761     response.type = atom(QXcbAtom::XdndStatus);
762     response.data.data32[0] = xcb_window(w);
763     response.data.data32[1] = qt_response.isAccepted(); // flags
764     response.data.data32[2] = 0; // x, y
765     response.data.data32[3] = 0; // w, h
766     response.data.data32[4] = toXdndAction(qt_response.acceptedAction()); // action
767
768
769
770     if (answerRect.left() < 0)
771         answerRect.setLeft(0);
772     if (answerRect.right() > 4096)
773         answerRect.setRight(4096);
774     if (answerRect.top() < 0)
775         answerRect.setTop(0);
776     if (answerRect.bottom() > 4096)
777         answerRect.setBottom(4096);
778     if (answerRect.width() < 0)
779         answerRect.setWidth(0);
780     if (answerRect.height() < 0)
781         answerRect.setHeight(0);
782
783     response.data.data32[4] = toXdndAction(qt_response.acceptedAction());
784
785     // reset
786     target_time = XCB_CURRENT_TIME;
787
788     if (xdnd_dragsource == connection()->clipboard()->owner())
789         handle_xdnd_status(&response);
790     else
791         Q_XCB_CALL(xcb_send_event(xcb_connection(), false, xdnd_dragsource,
792                                   XCB_EVENT_MASK_NO_EVENT, (const char *)&response));
793 }
794
795 namespace
796 {
797     class ClientMessageScanner {
798     public:
799         ClientMessageScanner(xcb_atom_t a) : atom(a) {}
800         xcb_atom_t atom;
801         bool checkEvent(xcb_generic_event_t *event) const {
802             if (!event)
803                 return false;
804             if ((event->response_type & 0x7f) != XCB_CLIENT_MESSAGE)
805                 return false;
806             return ((xcb_client_message_event_t *)event)->type == atom;
807         }
808     };
809 }
810
811 void QXcbDrag::handlePosition(QWindow * w, const xcb_client_message_event_t *event)
812 {
813     xcb_client_message_event_t *lastEvent = const_cast<xcb_client_message_event_t *>(event);
814     xcb_generic_event_t *nextEvent;
815     ClientMessageScanner scanner(atom(QXcbAtom::XdndPosition));
816     while ((nextEvent = connection()->checkEvent(scanner))) {
817         if (lastEvent != event)
818             free(lastEvent);
819         lastEvent = (xcb_client_message_event_t *)nextEvent;
820     }
821
822     handle_xdnd_position(w, lastEvent);
823     if (lastEvent != event)
824         free(lastEvent);
825 }
826
827 void QXcbDrag::handle_xdnd_status(const xcb_client_message_event_t *event)
828 {
829     DEBUG("xdndHandleStatus");
830     waiting_for_status = false;
831     // ignore late status messages
832     if (event->data.data32[0] && event->data.data32[0] != current_proxy_target)
833         return;
834
835     const bool dropPossible = event->data.data32[1];
836     setCanDrop(dropPossible);
837
838     if (dropPossible) {
839         accepted_drop_action = toDropAction(event->data.data32[4]);
840         updateCursor(accepted_drop_action);
841     } else {
842         updateCursor(Qt::IgnoreAction);
843     }
844
845     if ((event->data.data32[1] & 2) == 0) {
846         QPoint p((event->data.data32[2] & 0xffff0000) >> 16, event->data.data32[2] & 0x0000ffff);
847         QSize s((event->data.data32[3] & 0xffff0000) >> 16, event->data.data32[3] & 0x0000ffff);
848         source_sameanswer = QRect(p, s);
849     } else {
850         source_sameanswer = QRect();
851     }
852 }
853
854 void QXcbDrag::handleStatus(const xcb_client_message_event_t *event)
855 {
856     if (event->window != connection()->clipboard()->owner())
857         return;
858
859     xcb_client_message_event_t *lastEvent = const_cast<xcb_client_message_event_t *>(event);
860     xcb_generic_event_t *nextEvent;
861     ClientMessageScanner scanner(atom(QXcbAtom::XdndStatus));
862     while ((nextEvent = connection()->checkEvent(scanner))) {
863         if (lastEvent != event)
864             free(lastEvent);
865         lastEvent = (xcb_client_message_event_t *)nextEvent;
866     }
867
868     handle_xdnd_status(lastEvent);
869     if (lastEvent != event)
870         free(lastEvent);
871     DEBUG("xdndHandleStatus end");
872 }
873
874 void QXcbDrag::handleLeave(QWindow *w, const xcb_client_message_event_t *event)
875 {
876     DEBUG("xdnd leave");
877     if (!currentWindow || w != currentWindow.data())
878         return; // sanity
879
880     // ###
881 //    if (checkEmbedded(current_embedding_widget, event)) {
882 //        current_embedding_widget = 0;
883 //        currentWindow.clear();
884 //        return;
885 //    }
886
887     if (event->data.data32[0] != xdnd_dragsource) {
888         // This often happens - leave other-process window quickly
889         DEBUG("xdnd drag leave from unexpected source (%x not %x", event->data.data32[0], xdnd_dragsource);
890     }
891
892     QWindowSystemInterface::handleDrag(w,0,QPoint(),Qt::IgnoreAction);
893     updateAction(Qt::IgnoreAction);
894
895     xdnd_dragsource = 0;
896     xdnd_types.clear();
897     currentWindow.clear();
898 }
899
900 void QXcbDrag::send_leave()
901 {
902     if (!current_target)
903         return;
904
905
906     xcb_client_message_event_t leave;
907     leave.response_type = XCB_CLIENT_MESSAGE;
908     leave.window = current_target;
909     leave.format = 32;
910     leave.type = atom(QXcbAtom::XdndLeave);
911     leave.data.data32[0] = connection()->clipboard()->owner();
912     leave.data.data32[1] = 0; // flags
913     leave.data.data32[2] = 0; // x, y
914     leave.data.data32[3] = 0; // w, h
915     leave.data.data32[4] = 0; // just null
916
917     QXcbWindow *w = connection()->platformWindowFromId(current_proxy_target);
918
919     if (w && (w->window()->windowType() == Qt::Desktop) /*&& !w->acceptDrops()*/)
920         w = 0;
921
922     if (w)
923         handleLeave(w->window(), (const xcb_client_message_event_t *)&leave);
924     else
925         xcb_send_event(xcb_connection(), false,current_proxy_target,
926                        XCB_EVENT_MASK_NO_EVENT, (const char *)&leave);
927
928     current_target = 0;
929     current_proxy_target = 0;
930     source_time = XCB_CURRENT_TIME;
931     waiting_for_status = false;
932 }
933
934 void QXcbDrag::handleDrop(QWindow *, const xcb_client_message_event_t *event)
935 {
936     DEBUG("xdndHandleDrop");
937     if (!currentWindow) {
938         xdnd_dragsource = 0;
939         return; // sanity
940     }
941
942     const uint32_t *l = event->data.data32;
943
944     DEBUG("xdnd drop");
945
946     if (l[0] != xdnd_dragsource) {
947         DEBUG("xdnd drop from unexpected source (%x not %x", l[0], xdnd_dragsource);
948         return;
949     }
950
951     // update the "user time" from the timestamp in the event.
952     if (l[2] != 0)
953         target_time = /*X11->userTime =*/ l[2];
954
955     // this could be a same-application drop, just proxied due to
956     // some XEMBEDding, so try to find the real QMimeData used
957     // based on the timestamp for this drop.
958     Qt::DropActions supported_drop_actions(l[4]);
959     QMimeData *dropData = 0;
960     if (currentDrag()) {
961         dropData = currentDrag()->mimeData();
962     } else {
963         dropData = platformDropData();
964     }
965
966     if (!dropData)
967         return;
968     // ###
969     //        int at = findXdndDropTransactionByTime(target_time);
970     //        if (at != -1)
971     //            dropData = QDragManager::dragPrivate(X11->dndDropTransactions.at(at).object)->data;
972     // if we can't find it, then use the data in the drag manager
973
974     QPlatformDropQtResponse response = QWindowSystemInterface::handleDrop(currentWindow.data(),dropData,currentPosition,supported_drop_actions);
975     setExecutedDropAction(response.acceptedAction());
976
977     xcb_client_message_event_t finished;
978     finished.response_type = XCB_CLIENT_MESSAGE;
979     finished.window = xdnd_dragsource;
980     finished.format = 32;
981     finished.type = atom(QXcbAtom::XdndFinished);
982     finished.data.data32[0] = currentWindow ? xcb_window(currentWindow.data()) : XCB_NONE;
983     finished.data.data32[1] = response.isAccepted(); // flags
984     finished.data.data32[2] = toXdndAction(response.acceptedAction());
985     Q_XCB_CALL(xcb_send_event(xcb_connection(), false, xdnd_dragsource,
986                               XCB_EVENT_MASK_NO_EVENT, (char *)&finished));
987
988     xdnd_dragsource = 0;
989     currentWindow.clear();
990     waiting_for_status = false;
991
992     // reset
993     target_time = XCB_CURRENT_TIME;
994 }
995
996
997 void QXcbDrag::handleFinished(const xcb_client_message_event_t *event)
998 {
999     DEBUG("xdndHandleFinished");
1000     if (event->window != connection()->clipboard()->owner())
1001         return;
1002
1003     const unsigned long *l = (const unsigned long *)event->data.data32;
1004
1005     DNDDEBUG << "xdndHandleFinished, l[0]" << l[0]
1006              << "current_target" << current_target
1007              << "qt_xdnd_current_proxy_targe" << current_proxy_target;
1008
1009     if (l[0]) {
1010         int at = findTransactionByWindow(l[0]);
1011         if (at != -1) {
1012             restartDropExpiryTimer();
1013
1014             Transaction t = transactions.takeAt(at);
1015 //            QDragManager *manager = QDragManager::self();
1016
1017 //            Window target = current_target;
1018 //            Window proxy_target = current_proxy_target;
1019 //            QWidget *embedding_widget = current_embedding_widget;
1020 //            QDrag *currentObject = manager->object;
1021
1022 //            current_target = t.target;
1023 //            current_proxy_target = t.proxy_target;
1024 //            current_embedding_widget = t.embedding_widget;
1025 //            manager->object = t.object;
1026
1027 //            if (!passive)
1028 //                (void) checkEmbedded(currentWindow, xe);
1029
1030 //            current_embedding_widget = 0;
1031 //            current_target = 0;
1032 //            current_proxy_target = 0;
1033
1034             if (t.drag)
1035                 t.drag->deleteLater();
1036
1037 //            current_target = target;
1038 //            current_proxy_target = proxy_target;
1039 //            current_embedding_widget = embedding_widget;
1040 //            manager->object = currentObject;
1041         }
1042     }
1043     waiting_for_status = false;
1044 }
1045
1046
1047 void QXcbDrag::timerEvent(QTimerEvent* e)
1048 {
1049     if (e->timerId() == heartbeat && source_sameanswer.isNull()) {
1050         QPointF pos = QCursor::pos();
1051         QMouseEvent me(QEvent::MouseMove, pos, pos, pos, Qt::LeftButton,
1052                        QGuiApplication::mouseButtons(), QGuiApplication::keyboardModifiers());
1053         move(&me);
1054     } else if (e->timerId() == transaction_expiry_timer) {
1055         for (int i = 0; i < transactions.count(); ++i) {
1056             const Transaction &t = transactions.at(i);
1057             if (t.targetWindow) {
1058                 // dnd within the same process, don't delete these
1059                 continue;
1060             }
1061             t.drag->deleteLater();
1062             transactions.removeAt(i--);
1063         }
1064
1065         killTimer(transaction_expiry_timer);
1066         transaction_expiry_timer = -1;
1067     }
1068 }
1069
1070 void QXcbDrag::cancel()
1071 {
1072     DEBUG("QXcbDrag::cancel");
1073     QBasicDrag::cancel();
1074     if (current_target)
1075         send_leave();
1076 }
1077
1078
1079 void QXcbDrag::handleSelectionRequest(const xcb_selection_request_event_t *event)
1080 {
1081     xcb_selection_notify_event_t notify;
1082     notify.response_type = XCB_SELECTION_NOTIFY;
1083     notify.requestor = event->requestor;
1084     notify.selection = event->selection;
1085     notify.target = XCB_NONE;
1086     notify.property = XCB_NONE;
1087     notify.time = event->time;
1088
1089     // which transaction do we use? (note: -2 means use current manager->object)
1090     int at = -1;
1091
1092     // figure out which data the requestor is really interested in
1093     if (currentDrag() && event->time == source_time) {
1094         // requestor wants the current drag data
1095         at = -2;
1096     } else {
1097         // if someone has requested data in response to XdndDrop, find the corresponding transaction. the
1098         // spec says to call XConvertSelection() using the timestamp from the XdndDrop
1099         at = findTransactionByTime(event->time);
1100         if (at == -1) {
1101             // no dice, perhaps the client was nice enough to use the same window id in XConvertSelection()
1102             // that we sent the XdndDrop event to.
1103             at = findTransactionByWindow(event->requestor);
1104         }
1105 //        if (at == -1 && event->time == XCB_CURRENT_TIME) {
1106 //            // previous Qt versions always requested the data on a child of the target window
1107 //            // using CurrentTime... but it could be asking for either drop data or the current drag's data
1108 //            Window target = findXdndAwareParent(event->requestor);
1109 //            if (target) {
1110 //                if (current_target && current_target == target)
1111 //                    at = -2;
1112 //                else
1113 //                    at = findXdndDropTransactionByWindow(target);
1114 //            }
1115 //        }
1116     }
1117
1118     QDrag *transactionDrag = 0;
1119     if (at >= 0) {
1120         restartDropExpiryTimer();
1121
1122         transactionDrag = transactions.at(at).drag;
1123     }
1124     if (transactionDrag) {
1125         xcb_atom_t atomFormat = event->target;
1126         int dataFormat = 0;
1127         QByteArray data;
1128         if (QXcbMime::mimeDataForAtom(connection(), event->target, transactionDrag->mimeData(),
1129                                      &data, &atomFormat, &dataFormat)) {
1130             int dataSize = data.size() / (dataFormat / 8);
1131             xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, event->requestor, event->property,
1132                                 atomFormat, dataFormat, dataSize, (const void *)data.constData());
1133             notify.property = event->property;
1134             notify.target = atomFormat;
1135         }
1136     }
1137
1138     xcb_send_event(xcb_connection(), false, event->requestor, XCB_EVENT_MASK_NO_EVENT, (const char *)&notify);
1139 }
1140
1141
1142 bool QXcbDrag::dndEnable(QXcbWindow *w, bool on)
1143 {
1144     DNDDEBUG << "xdndEnable" << w << on;
1145     if (on) {
1146         QXcbWindow *xdnd_widget = 0;
1147         if ((w->window()->windowType() == Qt::Desktop)) {
1148             if (desktop_proxy) // *WE* already have one.
1149                 return false;
1150
1151             xcb_grab_server(xcb_connection());
1152
1153             // As per Xdnd4, use XdndProxy
1154             xcb_window_t proxy_id = xdndProxy(connection(), w->xcb_window());
1155
1156             if (!proxy_id) {
1157                 desktop_proxy = new QWindow;
1158                 xdnd_widget = static_cast<QXcbWindow *>(desktop_proxy->handle());
1159                 proxy_id = xdnd_widget->xcb_window();
1160                 xcb_atom_t xdnd_proxy = atom(QXcbAtom::XdndProxy);
1161                 xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, w->xcb_window(), xdnd_proxy,
1162                                     XCB_ATOM_WINDOW, 32, 1, &proxy_id);
1163                 xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, proxy_id, xdnd_proxy,
1164                                     XCB_ATOM_WINDOW, 32, 1, &proxy_id);
1165             }
1166
1167             xcb_ungrab_server(xcb_connection());
1168         } else {
1169             xdnd_widget = w;
1170         }
1171         if (xdnd_widget) {
1172             DNDDEBUG << "setting XdndAware for" << xdnd_widget << xdnd_widget->xcb_window();
1173             xcb_atom_t atm = xdnd_version;
1174             xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, xdnd_widget->xcb_window(),
1175                                 atom(QXcbAtom::XdndAware), XCB_ATOM_ATOM, 32, 1, &atm);
1176             return true;
1177         } else {
1178             return false;
1179         }
1180     } else {
1181         if ((w->window()->windowType() == Qt::Desktop)) {
1182             xcb_delete_property(xcb_connection(), w->xcb_window(), atom(QXcbAtom::XdndProxy));
1183             delete desktop_proxy;
1184             desktop_proxy = 0;
1185         } else {
1186             DNDDEBUG << "not deleting XDndAware";
1187         }
1188         return true;
1189     }
1190 }
1191
1192 QXcbDropData::QXcbDropData(QXcbDrag *d)
1193     : QXcbMime(),
1194       drag(d)
1195 {
1196 }
1197
1198 QXcbDropData::~QXcbDropData()
1199 {
1200 }
1201
1202 QVariant QXcbDropData::retrieveData_sys(const QString &mimetype, QVariant::Type requestedType) const
1203 {
1204     QByteArray mime = mimetype.toLatin1();
1205     QVariant data = /*X11->motifdnd_active
1206                       ? X11->motifdndObtainData(mime)
1207                       :*/ xdndObtainData(mime, requestedType);
1208     return data;
1209 }
1210
1211 QVariant QXcbDropData::xdndObtainData(const QByteArray &format, QVariant::Type requestedType) const
1212 {
1213     QByteArray result;
1214
1215     QXcbConnection *c = drag->connection();
1216     QXcbWindow *xcb_window = c->platformWindowFromId(drag->xdnd_dragsource);
1217     if (xcb_window && drag->currentDrag() && xcb_window->window()->windowType() != Qt::Desktop) {
1218         QMimeData *data = drag->currentDrag()->mimeData();
1219         if (data->hasFormat(QLatin1String(format)))
1220             result = data->data(QLatin1String(format));
1221         return result;
1222     }
1223
1224     QList<xcb_atom_t> atoms = drag->xdnd_types;
1225     QByteArray encoding;
1226     xcb_atom_t a = mimeAtomForFormat(c, QLatin1String(format), requestedType, atoms, &encoding);
1227     if (a == XCB_NONE)
1228         return result;
1229
1230     if (c->clipboard()->getSelectionOwner(drag->atom(QXcbAtom::XdndSelection)) == XCB_NONE)
1231         return result; // should never happen?
1232
1233     xcb_atom_t xdnd_selection = c->atom(QXcbAtom::XdndSelection);
1234     result = c->clipboard()->getSelection(xdnd_selection, a, xdnd_selection);
1235
1236     return mimeConvertToFormat(c, a, result, QLatin1String(format), requestedType, encoding);
1237 }
1238
1239
1240 bool QXcbDropData::hasFormat_sys(const QString &format) const
1241 {
1242     return formats().contains(format);
1243 }
1244
1245 QStringList QXcbDropData::formats_sys() const
1246 {
1247     QStringList formats;
1248 //    if (X11->motifdnd_active) {
1249 //        int i = 0;
1250 //        QByteArray fmt;
1251 //        while (!(fmt = X11->motifdndFormat(i)).isEmpty()) {
1252 //            formats.append(QLatin1String(fmt));
1253 //            ++i;
1254 //        }
1255 //    } else {
1256         for (int i = 0; i < drag->xdnd_types.size(); ++i) {
1257             QString f = mimeAtomToString(drag->connection(), drag->xdnd_types.at(i));
1258             if (!formats.contains(f))
1259                 formats.append(f);
1260         }
1261 //    }
1262     return formats;
1263 }
1264
1265 #endif // QT_NO_DRAGANDDROP
1266
1267 QT_END_NAMESPACE