Implement cocoa clipboard support.
[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 /*****************************************************************************
67    QMacPasteboard code
68 *****************************************************************************/
69
70 QMacPasteboard::QMacPasteboard(PasteboardRef p, uchar mt)
71 {
72     mac_mime_source = false;
73     mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
74     paste = p;
75     CFRetain(paste);
76 }
77
78 QMacPasteboard::QMacPasteboard(uchar mt)
79 {
80     mac_mime_source = false;
81     mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
82     paste = 0;
83     OSStatus err = PasteboardCreate(0, &paste);
84     if (err == noErr) {
85         PasteboardSetPromiseKeeper(paste, promiseKeeper, this);
86     } else {
87         qDebug("PasteBoard: Error creating pasteboard: [%d]", (int)err);
88     }
89 }
90
91 QMacPasteboard::QMacPasteboard(CFStringRef name, uchar mt)
92 {
93     mac_mime_source = false;
94     mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
95     paste = 0;
96     OSStatus err = PasteboardCreate(name, &paste);
97     if (err == noErr) {
98         PasteboardSetPromiseKeeper(paste, promiseKeeper, this);
99     } else {
100         qDebug("PasteBoard: Error creating pasteboard: %s [%d]", QCFString::toQString(name).toLatin1().constData(), (int)err);
101     }
102 }
103
104 QMacPasteboard::~QMacPasteboard()
105 {
106     // commit all promises for paste after exit close
107     for (int i = 0; i < promises.count(); ++i) {
108         const Promise &promise = promises.at(i);
109         QCFString flavor = QCFString(promise.convertor->flavorFor(promise.mime));
110         promiseKeeper(paste, (PasteboardItemID)promise.itemId, flavor, this);
111     }
112
113     if (paste)
114         CFRelease(paste);
115 }
116
117 PasteboardRef
118 QMacPasteboard::pasteBoard() const
119 {
120     return paste;
121 }
122
123 OSStatus QMacPasteboard::promiseKeeper(PasteboardRef paste, PasteboardItemID id, CFStringRef flavor, void *_qpaste)
124 {
125     QMacPasteboard *qpaste = (QMacPasteboard*)_qpaste;
126     const long promise_id = (long)id;
127
128     // Find the kept promise
129     const QString flavorAsQString = QCFString::toQString(flavor);
130     QMacPasteboard::Promise promise;
131     for (int i = 0; i < qpaste->promises.size(); i++){
132         QMacPasteboard::Promise tmp = qpaste->promises[i];
133         if (tmp.itemId == promise_id && tmp.convertor->canConvert(tmp.mime, flavorAsQString)){
134             promise = tmp;
135             break;
136         }
137     }
138
139     if (!promise.itemId && flavorAsQString == QLatin1String("com.trolltech.qt.MimeTypeName")) {
140         // we have promised this data, but wont be able to convert, so return null data.
141         // This helps in making the application/x-qt-mime-type-name hidden from normal use.
142         QByteArray ba;
143         QCFType<CFDataRef> data = CFDataCreate(0, (UInt8*)ba.constData(), ba.size());
144         PasteboardPutItemFlavor(paste, id, flavor, data, kPasteboardFlavorNoFlags);
145         return noErr;
146     }
147
148     if (!promise.itemId) {
149         // There was no promise that could deliver data for the
150         // given id and flavor. This should not happend.
151         qDebug("Pasteboard: %d: Request for %ld, %s, but no promise found!", __LINE__, promise_id, qPrintable(flavorAsQString));
152         return cantGetFlavorErr;
153     }
154
155 #ifdef DEBUG_PASTEBOARD
156     qDebug("PasteBoard: Calling in promise for %s[%ld] [%s] (%s) [%d]", qPrintable(promise.mime), promise_id,
157            qPrintable(flavorAsQString), qPrintable(promise.convertor->convertorName()), promise.offset);
158 #endif
159
160     QList<QByteArray> md = promise.convertor->convertFromMime(promise.mime, promise.data, flavorAsQString);
161     if (md.size() <= promise.offset)
162         return cantGetFlavorErr;
163     const QByteArray &ba = md[promise.offset];
164     QCFType<CFDataRef> data = CFDataCreate(0, (UInt8*)ba.constData(), ba.size());
165     PasteboardPutItemFlavor(paste, id, flavor, data, kPasteboardFlavorNoFlags);
166     return noErr;
167 }
168
169 bool
170 QMacPasteboard::hasOSType(int c_flavor) const
171 {
172     if (!paste)
173         return false;
174
175     sync();
176
177     ItemCount cnt = 0;
178     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
179         return false;
180
181 #ifdef DEBUG_PASTEBOARD
182     qDebug("PasteBoard: hasOSType [%c%c%c%c]", (c_flavor>>24)&0xFF, (c_flavor>>16)&0xFF,
183            (c_flavor>>8)&0xFF, (c_flavor>>0)&0xFF);
184 #endif
185     for (uint index = 1; index <= cnt; ++index) {
186
187         PasteboardItemID id;
188         if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
189             return false;
190
191         QCFType<CFArrayRef> types;
192         if (PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
193             return false;
194
195         const int type_count = CFArrayGetCount(types);
196         for (int i = 0; i < type_count; ++i) {
197             CFStringRef flavor = (CFStringRef)CFArrayGetValueAtIndex(types, i);
198             const int os_flavor = UTGetOSTypeFromString(UTTypeCopyPreferredTagWithClass(flavor, kUTTagClassOSType));
199             if (os_flavor == c_flavor) {
200 #ifdef DEBUG_PASTEBOARD
201                 qDebug("  - Found!");
202 #endif
203                 return true;
204             }
205         }
206     }
207 #ifdef DEBUG_PASTEBOARD
208     qDebug("  - NotFound!");
209 #endif
210     return false;
211 }
212
213 bool
214 QMacPasteboard::hasFlavor(QString c_flavor) const
215 {
216     if (!paste)
217         return false;
218
219     sync();
220
221     ItemCount cnt = 0;
222     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
223         return false;
224
225 #ifdef DEBUG_PASTEBOARD
226     qDebug("PasteBoard: hasFlavor [%s]", qPrintable(c_flavor));
227 #endif
228     for (uint index = 1; index <= cnt; ++index) {
229
230         PasteboardItemID id;
231         if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
232             return false;
233
234         PasteboardFlavorFlags flags;
235         if (PasteboardGetItemFlavorFlags(paste, id, QCFString(c_flavor), &flags) == noErr) {
236 #ifdef DEBUG_PASTEBOARD
237             qDebug("  - Found!");
238 #endif
239             return true;
240         }
241     }
242 #ifdef DEBUG_PASTEBOARD
243     qDebug("  - NotFound!");
244 #endif
245     return false;
246 }
247
248 class QMacPasteboardMimeSource : public QMimeData {
249     const QMacPasteboard *paste;
250 public:
251     QMacPasteboardMimeSource(const QMacPasteboard *p) : QMimeData(), paste(p) { }
252     ~QMacPasteboardMimeSource() { }
253     virtual QStringList formats() const { return paste->formats(); }
254     virtual QVariant retrieveData(const QString &format, QVariant::Type type) const { return paste->retrieveData(format, type); }
255 };
256
257 QMimeData
258 *QMacPasteboard::mimeData() const
259 {
260     if (!mime) {
261         mac_mime_source = true;
262         mime = new QMacPasteboardMimeSource(this);
263
264     }
265     return mime;
266 }
267
268 class QMacMimeData : public QMimeData
269 {
270 public:
271     QVariant variantData(const QString &mime) { return retrieveData(mime, QVariant::Invalid); }
272 private:
273     QMacMimeData();
274 };
275
276 void
277 QMacPasteboard::setMimeData(QMimeData *mime_src)
278 {
279     if (!paste)
280         return;
281
282     if (mime == mime_src || (!mime_src && mime && mac_mime_source))
283         return;
284     mac_mime_source = false;
285     delete mime;
286     mime = mime_src;
287
288     QList<QMacPasteboardMime*> availableConverters = QMacPasteboardMime::all(mime_type);
289     if (mime != 0) {
290         clear_helper();
291         QStringList formats = mime_src->formats();
292
293         // QMimeData sub classes reimplementing the formats() might not expose the
294         // temporary "application/x-qt-mime-type-name" mimetype. So check the existence
295         // of this mime type while doing drag and drop.
296         QString dummyMimeType(QLatin1String("application/x-qt-mime-type-name"));
297         if (!formats.contains(dummyMimeType)) {
298             QByteArray dummyType = mime_src->data(dummyMimeType);
299             if (!dummyType.isEmpty()) {
300                 formats.append(dummyMimeType);
301             }
302         }
303         for (int f = 0; f < formats.size(); ++f) {
304             QString mimeType = formats.at(f);
305             for (QList<QMacPasteboardMime *>::Iterator it = availableConverters.begin(); it != availableConverters.end(); ++it) {
306                 QMacPasteboardMime *c = (*it);
307                 QString flavor(c->flavorFor(mimeType));
308                 if (!flavor.isEmpty()) {
309                     QVariant mimeData = static_cast<QMacMimeData*>(mime_src)->variantData(mimeType);
310 #if 0
311                     //### Grrr, why didn't I put in a virtual int QMacPasteboardMime::count()? --Sam
312                     const int numItems = c->convertFromMime(mimeType, mimeData, flavor).size();
313 #else
314                     int numItems = 1; //this is a hack but it is much faster than allowing conversion above
315                     if (c->convertorName() == QLatin1String("FileURL"))
316                         numItems = mime_src->urls().count();
317 #endif
318                     for (int item = 0; item < numItems; ++item) {
319                         const int itemID = item+1; //id starts at 1
320                         promises.append(QMacPasteboard::Promise(itemID, c, mimeType, mimeData, item));
321                         PasteboardPutItemFlavor(paste, (PasteboardItemID)itemID, QCFString(flavor), 0, kPasteboardFlavorNoFlags);
322 #ifdef DEBUG_PASTEBOARD
323                         qDebug(" -  adding %d %s [%s] <%s> [%d]",
324                                itemID, qPrintable(mimeType), qPrintable(flavor), qPrintable(c->convertorName()), item);
325 #endif
326                     }
327                 }
328             }
329         }
330     }
331 }
332
333 QStringList
334 QMacPasteboard::formats() const
335 {
336     if (!paste)
337         return QStringList();
338
339     sync();
340
341     QStringList ret;
342     ItemCount cnt = 0;
343     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
344         return ret;
345
346 #ifdef DEBUG_PASTEBOARD
347     qDebug("PasteBoard: Formats [%d]", (int)cnt);
348 #endif
349     for (uint index = 1; index <= cnt; ++index) {
350
351         PasteboardItemID id;
352         if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
353             continue;
354
355         QCFType<CFArrayRef> types;
356         if (PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
357             continue;
358
359         const int type_count = CFArrayGetCount(types);
360         for (int i = 0; i < type_count; ++i) {
361             const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
362 #ifdef DEBUG_PASTEBOARD
363             qDebug(" -%s", qPrintable(QString(flavor)));
364 #endif
365             QString mimeType = QMacPasteboardMime::flavorToMime(mime_type, flavor);
366             if (!mimeType.isEmpty() && !ret.contains(mimeType)) {
367 #ifdef DEBUG_PASTEBOARD
368                 qDebug("   -<%d> %s [%s]", ret.size(), qPrintable(mimeType), qPrintable(QString(flavor)));
369 #endif
370                 ret << mimeType;
371             }
372         }
373     }
374     return ret;
375 }
376
377 bool
378 QMacPasteboard::hasFormat(const QString &format) const
379 {
380     if (!paste)
381         return false;
382
383     sync();
384
385     ItemCount cnt = 0;
386     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
387         return false;
388
389 #ifdef DEBUG_PASTEBOARD
390     qDebug("PasteBoard: hasFormat [%s]", qPrintable(format));
391 #endif
392     for (uint index = 1; index <= cnt; ++index) {
393
394         PasteboardItemID id;
395         if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
396             continue;
397
398         QCFType<CFArrayRef> types;
399         if (PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
400             continue;
401
402         const int type_count = CFArrayGetCount(types);
403         for (int i = 0; i < type_count; ++i) {
404             const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
405 #ifdef DEBUG_PASTEBOARD
406             qDebug(" -%s [0x%x]", qPrintable(QString(flavor)), mime_type);
407 #endif
408             QString mimeType = QMacPasteboardMime::flavorToMime(mime_type, flavor);
409 #ifdef DEBUG_PASTEBOARD
410             if (!mimeType.isEmpty())
411                 qDebug("   - %s", qPrintable(mimeType));
412 #endif
413             if (mimeType == format)
414                 return true;
415         }
416     }
417     return false;
418 }
419
420 QVariant
421 QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const
422 {
423     if (!paste)
424         return QVariant();
425
426     sync();
427
428     ItemCount cnt = 0;
429     if (PasteboardGetItemCount(paste, &cnt) || !cnt)
430         return QByteArray();
431
432 #ifdef DEBUG_PASTEBOARD
433     qDebug("Pasteboard: retrieveData [%s]", qPrintable(format));
434 #endif
435     const QList<QMacPasteboardMime *> mimes = QMacPasteboardMime::all(mime_type);
436     for (int mime = 0; mime < mimes.size(); ++mime) {
437         QMacPasteboardMime *c = mimes.at(mime);
438         QString c_flavor = c->flavorFor(format);
439         if (!c_flavor.isEmpty()) {
440             // Handle text/plain a little differently. Try handling Unicode first.
441             bool checkForUtf16 = (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text")
442                                   || c_flavor == QLatin1String("public.utf8-plain-text"));
443             if (checkForUtf16 || c_flavor == QLatin1String("public.utf16-plain-text")) {
444                 // Try to get the NSStringPboardType from NSPasteboard, newlines are mapped
445                 // correctly (as '\n') in this data. The 'public.utf16-plain-text' type
446                 // usually maps newlines to '\r' instead.
447                 QString str = qt_mac_get_pasteboardString(paste);
448                 if (!str.isEmpty())
449                     return str;
450             }
451             if (checkForUtf16 && hasFlavor(QLatin1String("public.utf16-plain-text")))
452                 c_flavor = QLatin1String("public.utf16-plain-text");
453
454             QVariant ret;
455             QList<QByteArray> retList;
456             for (uint index = 1; index <= cnt; ++index) {
457                 PasteboardItemID id;
458                 if (PasteboardGetItemIdentifier(paste, index, &id) != noErr)
459                     continue;
460
461                 QCFType<CFArrayRef> types;
462                 if (PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
463                     continue;
464
465                 const int type_count = CFArrayGetCount(types);
466                 for (int i = 0; i < type_count; ++i) {
467                     CFStringRef flavor = static_cast<CFStringRef>(CFArrayGetValueAtIndex(types, i));
468                     if (c_flavor == QCFString::toQString(flavor)) {
469                         QCFType<CFDataRef> macBuffer;
470                         if (PasteboardCopyItemFlavorData(paste, id, flavor, &macBuffer) == noErr) {
471                             QByteArray buffer((const char *)CFDataGetBytePtr(macBuffer), CFDataGetLength(macBuffer));
472                             if (!buffer.isEmpty()) {
473 #ifdef DEBUG_PASTEBOARD
474                                 qDebug("  - %s [%s] (%s)", qPrintable(format), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
475 #endif
476                                 buffer.detach(); //detach since we release the macBuffer
477                                 retList.append(buffer);
478                                 break; //skip to next element
479                             }
480                         }
481                     } else {
482 #ifdef DEBUG_PASTEBOARD
483                         qDebug("  - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
484 #endif
485                     }
486                 }
487             }
488
489             if (!retList.isEmpty()) {
490                 ret = c->convertToMime(format, retList, c_flavor);
491                 return ret;
492             }
493         }
494     }
495     return QVariant();
496 }
497
498 void QMacPasteboard::clear_helper()
499 {
500     if (paste)
501         PasteboardClear(paste);
502     promises.clear();
503 }
504
505 void
506 QMacPasteboard::clear()
507 {
508 #ifdef DEBUG_PASTEBOARD
509     qDebug("PasteBoard: clear!");
510 #endif
511     clear_helper();
512 }
513
514 bool
515 QMacPasteboard::sync() const
516 {
517     if (!paste)
518         return false;
519     const bool fromGlobal = PasteboardSynchronize(paste) & kPasteboardModified;
520
521     if (fromGlobal)
522         const_cast<QMacPasteboard *>(this)->setMimeData(0);
523
524 #ifdef DEBUG_PASTEBOARD
525     if (fromGlobal)
526         qDebug("Pasteboard: Synchronize!");
527 #endif
528     return fromGlobal;
529 }
530
531
532 QString qt_mac_get_pasteboardString(PasteboardRef paste)
533 {
534     QCocoaAutoReleasePool pool;
535     NSPasteboard *pb = nil;
536     CFStringRef pbname;
537     if (PasteboardCopyName(paste, &pbname) == noErr) {
538         pb = [NSPasteboard pasteboardWithName:const_cast<NSString *>(reinterpret_cast<const NSString *>(pbname))];
539         CFRelease(pbname);
540     } else {
541         pb = [NSPasteboard generalPasteboard];
542     }
543     if (pb) {
544         NSString *text = [pb stringForType:NSStringPboardType];
545         if (text)
546             return QCFString::toQString(text);
547     }
548     return QString();
549 }
550
551
552
553 QT_END_NAMESPACE