d5af6de69c8c5747779ff96c9a72e8fe58715712
[profile/ivi/qtbase.git] / src / plugins / platforms / cocoa / qmacclipboard.mm
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the plugins of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qmacclipboard.h"
43 #include "qclipboard.h"
44 #include "qapplication.h"
45 #include "qbitmap.h"
46 #include "qdatetime.h"
47 #include "qdebug.h"
48 #include "qguiapplication.h"
49 #include "qevent.h"
50 #include "qurl.h"
51 #include <stdlib.h>
52 #include <string.h>
53 #include "qcocoahelpers.h"
54 #include "qmacmime.h"
55 #include "qcocoaautoreleasepool.h"
56
57 QT_BEGIN_NAMESPACE
58
59 QT_USE_NAMESPACE
60
61 /*****************************************************************************
62   QClipboard debug facilities
63  *****************************************************************************/
64 //#define DEBUG_PASTEBOARD
65
66 #ifndef QT_NO_CLIPBOARD
67
68 /*****************************************************************************
69   QClipboard member functions for mac.
70  *****************************************************************************/
71
72 static QMacPasteboard *qt_mac_pasteboards[2] = {0, 0};
73
74 static inline QMacPasteboard *qt_mac_pasteboard(QClipboard::Mode mode)
75 {
76     Q_ASSERT(mode == QClipboard::Clipboard || mode == QClipboard::FindBuffer);
77     if (mode == QClipboard::Clipboard)
78         return qt_mac_pasteboards[0];
79     else
80         return qt_mac_pasteboards[1];
81 }
82
83 static void qt_mac_cleanupPasteboard() {
84     delete qt_mac_pasteboards[0];
85     delete qt_mac_pasteboards[1];
86     qt_mac_pasteboards[0] = 0;
87     qt_mac_pasteboards[1] = 0;
88 }
89
90 static bool qt_mac_updateScrap(QClipboard::Mode mode)
91 {
92     if (!qt_mac_pasteboards[0]) {
93         qt_mac_pasteboards[0] = new QMacPasteboard(kPasteboardClipboard, QMacPasteboardMime::MIME_CLIP);
94         qt_mac_pasteboards[1] = new QMacPasteboard(kPasteboardFind, QMacPasteboardMime::MIME_CLIP);
95         qAddPostRoutine(qt_mac_cleanupPasteboard);
96         return true;
97     }
98     return qt_mac_pasteboard(mode)->sync();
99 }
100
101 void QClipboard::clear(Mode mode)
102 {
103     if (!supportsMode(mode))
104         return;
105     qt_mac_updateScrap(mode);
106     qt_mac_pasteboard(mode)->clear();
107     setMimeData(0, mode);
108 }
109
110 void QClipboard::ownerDestroyed()
111 {
112 }
113
114
115 void QClipboard::connectNotify(const char *signal)
116 {
117     Q_UNUSED(signal);
118 }
119
120 bool QClipboard::event(QEvent *e)
121 {
122     if (e->type() != QEvent::Clipboard)
123         return QObject::event(e);
124
125     if (qt_mac_updateScrap(QClipboard::Clipboard)) {
126         emitChanged(QClipboard::Clipboard);
127     }
128
129     if (qt_mac_updateScrap(QClipboard::FindBuffer)) {
130         emitChanged(QClipboard::FindBuffer);
131     }
132
133     return QObject::event(e);
134 }
135
136 const QMimeData *QClipboard::mimeData(Mode mode) const
137 {
138     if (!supportsMode(mode))
139         return 0;
140     qt_mac_updateScrap(mode);
141     return qt_mac_pasteboard(mode)->mimeData();
142 }
143
144 void QClipboard::setMimeData(QMimeData *src, Mode mode)
145 {
146     if (!supportsMode(mode))
147         return;
148     qt_mac_updateScrap(mode);
149     qt_mac_pasteboard(mode)->setMimeData(src);
150     emitChanged(mode);
151 }
152
153 bool QClipboard::supportsMode(Mode mode) const
154 {
155     return (mode == Clipboard || mode == FindBuffer);
156 }
157
158 bool QClipboard::ownsMode(Mode mode) const
159 {
160     Q_UNUSED(mode);
161     return false;
162 }
163
164 #endif // QT_NO_CLIPBOARD
165
166 /*****************************************************************************
167    QMacPasteboard code
168 *****************************************************************************/
169
170 QMacPasteboard::QMacPasteboard(PasteboardRef p, uchar mt)
171 {
172     mac_mime_source = false;
173     mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
174     paste = p;
175     CFRetain(paste);
176 }
177
178 QMacPasteboard::QMacPasteboard(uchar mt)
179 {
180     mac_mime_source = false;
181     mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
182     paste = 0;
183     OSStatus err = PasteboardCreate(0, &paste);
184     if (err == noErr) {
185         PasteboardSetPromiseKeeper(paste, promiseKeeper, this);
186     } else {
187         qDebug("PasteBoard: Error creating pasteboard: [%d]", (int)err);
188     }
189 }
190
191 QMacPasteboard::QMacPasteboard(CFStringRef name, uchar mt)
192 {
193     mac_mime_source = false;
194     mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
195     paste = 0;
196     OSStatus err = PasteboardCreate(name, &paste);
197     if (err == noErr) {
198         PasteboardSetPromiseKeeper(paste, promiseKeeper, this);
199     } else {
200         qDebug("PasteBoard: Error creating pasteboard: %s [%d]", QCFString::toQString(name).toLatin1().constData(), (int)err);
201     }
202 }
203
204 QMacPasteboard::~QMacPasteboard()
205 {
206     // commit all promises for paste after exit close
207     for (int i = 0; i < promises.count(); ++i) {
208         const Promise &promise = promises.at(i);
209         QCFString flavor = QCFString(promise.convertor->flavorFor(promise.mime));
210         promiseKeeper(paste, (PasteboardItemID)promise.itemId, flavor, this);
211     }
212
213     if (paste)
214         CFRelease(paste);
215 }
216
217 PasteboardRef
218 QMacPasteboard::pasteBoard() const
219 {
220     return paste;
221 }
222
223 OSStatus QMacPasteboard::promiseKeeper(PasteboardRef paste, PasteboardItemID id, CFStringRef flavor, void *_qpaste)
224 {
225     QMacPasteboard *qpaste = (QMacPasteboard*)_qpaste;
226     const long promise_id = (long)id;
227
228     // Find the kept promise
229     const QString flavorAsQString = QCFString::toQString(flavor);
230     QMacPasteboard::Promise promise;
231     for (int i = 0; i < qpaste->promises.size(); i++){
232         QMacPasteboard::Promise tmp = qpaste->promises[i];
233         if (tmp.itemId == promise_id && tmp.convertor->canConvert(tmp.mime, flavorAsQString)){
234             promise = tmp;
235             break;
236         }
237     }
238
239     if (!promise.itemId && flavorAsQString == QLatin1String("com.trolltech.qt.MimeTypeName")) {
240         // we have promised this data, but wont be able to convert, so return null data.
241         // This helps in making the application/x-qt-mime-type-name hidden from normal use.
242         QByteArray ba;
243         QCFType<CFDataRef> data = CFDataCreate(0, (UInt8*)ba.constData(), ba.size());
244         PasteboardPutItemFlavor(paste, id, flavor, data, kPasteboardFlavorNoFlags);
245         return noErr;
246     }
247
248     if (!promise.itemId) {
249         // There was no promise that could deliver data for the
250         // given id and flavor. This should not happend.
251         qDebug("Pasteboard: %d: Request for %ld, %s, but no promise found!", __LINE__, promise_id, qPrintable(flavorAsQString));
252         return cantGetFlavorErr;
253     }
254
255 #ifdef DEBUG_PASTEBOARD
256     qDebug("PasteBoard: Calling in promise for %s[%ld] [%s] (%s) [%d]", qPrintable(promise.mime), promise_id,
257            qPrintable(flavorAsQString), qPrintable(promise.convertor->convertorName()), promise.offset);
258 #endif
259
260     QList<QByteArray> md = promise.convertor->convertFromMime(promise.mime, promise.data, flavorAsQString);
261     if (md.size() <= promise.offset)
262         return cantGetFlavorErr;
263     const QByteArray &ba = md[promise.offset];
264     QCFType<CFDataRef> data = CFDataCreate(0, (UInt8*)ba.constData(), ba.size());
265     PasteboardPutItemFlavor(paste, id, flavor, data, kPasteboardFlavorNoFlags);
266     return noErr;
267 }
268
269 bool
270 QMacPasteboard::hasOSType(int c_flavor) const
271 {
272     if (!paste)
273         return false;
274
275     sync();
276
277     ItemCount cnt = 0;
278     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
279         return false;
280
281 #ifdef DEBUG_PASTEBOARD
282     qDebug("PasteBoard: hasOSType [%c%c%c%c]", (c_flavor>>24)&0xFF, (c_flavor>>16)&0xFF,
283            (c_flavor>>8)&0xFF, (c_flavor>>0)&0xFF);
284 #endif
285     for (uint index = 1; index <= cnt; ++index) {
286
287         PasteboardItemID id;
288         if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
289             return false;
290
291         QCFType<CFArrayRef> types;
292         if (PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
293             return false;
294
295         const int type_count = CFArrayGetCount(types);
296         for (int i = 0; i < type_count; ++i) {
297             CFStringRef flavor = (CFStringRef)CFArrayGetValueAtIndex(types, i);
298             const int os_flavor = UTGetOSTypeFromString(UTTypeCopyPreferredTagWithClass(flavor, kUTTagClassOSType));
299             if (os_flavor == c_flavor) {
300 #ifdef DEBUG_PASTEBOARD
301                 qDebug("  - Found!");
302 #endif
303                 return true;
304             }
305         }
306     }
307 #ifdef DEBUG_PASTEBOARD
308     qDebug("  - NotFound!");
309 #endif
310     return false;
311 }
312
313 bool
314 QMacPasteboard::hasFlavor(QString c_flavor) const
315 {
316     if (!paste)
317         return false;
318
319     sync();
320
321     ItemCount cnt = 0;
322     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
323         return false;
324
325 #ifdef DEBUG_PASTEBOARD
326     qDebug("PasteBoard: hasFlavor [%s]", qPrintable(c_flavor));
327 #endif
328     for (uint index = 1; index <= cnt; ++index) {
329
330         PasteboardItemID id;
331         if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
332             return false;
333
334         PasteboardFlavorFlags flags;
335         if (PasteboardGetItemFlavorFlags(paste, id, QCFString(c_flavor), &flags) == noErr) {
336 #ifdef DEBUG_PASTEBOARD
337             qDebug("  - Found!");
338 #endif
339             return true;
340         }
341     }
342 #ifdef DEBUG_PASTEBOARD
343     qDebug("  - NotFound!");
344 #endif
345     return false;
346 }
347
348 class QMacPasteboardMimeSource : public QMimeData {
349     const QMacPasteboard *paste;
350 public:
351     QMacPasteboardMimeSource(const QMacPasteboard *p) : QMimeData(), paste(p) { }
352     ~QMacPasteboardMimeSource() { }
353     virtual QStringList formats() const { return paste->formats(); }
354     virtual QVariant retrieveData(const QString &format, QVariant::Type type) const { return paste->retrieveData(format, type); }
355 };
356
357 QMimeData
358 *QMacPasteboard::mimeData() const
359 {
360     if (!mime) {
361         mac_mime_source = true;
362         mime = new QMacPasteboardMimeSource(this);
363
364     }
365     return mime;
366 }
367
368 class QMacMimeData : public QMimeData
369 {
370 public:
371     QVariant variantData(const QString &mime) { return retrieveData(mime, QVariant::Invalid); }
372 private:
373     QMacMimeData();
374 };
375
376 void
377 QMacPasteboard::setMimeData(QMimeData *mime_src)
378 {
379     if (!paste)
380         return;
381
382     if (mime == mime_src || (!mime_src && mime && mac_mime_source))
383         return;
384     mac_mime_source = false;
385     delete mime;
386     mime = mime_src;
387
388     QList<QMacPasteboardMime*> availableConverters = QMacPasteboardMime::all(mime_type);
389     if (mime != 0) {
390         clear_helper();
391         QStringList formats = mime_src->formats();
392
393         // QMimeData sub classes reimplementing the formats() might not expose the
394         // temporary "application/x-qt-mime-type-name" mimetype. So check the existence
395         // of this mime type while doing drag and drop.
396         QString dummyMimeType(QLatin1String("application/x-qt-mime-type-name"));
397         if (!formats.contains(dummyMimeType)) {
398             QByteArray dummyType = mime_src->data(dummyMimeType);
399             if (!dummyType.isEmpty()) {
400                 formats.append(dummyMimeType);
401             }
402         }
403         for (int f = 0; f < formats.size(); ++f) {
404             QString mimeType = formats.at(f);
405             for (QList<QMacPasteboardMime *>::Iterator it = availableConverters.begin(); it != availableConverters.end(); ++it) {
406                 QMacPasteboardMime *c = (*it);
407                 QString flavor(c->flavorFor(mimeType));
408                 if (!flavor.isEmpty()) {
409                     QVariant mimeData = static_cast<QMacMimeData*>(mime_src)->variantData(mimeType);
410 #if 0
411                     //### Grrr, why didn't I put in a virtual int QMacPasteboardMime::count()? --Sam
412                     const int numItems = c->convertFromMime(mimeType, mimeData, flavor).size();
413 #else
414                     int numItems = 1; //this is a hack but it is much faster than allowing conversion above
415                     if (c->convertorName() == QLatin1String("FileURL"))
416                         numItems = mime_src->urls().count();
417 #endif
418                     for (int item = 0; item < numItems; ++item) {
419                         const int itemID = item+1; //id starts at 1
420                         promises.append(QMacPasteboard::Promise(itemID, c, mimeType, mimeData, item));
421                         PasteboardPutItemFlavor(paste, (PasteboardItemID)itemID, QCFString(flavor), 0, kPasteboardFlavorNoFlags);
422 #ifdef DEBUG_PASTEBOARD
423                         qDebug(" -  adding %d %s [%s] <%s> [%d]",
424                                itemID, qPrintable(mimeType), qPrintable(flavor), qPrintable(c->convertorName()), item);
425 #endif
426                     }
427                 }
428             }
429         }
430     }
431 }
432
433 QStringList
434 QMacPasteboard::formats() const
435 {
436     if (!paste)
437         return QStringList();
438
439     sync();
440
441     QStringList ret;
442     ItemCount cnt = 0;
443     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
444         return ret;
445
446 #ifdef DEBUG_PASTEBOARD
447     qDebug("PasteBoard: Formats [%d]", (int)cnt);
448 #endif
449     for (uint index = 1; index <= cnt; ++index) {
450
451         PasteboardItemID id;
452         if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
453             continue;
454
455         QCFType<CFArrayRef> types;
456         if (PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
457             continue;
458
459         const int type_count = CFArrayGetCount(types);
460         for (int i = 0; i < type_count; ++i) {
461             const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
462 #ifdef DEBUG_PASTEBOARD
463             qDebug(" -%s", qPrintable(QString(flavor)));
464 #endif
465             QString mimeType = QMacPasteboardMime::flavorToMime(mime_type, flavor);
466             if (!mimeType.isEmpty() && !ret.contains(mimeType)) {
467 #ifdef DEBUG_PASTEBOARD
468                 qDebug("   -<%d> %s [%s]", ret.size(), qPrintable(mimeType), qPrintable(QString(flavor)));
469 #endif
470                 ret << mimeType;
471             }
472         }
473     }
474     return ret;
475 }
476
477 bool
478 QMacPasteboard::hasFormat(const QString &format) const
479 {
480     if (!paste)
481         return false;
482
483     sync();
484
485     ItemCount cnt = 0;
486     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
487         return false;
488
489 #ifdef DEBUG_PASTEBOARD
490     qDebug("PasteBoard: hasFormat [%s]", qPrintable(format));
491 #endif
492     for (uint index = 1; index <= cnt; ++index) {
493
494         PasteboardItemID id;
495         if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
496             continue;
497
498         QCFType<CFArrayRef> types;
499         if (PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
500             continue;
501
502         const int type_count = CFArrayGetCount(types);
503         for (int i = 0; i < type_count; ++i) {
504             const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
505 #ifdef DEBUG_PASTEBOARD
506             qDebug(" -%s [0x%x]", qPrintable(QString(flavor)), mime_type);
507 #endif
508             QString mimeType = QMacPasteboardMime::flavorToMime(mime_type, flavor);
509 #ifdef DEBUG_PASTEBOARD
510             if (!mimeType.isEmpty())
511                 qDebug("   - %s", qPrintable(mimeType));
512 #endif
513             if (mimeType == format)
514                 return true;
515         }
516     }
517     return false;
518 }
519
520 QVariant
521 QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const
522 {
523     if (!paste)
524         return QVariant();
525
526     sync();
527
528     ItemCount cnt = 0;
529     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
530         return QByteArray();
531
532 #ifdef DEBUG_PASTEBOARD
533     qDebug("Pasteboard: retrieveData [%s]", qPrintable(format));
534 #endif
535     const QList<QMacPasteboardMime *> mimes = QMacPasteboardMime::all(mime_type);
536     for (int mime = 0; mime < mimes.size(); ++mime) {
537         QMacPasteboardMime *c = mimes.at(mime);
538         QString c_flavor = c->flavorFor(format);
539         if (!c_flavor.isEmpty()) {
540             // Handle text/plain a little differently. Try handling Unicode first.
541             bool checkForUtf16 = (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text")
542                                   || c_flavor == QLatin1String("public.utf8-plain-text"));
543             if (checkForUtf16 || c_flavor == QLatin1String("public.utf16-plain-text")) {
544                 // Try to get the NSStringPboardType from NSPasteboard, newlines are mapped
545                 // correctly (as '\n') in this data. The 'public.utf16-plain-text' type
546                 // usually maps newlines to '\r' instead.
547                 QString str = qt_mac_get_pasteboardString(paste);
548                 if (!str.isEmpty())
549                     return str;
550             }
551             if (checkForUtf16 && hasFlavor(QLatin1String("public.utf16-plain-text")))
552                 c_flavor = QLatin1String("public.utf16-plain-text");
553
554             QVariant ret;
555             QList<QByteArray> retList;
556             for (uint index = 1; index <= cnt; ++index) {
557                 PasteboardItemID id;
558                 if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
559                     continue;
560
561                 QCFType<CFArrayRef> types;
562                 if (PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
563                     continue;
564
565                 const int type_count = CFArrayGetCount(types);
566                 for (int i = 0; i < type_count; ++i) {
567                     CFStringRef flavor = static_cast<CFStringRef>(CFArrayGetValueAtIndex(types, i));
568                     if (c_flavor == QCFString::toQString(flavor)) {
569                         QCFType<CFDataRef> macBuffer;
570                         if (PasteboardCopyItemFlavorData(paste, id, flavor, &macBuffer) == noErr) {
571                             QByteArray buffer((const char *)CFDataGetBytePtr(macBuffer), CFDataGetLength(macBuffer));
572                             if (!buffer.isEmpty()) {
573 #ifdef DEBUG_PASTEBOARD
574                                 qDebug("  - %s [%s] (%s)", qPrintable(format), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
575 #endif
576                                 buffer.detach(); //detach since we release the macBuffer
577                                 retList.append(buffer);
578                                 break; //skip to next element
579                             }
580                         }
581                     } else {
582 #ifdef DEBUG_PASTEBOARD
583                         qDebug("  - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
584 #endif
585                     }
586                 }
587             }
588
589             if (!retList.isEmpty()) {
590                 ret = c->convertToMime(format, retList, c_flavor);
591                 return ret;
592             }
593         }
594     }
595     return QVariant();
596 }
597
598 void QMacPasteboard::clear_helper()
599 {
600     if (paste)
601         PasteboardClear(paste);
602     promises.clear();
603 }
604
605 void
606 QMacPasteboard::clear()
607 {
608 #ifdef DEBUG_PASTEBOARD
609     qDebug("PasteBoard: clear!");
610 #endif
611     clear_helper();
612 }
613
614 bool
615 QMacPasteboard::sync() const
616 {
617     if (!paste)
618         return false;
619     const bool fromGlobal = PasteboardSynchronize(paste) & kPasteboardModified;
620
621     if (fromGlobal)
622         const_cast<QMacPasteboard *>(this)->setMimeData(0);
623
624 #ifdef DEBUG_PASTEBOARD
625     if (fromGlobal)
626         qDebug("Pasteboard: Synchronize!");
627 #endif
628     return fromGlobal;
629 }
630
631
632 QString qt_mac_get_pasteboardString(PasteboardRef paste)
633 {
634     QCocoaAutoReleasePool pool;
635     NSPasteboard *pb = nil;
636     CFStringRef pbname;
637     if (PasteboardCopyName(paste, &pbname) == noErr) {
638         pb = [NSPasteboard pasteboardWithName:const_cast<NSString *>(reinterpret_cast<const NSString *>(pbname))];
639         CFRelease(pbname);
640     } else {
641         pb = [NSPasteboard generalPasteboard];
642     }
643     if (pb) {
644         NSString *text = [pb stringForType:NSStringPboardType];
645         if (text)
646             return QCFString::toQString(text);
647     }
648     return QString();
649 }
650
651
652
653 QT_END_NAMESPACE