summaryrefslogtreecommitdiffstats
path: root/src/gui/kernel/qclipboard_x11.cpp
blob: 803b1ba7f8b4b99345b6129f69163bee86c0815c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

// #define QCLIPBOARD_DEBUG
// #define QCLIPBOARD_DEBUG_VERBOSE

#ifdef QCLIPBOARD_DEBUG
#  define DEBUG qDebug
#else
#  define DEBUG if (false) qDebug
#endif

#ifdef QCLIPBOARD_DEBUG_VERBOSE
#  define VDEBUG qDebug
#else
#  define VDEBUG if (false) qDebug
#endif

#include "qplatformdefs.h"

#include "qclipboard.h"
#include "qclipboard_p.h"

#ifndef QT_NO_CLIPBOARD

#include "qabstracteventdispatcher.h"
#include "qapplication.h"
#include "qdesktopwidget.h"
#include "qbitmap.h"
#include "qiodevice.h"
#include "qbuffer.h"
#include "qtextcodec.h"
#include "qlist.h"
#include "qmap.h"
#include "qapplication_p.h"
#include "qevent.h"
#include "qt_x11_p.h"
#include "qx11info_x11.h"
#include "qimagewriter.h"
#include "qelapsedtimer.h"
#include "qvariant.h"
#include "qdnd_p.h"
#include <private/qwidget_p.h>

#ifndef QT_NO_XFIXES
#include <X11/extensions/Xfixes.h>
#endif // QT_NO_XFIXES

QT_BEGIN_NAMESPACE

/*****************************************************************************
  Internal QClipboard functions for X11.
 *****************************************************************************/

static int clipboard_timeout = 5000; // 5s timeout on clipboard operations

static QWidget * owner = 0;
static QWidget *requestor = 0;
static bool timer_event_clear = false;
static int timer_id = 0;

static int pending_timer_id = 0;
static bool pending_clipboard_changed = false;
static bool pending_selection_changed = false;


// event capture mechanism for qt_xclb_wait_for_event
static bool waiting_for_data = false;
static bool has_captured_event = false;
static Window capture_event_win = XNone;
static int capture_event_type = -1;
static XEvent captured_event;

class QClipboardWatcher; // forward decl
static QClipboardWatcher *selection_watcher = 0;
static QClipboardWatcher *clipboard_watcher = 0;

static void cleanup()
{
    delete owner;
    delete requestor;
    owner = 0;
    requestor = 0;
}

static
void setupOwner()
{
    if (owner)
        return;
    owner = new QWidget(0);
    owner->setObjectName(QLatin1String("internal clipboard owner"));
    owner->createWinId();
    requestor = new QWidget(0);
    requestor->createWinId();
    requestor->setObjectName(QLatin1String("internal clipboard requestor"));
    // We don't need this internal widgets to appear in QApplication::topLevelWidgets()
    if (QWidgetPrivate::allWidgets) {
        QWidgetPrivate::allWidgets->remove(owner);
        QWidgetPrivate::allWidgets->remove(requestor);
    }
    qAddPostRoutine(cleanup);
}


class QClipboardWatcher : public QInternalMimeData {
public:
    QClipboardWatcher(QClipboard::Mode mode);
    ~QClipboardWatcher();
    bool empty() const;
    virtual bool hasFormat_sys(const QString &mimetype) const;
    virtual QStringList formats_sys() const;

    QVariant retrieveData_sys(const QString &mimetype, QVariant::Type type) const;
    QByteArray getDataInFormat(Atom fmtatom) const;

    Atom atom;
    mutable QStringList formatList;
    mutable QByteArray format_atoms;
};

class QClipboardData
{
private:
    QMimeData *&mimeDataRef() const
    {
        if(mode == QClipboard::Selection)
            return selectionData;
        return clipboardData;
    }

public:
    QClipboardData(QClipboard::Mode mode);
    ~QClipboardData();

    void setSource(QMimeData* s)
    {
        if ((mode == QClipboard::Selection && selectionData == s)
            || clipboardData == s) {
            return;
        }

        if (selectionData != clipboardData) {
            delete mimeDataRef();
        }

        mimeDataRef() = s;
    }

    QMimeData *source() const
    {
        return mimeDataRef();
    }

    void clear()
    {
        timestamp = CurrentTime;
        if (selectionData == clipboardData) {
            mimeDataRef() = 0;
        } else {
            QMimeData *&src = mimeDataRef();
            delete src;
            src = 0;
        }
    }

    static QMimeData *selectionData;
    static QMimeData *clipboardData;
    Time timestamp;
    QClipboard::Mode mode;
};

QMimeData *QClipboardData::selectionData = 0;
QMimeData *QClipboardData::clipboardData = 0;

QClipboardData::QClipboardData(QClipboard::Mode clipboardMode)
{
    timestamp = CurrentTime;
    mode = clipboardMode;
}

QClipboardData::~QClipboardData()
{ clear(); }


static QClipboardData *internalCbData = 0;
static QClipboardData *internalSelData = 0;

static void cleanupClipboardData()
{
    delete internalCbData;
    internalCbData = 0;
}

static QClipboardData *clipboardData()
{
    if (internalCbData == 0) {
        internalCbData = new QClipboardData(QClipboard::Clipboard);
        qAddPostRoutine(cleanupClipboardData);
    }
    return internalCbData;
}

static void cleanupSelectionData()
{
    delete internalSelData;
    internalSelData = 0;
}

static QClipboardData *selectionData()
{
    if (internalSelData == 0) {
        internalSelData = new QClipboardData(QClipboard::Selection);
        qAddPostRoutine(cleanupSelectionData);
    }
    return internalSelData;
}

class QClipboardINCRTransaction
{
public:
    QClipboardINCRTransaction(Window w, Atom p, Atom t, int f, QByteArray d, unsigned int i);
    ~QClipboardINCRTransaction(void);

    int x11Event(XEvent *event);

    Window window;
    Atom property, target;
    int format;
    QByteArray data;
    unsigned int increment;
    unsigned int offset;
};

typedef QMap<Window,QClipboardINCRTransaction*> TransactionMap;
static TransactionMap *transactions = 0;
static QApplication::EventFilter prev_event_filter = 0;
static int incr_timer_id = 0;

static bool qt_x11_incr_event_filter(void *message, long *result)
{
    XEvent *event = reinterpret_cast<XEvent *>(message);
    TransactionMap::Iterator it = transactions->find(event->xany.window);
    if (it != transactions->end()) {
        if ((*it)->x11Event(event) != 0)
            return true;
    }
    if (prev_event_filter)
        return prev_event_filter(event, result);
    return false;
}

/*
  called when no INCR activity has happened for 'clipboard_timeout'
  milliseconds... we assume that all unfinished transactions have
  timed out and remove everything from the transaction map
*/
static void qt_xclb_incr_timeout(void)
{
    qWarning("QClipboard: Timed out while sending data");

    while (transactions)
        delete *transactions->begin();
}

QClipboardINCRTransaction::QClipboardINCRTransaction(Window w, Atom p, Atom t, int f,
                                                     QByteArray d, unsigned int i)
    : window(w), property(p), target(t), format(f), data(d), increment(i), offset(0u)
{
    DEBUG("QClipboard: sending %d bytes (INCR transaction %p)", d.size(), this);

    XSelectInput(X11->display, window, PropertyChangeMask);

    if (! transactions) {
        VDEBUG("QClipboard: created INCR transaction map");
        transactions = new TransactionMap;
        prev_event_filter = qApp->setEventFilter(qt_x11_incr_event_filter);
        incr_timer_id = QApplication::clipboard()->startTimer(clipboard_timeout);
    }
    transactions->insert(window, this);
}

QClipboardINCRTransaction::~QClipboardINCRTransaction(void)
{
    VDEBUG("QClipboard: destroyed INCR transacton %p", this);

    XSelectInput(X11->display, window, NoEventMask);

    transactions->remove(window);
    if (transactions->isEmpty()) {
        VDEBUG("QClipboard: no more INCR transactions");
        delete transactions;
        transactions = 0;

        (void)qApp->setEventFilter(prev_event_filter);

        if (incr_timer_id != 0) {
            QApplication::clipboard()->killTimer(incr_timer_id);
            incr_timer_id = 0;
        }
    }
}

int QClipboardINCRTransaction::x11Event(XEvent *event)
{
    if (event->type != PropertyNotify
        || (event->xproperty.state != PropertyDelete
            || event->xproperty.atom != property))
        return 0;

    // restart the INCR timer
    if (incr_timer_id) QApplication::clipboard()->killTimer(incr_timer_id);
    incr_timer_id = QApplication::clipboard()->startTimer(clipboard_timeout);

    unsigned int bytes_left = data.size() - offset;
    if (bytes_left > 0) {
        unsigned int xfer = qMin(increment, bytes_left);
        VDEBUG("QClipboard: sending %d bytes, %d remaining (INCR transaction %p)",
               xfer, bytes_left - xfer, this);

        XChangeProperty(X11->display, window, property, target, format,
                        PropModeReplace, (uchar *) data.data() + offset, xfer);
        offset += xfer;
    } else {
        // INCR transaction finished...
        XChangeProperty(X11->display, window, property, target, format,
                        PropModeReplace, (uchar *) data.data(), 0);
        delete this;
    }

    return 1;
}


/*****************************************************************************
  QClipboard member functions for X11.
 *****************************************************************************/

struct qt_init_timestamp_data
{
    Time timestamp;
};

#if defined(Q_C_CALLBACKS)
extern "C" {
#endif

static Bool qt_init_timestamp_scanner(Display*, XEvent *event, XPointer arg)
{
    qt_init_timestamp_data *data =
        reinterpret_cast<qt_init_timestamp_data*>(arg);
    switch(event->type)
    {
    case ButtonPress:
    case ButtonRelease:
        data->timestamp = event->xbutton.time;
        break;
    case MotionNotify:
        data->timestamp = event->xmotion.time;
        break;
    case XKeyPress:
    case XKeyRelease:
        data->timestamp = event->xkey.time;
        break;
    case PropertyNotify:
        data->timestamp = event->xproperty.time;
        break;
    case EnterNotify:
    case LeaveNotify:
        data->timestamp = event->xcrossing.time;
        break;
    case SelectionClear:
        data->timestamp = event->xselectionclear.time;
        break;
    default:
        break;
    }
#ifndef QT_NO_XFIXES
    if (X11->use_xfixes && event->type == (X11->xfixes_eventbase + XFixesSelectionNotify)) {
        XFixesSelectionNotifyEvent *req =
            reinterpret_cast<XFixesSelectionNotifyEvent *>(event);
        data->timestamp = req->selection_timestamp;
    }
#endif
    return false;
}

#if defined(Q_C_CALLBACKS)
}
#endif

QClipboard::QClipboard(QObject *parent)
    : QObject(*new QClipboardPrivate, parent)
{
    // create desktop widget since we need it to get PropertyNotify or
    // XFixesSelectionNotify events when someone changes the
    // clipboard.
    (void)QApplication::desktop();

#ifndef QT_NO_XFIXES
    if (X11->use_xfixes && X11->ptrXFixesSelectSelectionInput) {
        const unsigned long eventMask =
            XFixesSetSelectionOwnerNotifyMask | XFixesSelectionWindowDestroyNotifyMask | XFixesSelectionClientCloseNotifyMask;
        for (int i = 0; i < X11->screenCount; ++i) {
            X11->ptrXFixesSelectSelectionInput(X11->display, QX11Info::appRootWindow(i),
                                               XA_PRIMARY, eventMask);
            X11->ptrXFixesSelectSelectionInput(X11->display, QX11Info::appRootWindow(i),
                                               ATOM(CLIPBOARD), eventMask);
        }
    }
#endif // QT_NO_XFIXES

    if (X11->time == CurrentTime) {
        // send a dummy event to myself to get the timestamp from X11.
        qt_init_timestamp_data data;
        data.timestamp = CurrentTime;
        XEvent ev;
        XCheckIfEvent(X11->display, &ev, &qt_init_timestamp_scanner, (XPointer)&data);
        if (data.timestamp == CurrentTime) {
            setupOwner();
            // We need this value just for completeness, we don't use it.
            long dummy = 0;
            Window ownerId = owner->internalWinId();
            XChangeProperty(X11->display, ownerId,
                            ATOM(CLIP_TEMPORARY), XA_INTEGER, 32,
                            PropModeReplace, (uchar*)&dummy, 1);
            XWindowEvent(X11->display, ownerId, PropertyChangeMask, &ev);
            data.timestamp = ev.xproperty.time;
            XDeleteProperty(X11->display, ownerId, ATOM(CLIP_TEMPORARY));
        }
        X11->time = data.timestamp;
    }
}

void QClipboard::clear(Mode mode)
{
    setMimeData(0, mode);
}


bool QClipboard::supportsMode(Mode mode) const
{
    return (mode == Clipboard || mode == Selection);
}

bool QClipboard::ownsMode(Mode mode) const
{
    if (mode == Clipboard)
        return clipboardData()->timestamp != CurrentTime;
    else if(mode == Selection)
        return selectionData()->timestamp != CurrentTime;
    else
        return false;
}


// event filter function... captures interesting events while
// qt_xclb_wait_for_event is running the event loop
static bool qt_x11_clipboard_event_filter(void *message, long *)
{
    XEvent *event = reinterpret_cast<XEvent *>(message);
    if (event->xany.type == capture_event_type &&
        event->xany.window == capture_event_win) {
        VDEBUG("QClipboard: event_filter(): caught event type %d", event->type);
        has_captured_event = true;
        captured_event = *event;
        return true;
    }
    return false;
}

static Bool checkForClipboardEvents(Display *, XEvent *e, XPointer)
{
    return ((e->type == SelectionRequest && (e->xselectionrequest.selection == XA_PRIMARY
                                             || e->xselectionrequest.selection == ATOM(CLIPBOARD)))
            || (e->type == SelectionClear && (e->xselectionclear.selection == XA_PRIMARY
                                              || e->xselectionclear.selection == ATOM(CLIPBOARD))));
}

bool QX11Data::clipboardWaitForEvent(Window win, int type, XEvent *event, int timeout, bool checkManager)
{
    QElapsedTimer started;
    started.start();
    QElapsedTimer now = started;

    if (QAbstractEventDispatcher::instance()->inherits("QtMotif")
        || QApplication::clipboard()->property("useEventLoopWhenWaiting").toBool()) {
        if (waiting_for_data) {
            Q_ASSERT(!"QClipboard: internal error, qt_xclb_wait_for_event recursed");
            return false;
        }
        waiting_for_data = true;


        has_captured_event = false;
        capture_event_win = win;
        capture_event_type = type;

        QApplication::EventFilter old_event_filter =
            qApp->setEventFilter(qt_x11_clipboard_event_filter);

        do {
            if (XCheckTypedWindowEvent(display, win, type, event)) {
                waiting_for_data = false;
                qApp->setEventFilter(old_event_filter);
                return true;
            }

            if (checkManager && XGetSelectionOwner(X11->display, ATOM(CLIPBOARD_MANAGER)) == XNone)
                return false;

            XSync(X11->display, false);
            usleep(50000);

            now.start();

            QEventLoop::ProcessEventsFlags flags(QEventLoop::ExcludeUserInputEvents
                                                 | QEventLoop::ExcludeSocketNotifiers
                                                 | QEventLoop::WaitForMoreEvents
                                                 | QEventLoop::X11ExcludeTimers);
            QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance();
            eventDispatcher->processEvents(flags);

            if (has_captured_event) {
                waiting_for_data = false;
                *event = captured_event;
                qApp->setEventFilter(old_event_filter);
                return true;
            }
        } while (started.msecsTo(now) < timeout);

        waiting_for_data = false;
        qApp->setEventFilter(old_event_filter);
    } else {
        do {
            if (XCheckTypedWindowEvent(X11->display,win,type,event))
                return true;

            if (checkManager && XGetSelectionOwner(X11->display, ATOM(CLIPBOARD_MANAGER)) == XNone)
                return false;

            // process other clipboard events, since someone is probably requesting data from us
            XEvent e;
            if (XCheckIfEvent(X11->display, &e, checkForClipboardEvents, 0))
                qApp->x11ProcessEvent(&e);

            now.start();

            XFlush(X11->display);

            // sleep 50 ms, so we don't use up CPU cycles all the time.
            struct timeval usleep_tv;
            usleep_tv.tv_sec = 0;
            usleep_tv.tv_usec = 50000;
            select(0, 0, 0, 0, &usleep_tv);
        } while (started.msecsTo(now) < timeout);
    }
    return false;
}


static inline int maxSelectionIncr(Display *dpy)
{ return XMaxRequestSize(dpy) > 65536 ? 65536*4 : XMaxRequestSize(dpy)*4 - 100; }

bool QX11Data::clipboardReadProperty(Window win, Atom property, bool deleteProperty,
                                     QByteArray *buffer, int *size, Atom *type, int *format)
{
    int           maxsize = maxSelectionIncr(display);
    ulong  bytes_left; // bytes_after
    ulong  length;     // nitems
    uchar *data;
    Atom   dummy_type;
    int    dummy_format;
    int    r;

    if (!type)                                // allow null args
        type = &dummy_type;
    if (!format)
        format = &dummy_format;

    // Don't read anything, just get the size of the property data
    r = XGetWindowProperty(display, win, property, 0, 0, False,
                            AnyPropertyType, type, format,
                            &length, &bytes_left, &data);
    if (r != Success || (type && *type == XNone)) {
        buffer->resize(0);
        return false;
    }
    XFree((char*)data);

    int  offset = 0, buffer_offset = 0, format_inc = 1, proplen = bytes_left;

    VDEBUG("QClipboard: read_property(): initial property length: %d", proplen);

    switch (*format) {
    case 8:
    default:
        format_inc = sizeof(char) / 1;
        break;

    case 16:
        format_inc = sizeof(short) / 2;
        proplen *= sizeof(short) / 2;
        break;

    case 32:
        format_inc = sizeof(long) / 4;
        proplen *= sizeof(long) / 4;
        break;
    }

    int newSize = proplen;
    buffer->resize(newSize);

    bool ok = (buffer->size() == newSize);
    VDEBUG("QClipboard: read_property(): buffer resized to %d", buffer->size());

    if (ok && newSize) {
        // could allocate buffer

        while (bytes_left) {
            // more to read...

            r = XGetWindowProperty(display, win, property, offset, maxsize/4,
                                   False, AnyPropertyType, type, format,
                                   &length, &bytes_left, &data);
            if (r != Success || (type && *type == XNone))
                break;

            offset += length / (32 / *format);
            length *= format_inc * (*format) / 8;

            // Here we check if we get a buffer overflow and tries to
            // recover -- this shouldn't normally happen, but it doesn't
            // hurt to be defensive
            if ((int)(buffer_offset + length) > buffer->size()) {
                length = buffer->size() - buffer_offset;

                // escape loop
                bytes_left = 0;
            }

            memcpy(buffer->data() + buffer_offset, data, length);
            buffer_offset += length;

            XFree((char*)data);
        }

        if (*format == 8 && *type == ATOM(COMPOUND_TEXT)) {
            // convert COMPOUND_TEXT to a multibyte string
            XTextProperty textprop;
            textprop.encoding = *type;
            textprop.format = *format;
            textprop.nitems = buffer_offset;
            textprop.value = (unsigned char *) buffer->data();

            char **list_ret = 0;
            int count;
            if (XmbTextPropertyToTextList(display, &textprop, &list_ret,
                         &count) == Success && count && list_ret) {
                offset = buffer_offset = strlen(list_ret[0]);
                buffer->resize(offset);
                memcpy(buffer->data(), list_ret[0], offset);
            }
            if (list_ret) XFreeStringList(list_ret);
        }
    }

    // correct size, not 0-term.
    if (size)
        *size = buffer_offset;

    VDEBUG("QClipboard: read_property(): buffer size %d, buffer offset %d, offset %d",
           buffer->size(), buffer_offset, offset);

    if (deleteProperty)
        XDeleteProperty(display, win, property);

    XFlush(display);

    return ok;
}

QByteArray QX11Data::clipboardReadIncrementalProperty(Window win, Atom property, int nbytes, bool nullterm)
{
    XEvent event;

    QByteArray buf;
    QByteArray tmp_buf;
    bool alloc_error = false;
    int  length;
    int  offset = 0;

    if (nbytes > 0) {
        // Reserve buffer + zero-terminator (for text data)
        // We want to complete the INCR transfer even if we cannot
        // allocate more memory
        buf.resize(nbytes+1);
        alloc_error = buf.size() != nbytes+1;
    }

    for (;;) {
        XFlush(display);
        if (!clipboardWaitForEvent(win,PropertyNotify,&event,clipboard_timeout))
            break;
        if (event.xproperty.atom != property ||
             event.xproperty.state != PropertyNewValue)
            continue;
        if (X11->clipboardReadProperty(win, property, true, &tmp_buf, &length, 0, 0)) {
            if (length == 0) {                // no more data, we're done
                if (nullterm) {
                    buf.resize(offset+1);
                    buf[offset] = '\0';
                } else {
                    buf.resize(offset);
                }
                return buf;
            } else if (!alloc_error) {
                if (offset+length > (int)buf.size()) {
                    buf.resize(offset+length+65535);
                    if (buf.size() != offset+length+65535) {
                        alloc_error = true;
                        length = buf.size() - offset;
                    }
                }
                memcpy(buf.data()+offset, tmp_buf.constData(), length);
                tmp_buf.resize(0);
                offset += length;
            }
        } else {
            break;
        }
    }

    // timed out ... create a new requestor window, otherwise the requestor
    // could consider next request to be still part of this timed out request
    delete requestor;
    requestor = new QWidget(0);
    requestor->setObjectName(QLatin1String("internal clipboard requestor"));
    // We don't need this internal widget to appear in QApplication::topLevelWidgets()
    if (QWidgetPrivate::allWidgets)
        QWidgetPrivate::allWidgets->remove(requestor);

    return QByteArray();
}

static Atom send_targets_selection(QClipboardData *d, Window window, Atom property)
{
    QVector<Atom> types;
    QStringList formats = QInternalMimeData::formatsHelper(d->source());
    for (int i = 0; i < formats.size(); ++i) {
        QList<Atom> atoms = X11->xdndMimeAtomsForFormat(formats.at(i));
        for (int j = 0; j < atoms.size(); ++j) {
            if (!types.contains(atoms.at(j)))
                types.append(atoms.at(j));
        }
    }
    types.append(ATOM(TARGETS));
    types.append(ATOM(MULTIPLE));
    types.append(ATOM(TIMESTAMP));
    types.append(ATOM(SAVE_TARGETS));

    XChangeProperty(X11->display, window, property, XA_ATOM, 32,
                    PropModeReplace, (uchar *) types.data(), types.size());
    return property;
}

static Atom send_selection(QClipboardData *d, Atom target, Window window, Atom property)
{
    Atom atomFormat = target;
    int dataFormat = 0;
    QByteArray data;

    QByteArray fmt = X11->xdndAtomToString(target);
    if (fmt.isEmpty()) { // Not a MIME type we have
        DEBUG("QClipboard: send_selection(): converting to type '%s' is not supported", fmt.data());
        return XNone;
    }
    DEBUG("QClipboard: send_selection(): converting to type '%s'", fmt.data());

    if (X11->xdndMimeDataForAtom(target, d->source(), &data, &atomFormat, &dataFormat)) {

        VDEBUG("QClipboard: send_selection():\n"
          "    property type %lx\n"
          "    property name '%s'\n"
          "    format %d\n"
          "    %d bytes\n",
          target, X11->xdndMimeAtomToString(atomFormat).toLatin1().data(), dataFormat, data.size());

         // don't allow INCR transfers when using MULTIPLE or to
        // Motif clients (since Motif doesn't support INCR)
        static Atom motif_clip_temporary = ATOM(CLIP_TEMPORARY);
        bool allow_incr = property != motif_clip_temporary;

        // X_ChangeProperty protocol request is 24 bytes
        const int increment = (XMaxRequestSize(X11->display) * 4) - 24;
        if (data.size() > increment && allow_incr) {
            long bytes = data.size();
            XChangeProperty(X11->display, window, property,
                            ATOM(INCR), 32, PropModeReplace, (uchar *) &bytes, 1);

            (void)new QClipboardINCRTransaction(window, property, atomFormat, dataFormat, data, increment);
            return property;
        }

        // make sure we can perform the XChangeProperty in a single request
        if (data.size() > increment)
            return XNone; // ### perhaps use several XChangeProperty calls w/ PropModeAppend?
        int dataSize = data.size() / (dataFormat / 8);
        // use a single request to transfer data
        XChangeProperty(X11->display, window, property, atomFormat,
                        dataFormat, PropModeReplace, (uchar *) data.data(),
                        dataSize);
    }
    return property;
}

/*! \internal
    Internal cleanup for Windows.
*/
void QClipboard::ownerDestroyed()
{ }


/*! \internal
    Internal optimization for Windows.
*/
void QClipboard::connectNotify(const char *)
{ }


bool QClipboard::event(QEvent *e)
{
    if (e->type() == QEvent::Timer) {
        QTimerEvent *te = (QTimerEvent *) e;

        if (waiting_for_data) // should never happen
            return false;

        if (te->timerId() == timer_id) {
            killTimer(timer_id);
            timer_id = 0;

            timer_event_clear = true;
            if (selection_watcher) // clear selection
                selectionData()->clear();
            if (clipboard_watcher) // clear clipboard
                clipboardData()->clear();
            timer_event_clear = false;

            return true;
        } else if (te->timerId() == pending_timer_id) {
            // I hate klipper
            killTimer(pending_timer_id);
            pending_timer_id = 0;

            if (pending_clipboard_changed) {
                pending_clipboard_changed = false;
                clipboardData()->clear();
                emitChanged(QClipboard::Clipboard);
            }
            if (pending_selection_changed) {
                pending_selection_changed = false;
                selectionData()->clear();
                emitChanged(QClipboard::Selection);
            }

            return true;
        } else if (te->timerId() == incr_timer_id) {
            killTimer(incr_timer_id);
            incr_timer_id = 0;

            qt_xclb_incr_timeout();

            return true;
        } else {
            return QObject::event(e);
        }
    } else if (e->type() != QEvent::Clipboard) {
        return QObject::event(e);
    }

    XEvent *xevent = (XEvent *)(((QClipboardEvent *)e)->data());
    Display *dpy = X11->display;

    if (!xevent) {
        // That means application exits and we need to give clipboard
        // content to the clipboard manager.
        // First we check if there is a clipboard manager.
        if (XGetSelectionOwner(X11->display, ATOM(CLIPBOARD_MANAGER)) == XNone
            || !owner)
            return true;

        Window ownerId = owner->internalWinId();
        Q_ASSERT(ownerId);
        // we delete the property so the manager saves all TARGETS.
        XDeleteProperty(X11->display, ownerId, ATOM(_QT_SELECTION));
        XConvertSelection(X11->display, ATOM(CLIPBOARD_MANAGER), ATOM(SAVE_TARGETS),
                          ATOM(_QT_SELECTION), ownerId, X11->time);
        XSync(dpy, false);

        XEvent event;
        // waiting until the clipboard manager fetches the content.
        if (!X11->clipboardWaitForEvent(ownerId, SelectionNotify, &event, 10000, true)) {
            qWarning("QClipboard: Unable to receive an event from the "
                     "clipboard manager in a reasonable time");
        }

        return true;
    }

    switch (xevent->type) {

    case SelectionClear:
        // new selection owner
        if (xevent->xselectionclear.selection == XA_PRIMARY) {
            QClipboardData *d = selectionData();

            // ignore the event if it was generated before we gained selection ownership
            if (d->timestamp != CurrentTime && xevent->xselectionclear.time <= d->timestamp)
                break;

            DEBUG("QClipboard: new selection owner 0x%lx at time %lx (ours %lx)",
                  XGetSelectionOwner(dpy, XA_PRIMARY),
                  xevent->xselectionclear.time, d->timestamp);

            if (! waiting_for_data) {
                d->clear();
                emitChanged(QClipboard::Selection);
            } else {
                pending_selection_changed = true;
                if (! pending_timer_id)
                    pending_timer_id = QApplication::clipboard()->startTimer(0);
            }
        } else if (xevent->xselectionclear.selection == ATOM(CLIPBOARD)) {
            QClipboardData *d = clipboardData();

            // ignore the event if it was generated before we gained selection ownership
            if (d->timestamp != CurrentTime && xevent->xselectionclear.time <= d->timestamp)
                break;

            DEBUG("QClipboard: new clipboard owner 0x%lx at time %lx (%lx)",
                  XGetSelectionOwner(dpy, ATOM(CLIPBOARD)),
                  xevent->xselectionclear.time, d->timestamp);

            if (! waiting_for_data) {
                d->clear();
                emitChanged(QClipboard::Clipboard);
            } else {
                pending_clipboard_changed = true;
                if (! pending_timer_id)
                    pending_timer_id = QApplication::clipboard()->startTimer(0);
            }
        } else {
            qWarning("QClipboard: Unknown SelectionClear event received");
            return false;
        }
        break;

    case SelectionNotify:
        /*
          Something has delivered data to us, but this was not caught
          by QClipboardWatcher::getDataInFormat()

          Just skip the event to prevent Bad Things (tm) from
          happening later on...
        */
        break;

    case SelectionRequest:
        {
            // someone wants our data
            XSelectionRequestEvent *req = &xevent->xselectionrequest;

            if (requestor && req->requestor == requestor->internalWinId())
                break;

            XEvent event;
            event.xselection.type      = SelectionNotify;
            event.xselection.display   = req->display;
            event.xselection.requestor = req->requestor;
            event.xselection.selection = req->selection;
            event.xselection.target    = req->target;
            event.xselection.property  = XNone;
            event.xselection.time      = req->time;

            DEBUG("QClipboard: SelectionRequest from %lx\n"
                  "    selection 0x%lx (%s) target 0x%lx (%s)",
                  req->requestor,
                  req->selection,
                  X11->xdndAtomToString(req->selection).data(),
                  req->target,
                  X11->xdndAtomToString(req->target).data());

            QClipboardData *d;
            if (req->selection == XA_PRIMARY) {
                d = selectionData();
            } else if (req->selection == ATOM(CLIPBOARD)) {
                d = clipboardData();
            } else {
                qWarning("QClipboard: Unknown selection '%lx'", req->selection);
                XSendEvent(dpy, req->requestor, False, NoEventMask, &event);
                break;
            }

            if (! d->source()) {
                qWarning("QClipboard: Cannot transfer data, no data available");
                XSendEvent(dpy, req->requestor, False, NoEventMask, &event);
                break;
            }

            DEBUG("QClipboard: SelectionRequest at time %lx (ours %lx)",
                  req->time, d->timestamp);

            if (d->timestamp == CurrentTime // we don't own the selection anymore
                || (req->time != CurrentTime && req->time < d->timestamp)) {
                DEBUG("QClipboard: SelectionRequest too old");
                XSendEvent(dpy, req->requestor, False, NoEventMask, &event);
                break;
            }

            Atom xa_targets = ATOM(TARGETS);
            Atom xa_multiple = ATOM(MULTIPLE);
            Atom xa_timestamp = ATOM(TIMESTAMP);

            struct AtomPair { Atom target; Atom property; } *multi = 0;
            Atom multi_type = XNone;
            int multi_format = 0;
            int nmulti = 0;
            int imulti = -1;
            bool multi_writeback = false;

            if (req->target == xa_multiple) {
                QByteArray multi_data;
                if (req->property == XNone
                    || !X11->clipboardReadProperty(req->requestor, req->property, false, &multi_data,
                                                   0, &multi_type, &multi_format)
                    || multi_format != 32) {
                    // MULTIPLE property not formatted correctly
                    XSendEvent(dpy, req->requestor, False, NoEventMask, &event);
                    break;
                }
                nmulti = multi_data.size()/sizeof(*multi);
                multi = new AtomPair[nmulti];
                memcpy(multi,multi_data.data(),multi_data.size());
                imulti = 0;
            }

            for (; imulti < nmulti; ++imulti) {
                Atom target;
                Atom property;

                if (multi) {
                    target = multi[imulti].target;
                    property = multi[imulti].property;
                } else {
                    target = req->target;
                    property = req->property;
                    if (property == XNone) // obsolete client
                        property = target;
                }

                Atom ret = XNone;
                if (target == XNone || property == XNone) {
                    ;
                } else if (target == xa_timestamp) {
                    if (d->timestamp != CurrentTime) {
                        XChangeProperty(dpy, req->requestor, property, XA_INTEGER, 32,
                                        PropModeReplace, (uchar *) &d->timestamp, 1);
                        ret = property;
                    } else {
                        qWarning("QClipboard: Invalid data timestamp");
                    }
                } else if (target == xa_targets) {
                    ret = send_targets_selection(d, req->requestor, property);
                } else {
                    ret = send_selection(d, target, req->requestor, property);
                }

                if (nmulti > 0) {
                    if (ret == XNone) {
                        multi[imulti].property = XNone;
                        multi_writeback = true;
                    }
                } else {
                    event.xselection.property = ret;
                    break;
                }
            }

            if (nmulti > 0) {
                if (multi_writeback) {
                    // according to ICCCM 2.6.2 says to put None back
                    // into the original property on the requestor window
                    XChangeProperty(dpy, req->requestor, req->property, multi_type, 32,
                                    PropModeReplace, (uchar *) multi, nmulti * 2);
                }

                delete [] multi;
                event.xselection.property = req->property;
            }

            // send selection notify to requestor
            XSendEvent(dpy, req->requestor, False, NoEventMask, &event);

            DEBUG("QClipboard: SelectionNotify to 0x%lx\n"
                  "    property 0x%lx (%s)",
                  req->requestor, event.xselection.property,
                  X11->xdndAtomToString(event.xselection.property).data());
        }
        break;
    }

    return true;
}






QClipboardWatcher::QClipboardWatcher(QClipboard::Mode mode)
    : QInternalMimeData()
{
    switch (mode) {
    case QClipboard::Selection:
        atom = XA_PRIMARY;
        break;

    case QClipboard::Clipboard:
        atom = ATOM(CLIPBOARD);
        break;

    default:
        qWarning("QClipboardWatcher: Internal error: Unsupported clipboard mode");
        break;
    }

    setupOwner();
}

QClipboardWatcher::~QClipboardWatcher()
{
    if(selection_watcher == this)
        selection_watcher = 0;
    if(clipboard_watcher == this)
        clipboard_watcher = 0;
}

bool QClipboardWatcher::empty() const
{
    Display *dpy = X11->display;
    Window win = XGetSelectionOwner(dpy, atom);

    if(win == requestor->internalWinId()) {
        qWarning("QClipboardWatcher::empty: Internal error: Application owns the selection");
        return true;
    }

    return win == XNone;
}

QStringList QClipboardWatcher::formats_sys() const
{
    if (empty())
        return QStringList();

    if (!formatList.count()) {
        // get the list of targets from the current clipboard owner - we do this
        // once so that multiple calls to this function don't require multiple
        // server round trips...

        format_atoms = getDataInFormat(ATOM(TARGETS));

        if (format_atoms.size() > 0) {
            Atom *targets = (Atom *) format_atoms.data();
            int size = format_atoms.size() / sizeof(Atom);

            for (int i = 0; i < size; ++i) {
                if (targets[i] == 0)
                    continue;

                QStringList formatsForAtom = X11->xdndMimeFormatsForAtom(targets[i]);
                for (int j = 0; j < formatsForAtom.size(); ++j) {
                    if (!formatList.contains(formatsForAtom.at(j)))
                        formatList.append(formatsForAtom.at(j));
                }
                VDEBUG("    format: %s", X11->xdndAtomToString(targets[i]).data());
                VDEBUG("    data:\n%s\n", getDataInFormat(targets[i]).data());
            }
            DEBUG("QClipboardWatcher::format: %d formats available", formatList.count());
        }
    }

    return formatList;
}

bool QClipboardWatcher::hasFormat_sys(const QString &format) const
{
    QStringList list = formats();
    return list.contains(format);
}

QVariant QClipboardWatcher::retrieveData_sys(const QString &fmt, QVariant::Type requestedType) const
{
    if (fmt.isEmpty() || empty())
        return QByteArray();

    (void)formats(); // trigger update of format list
    DEBUG("QClipboardWatcher::data: fetching format '%s'", fmt.toLatin1().data());

    QList<Atom> atoms;
    Atom *targets = (Atom *) format_atoms.data();
    int size = format_atoms.size() / sizeof(Atom);
    for (int i = 0; i < size; ++i)
        atoms.append(targets[i]);

    QByteArray encoding;
    Atom fmtatom = X11->xdndMimeAtomForFormat(fmt, requestedType, atoms, &encoding);

    if (fmtatom == 0)
        return QVariant();

    return X11->xdndMimeConvertToFormat(fmtatom, getDataInFormat(fmtatom), fmt, requestedType, encoding);
}

QByteArray QClipboardWatcher::getDataInFormat(Atom fmtatom) const
{
    QByteArray buf;

    Display *dpy = X11->display;
    requestor->createWinId();
    Window   win = requestor->internalWinId();
    Q_ASSERT(requestor->testAttribute(Qt::WA_WState_Created));

    DEBUG("QClipboardWatcher::getDataInFormat: selection '%s' format '%s'",
          X11->xdndAtomToString(atom).data(), X11->xdndAtomToString(fmtatom).data());

    XSelectInput(dpy, win, NoEventMask); // don't listen for any events

    XDeleteProperty(dpy, win, ATOM(_QT_SELECTION));
    XConvertSelection(dpy, atom, fmtatom, ATOM(_QT_SELECTION), win, X11->time);
    XSync(dpy, false);

    VDEBUG("QClipboardWatcher::getDataInFormat: waiting for SelectionNotify event");

    XEvent xevent;
    if (!X11->clipboardWaitForEvent(win,SelectionNotify,&xevent,clipboard_timeout) ||
         xevent.xselection.property == XNone) {
        DEBUG("QClipboardWatcher::getDataInFormat: format not available");
        return buf;
    }

    VDEBUG("QClipboardWatcher::getDataInFormat: fetching data...");

    Atom   type;
    XSelectInput(dpy, win, PropertyChangeMask);

    if (X11->clipboardReadProperty(win, ATOM(_QT_SELECTION), true, &buf, 0, &type, 0)) {
        if (type == ATOM(INCR)) {
            int nbytes = buf.size() >= 4 ? *((int*)buf.data()) : 0;
            buf = X11->clipboardReadIncrementalProperty(win, ATOM(_QT_SELECTION), nbytes, false);
        }
    }

    XSelectInput(dpy, win, NoEventMask);

    DEBUG("QClipboardWatcher::getDataInFormat: %d bytes received", buf.size());

    return buf;
}


const QMimeData* QClipboard::mimeData(Mode mode) const
{
    QClipboardData *d = 0;
    switch (mode) {
    case Selection:
        d = selectionData();
        break;
    case Clipboard:
        d = clipboardData();
        break;
    default:
        qWarning("QClipboard::mimeData: unsupported mode '%d'", mode);
        return 0;
    }

    if (! d->source() && ! timer_event_clear) {
        if (mode == Selection) {
            if (! selection_watcher)
                selection_watcher = new QClipboardWatcher(mode);
            d->setSource(selection_watcher);
        } else {
            if (! clipboard_watcher)
                clipboard_watcher = new QClipboardWatcher(mode);
            d->setSource(clipboard_watcher);
        }

        if (! timer_id) {
            // start a zero timer - we will clear cached data when the timer
            // times out, which will be the next time we hit the event loop...
            // that way, the data is cached long enough for calls within a single
            // loop/function, but the data doesn't linger around in case the selection
            // changes
            QClipboard *that = ((QClipboard *) this);
            timer_id = that->startTimer(0);
        }
    }

    return d->source();
}


void QClipboard::setMimeData(QMimeData* src, Mode mode)
{
    Atom atom, sentinel_atom;
    QClipboardData *d;
    switch (mode) {
    case Selection:
        atom = XA_PRIMARY;
        sentinel_atom = ATOM(_QT_SELECTION_SENTINEL);
        d = selectionData();
        break;

    case Clipboard:
        atom = ATOM(CLIPBOARD);
        sentinel_atom = ATOM(_QT_CLIPBOARD_SENTINEL);
        d = clipboardData();
        break;

    default:
        qWarning("QClipboard::setMimeData: unsupported mode '%d'", mode);
        return;
    }

    Display *dpy = X11->display;
    Window newOwner;

    if (! src) { // no data, clear clipboard contents
        newOwner = XNone;
        d->clear();
    } else {
        setupOwner();

        newOwner = owner->internalWinId();

        d->setSource(src);
        d->timestamp = X11->time;
    }

    Window prevOwner = XGetSelectionOwner(dpy, atom);
    // use X11->time, since d->timestamp == CurrentTime when clearing
    XSetSelectionOwner(dpy, atom, newOwner, X11->time);

    if (mode == Selection)
        emitChanged(QClipboard::Selection);
    else
        emitChanged(QClipboard::Clipboard);

    if (XGetSelectionOwner(dpy, atom) != newOwner) {
        qWarning("QClipboard::setData: Cannot set X11 selection owner for %s",
                 X11->xdndAtomToString(atom).data());
        d->clear();
        return;
    }

    // Signal to other Qt processes that the selection has changed
    Window owners[2];
    owners[0] = newOwner;
    owners[1] = prevOwner;
    XChangeProperty(dpy, QApplication::desktop()->screen(0)->internalWinId(),
                     sentinel_atom, XA_WINDOW, 32, PropModeReplace,
                     (unsigned char*)&owners, 2);
}


/*
  Called by the main event loop in qapplication_x11.cpp when either
  the _QT_SELECTION_SENTINEL property has been changed (i.e. when some
  Qt process has performed QClipboard::setData()) or when Xfixes told
  us that an other application changed the selection. If it returns
  true, the QClipBoard dataChanged() signal should be emitted.
*/

bool qt_check_selection_sentinel()
{
    bool doIt = true;
    if (owner && !X11->use_xfixes) {
        /*
          Since the X selection mechanism cannot give any signal when
          the selection has changed, we emulate it (for Qt processes) here.
          The notification should be ignored in case of either
          a) This is the process that did setData (because setData()
          then has already emitted dataChanged())
          b) This is the process that owned the selection when dataChanged()
          was called (because we have then received a SelectionClear event,
          and have already emitted dataChanged() as a result of that)
        */

        unsigned char *retval;
        Atom actualType;
        int actualFormat;
        ulong nitems;
        ulong bytesLeft;

        if (XGetWindowProperty(X11->display,
                               QApplication::desktop()->screen(0)->internalWinId(),
                               ATOM(_QT_SELECTION_SENTINEL), 0, 2, False, XA_WINDOW,
                               &actualType, &actualFormat, &nitems,
                               &bytesLeft, &retval) == Success) {
            Window *owners = (Window *)retval;
            if (actualType == XA_WINDOW && actualFormat == 32 && nitems == 2) {
                Window win = owner->internalWinId();
                if (owners[0] == win || owners[1] == win)
                    doIt = false;
            }

            XFree(owners);
        }
    }

    if (doIt) {
        if (waiting_for_data) {
            pending_selection_changed = true;
            if (! pending_timer_id)
                pending_timer_id = QApplication::clipboard()->startTimer(0);
            doIt = false;
        } else {
            selectionData()->clear();
        }
    }

    return doIt;
}


bool qt_check_clipboard_sentinel()
{
    bool doIt = true;
    if (owner && !X11->use_xfixes) {
        unsigned char *retval;
        Atom actualType;
        int actualFormat;
        unsigned long nitems, bytesLeft;

        if (XGetWindowProperty(X11->display,
                               QApplication::desktop()->screen(0)->internalWinId(),
                               ATOM(_QT_CLIPBOARD_SENTINEL), 0, 2, False, XA_WINDOW,
                               &actualType, &actualFormat, &nitems, &bytesLeft,
                               &retval) == Success) {
            Window *owners = (Window *)retval;
            if (actualType == XA_WINDOW && actualFormat == 32 && nitems == 2) {
                Window win = owner->internalWinId();
                if (owners[0] == win || owners[1] == win)
                    doIt = false;
            }

            XFree(owners);
        }
    }

    if (doIt) {
        if (waiting_for_data) {
            pending_clipboard_changed = true;
            if (! pending_timer_id)
                pending_timer_id = QApplication::clipboard()->startTimer(0);
            doIt = false;
        } else {
            clipboardData()->clear();
        }
    }

    return doIt;
}

bool qt_xfixes_selection_changed(Window selectionOwner, Time timestamp)
{
    QClipboardData *d = selectionData();
#ifdef QCLIPBOARD_DEBUG
    DEBUG("qt_xfixes_selection_changed: owner = %u; selectionOwner = %u; internal timestamp = %u; external timestamp = %u",
          (unsigned int)(owner ? (int)owner->internalWinId() : 0), (unsigned int)selectionOwner,
          (unsigned int)(d ? d->timestamp : 0), (unsigned int)timestamp);
#endif
    if (!owner || (selectionOwner && selectionOwner != owner->internalWinId()) ||
        (!selectionOwner && (d->timestamp == CurrentTime || d->timestamp < timestamp)))
        return qt_check_selection_sentinel();
    return false;
}

bool qt_xfixes_clipboard_changed(Window clipboardOwner, Time timestamp)
{
    QClipboardData *d = clipboardData();
#ifdef QCLIPBOARD_DEBUG
    DEBUG("qt_xfixes_clipboard_changed: owner = %u; clipboardOwner = %u; internal timestamp = %u; external timestamp = %u",
          (unsigned int)(owner ? (int)owner->internalWinId() : 0), (unsigned int)clipboardOwner,
          (unsigned int)(d ? d->timestamp : 0), (unsigned int)timestamp);
#endif
    if (!owner || (clipboardOwner && clipboardOwner != owner->internalWinId()) ||
        (!clipboardOwner && (d->timestamp == CurrentTime || d->timestamp < timestamp)))
        return qt_check_clipboard_sentinel();
    return false;
}

QT_END_NAMESPACE

#endif // QT_NO_CLIPBOARD