]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiClipboard.cpp
17f5132f2f71a4dc2ee32fa78550278c08063972
[lyx.git] / src / frontends / qt4 / GuiClipboard.cpp
1 // -*- C++ -*-
2 /**
3  * \file qt4/GuiClipboard.cpp
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "FileDialog.h"
16
17 #include "GuiClipboard.h"
18 #include "qt_helpers.h"
19
20 #include "frontends/alert.h"
21
22 #include "Buffer.h"
23 #include "BufferView.h"
24 #include "Cursor.h"
25
26 #include "support/convert.h"
27 #include "support/debug.h"
28 #include "support/filetools.h"
29 #include "support/FileFilterList.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
32
33 #include <QApplication>
34 #include <QBuffer>
35 #include <QClipboard>
36 #include <QDataStream>
37 #include <QFile>
38 #include <QImage>
39 #include <QMacPasteboardMime>
40 #include <QMimeData>
41 #include <QString>
42 #include <QStringList>
43
44 #ifdef Q_WS_WIN
45 #include <QWindowsMime>
46 #ifdef Q_CYGWIN_WIN
47 #include <wtypes.h>
48 #endif
49 #include <objidl.h>
50 #endif // Q_WS_WIN
51
52 #include "boost/assert.hpp"
53
54 #include <map>
55
56 #ifdef Q_WS_MACX
57 #include "support/linkback/LinkBackProxy.h"
58 #endif // Q_WS_MACX
59
60 using namespace std;
61 using namespace lyx::support;
62
63 static char const * const lyx_mime_type = "application/x-lyx";
64 static char const * const pdf_mime_type = "application/pdf";
65 static char const * const emf_mime_type = "image/x-emf";
66 static char const * const wmf_mime_type = "image/x-wmf";
67
68 namespace lyx {
69
70 namespace frontend {
71
72 #ifdef Q_WS_WIN
73
74 static FORMATETC cfFromMime(QString const & mimetype)
75 {
76         FORMATETC formatetc;
77         if (mimetype == emf_mime_type) {
78                 formatetc.cfFormat = CF_ENHMETAFILE;
79                 formatetc.tymed = TYMED_ENHMF;
80         } else if (mimetype == wmf_mime_type) {
81                 formatetc.cfFormat = CF_METAFILEPICT;
82                 formatetc.tymed = TYMED_MFPICT;
83         }
84         formatetc.ptd = 0;
85         formatetc.dwAspect = DVASPECT_CONTENT;
86         formatetc.lindex = -1;
87         return formatetc;
88 }
89
90
91 class QWindowsMimeMetafile : public QWindowsMime {
92 public:
93         bool canConvertFromMime(FORMATETC const & formatetc, QMimeData const * mimedata) const;
94         bool canConvertToMime(QString const & mimetype, IDataObject * pDataObj) const;
95         bool convertFromMime(FORMATETC const & formatetc, const QMimeData * mimedata, STGMEDIUM * pmedium) const;
96         QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj, QVariant::Type preferredType) const;
97         QVector<FORMATETC> formatsForMime(QString const & mimeType, QMimeData const * mimeData) const;
98         QString mimeForFormat(FORMATETC const &) const;
99 };
100
101
102 QString QWindowsMimeMetafile::mimeForFormat(FORMATETC const & formatetc) const
103 {
104         QString f;
105         if (formatetc.cfFormat == CF_ENHMETAFILE)
106                 f = emf_mime_type; 
107         else if (formatetc.cfFormat == CF_METAFILEPICT)
108                 f = wmf_mime_type;
109         return f;
110 }
111
112
113 bool QWindowsMimeMetafile::canConvertFromMime(FORMATETC const & formatetc, 
114         QMimeData const * mimedata) const
115 {
116         return false;
117 }
118
119
120 bool QWindowsMimeMetafile::canConvertToMime(QString const & mimetype,
121         IDataObject * pDataObj) const
122 {
123         if (mimetype != emf_mime_type && mimetype != wmf_mime_type)
124                 return false;
125         FORMATETC formatetc = cfFromMime(mimetype);
126         return pDataObj->QueryGetData(&formatetc) == S_OK;
127 }
128
129
130 bool QWindowsMimeMetafile::convertFromMime(FORMATETC const & formatetc,
131         QMimeData const * mimedata, STGMEDIUM * pmedium) const
132 {
133         return false;
134 }
135
136
137 QVariant QWindowsMimeMetafile::convertToMime(QString const & mimetype,
138         IDataObject * pDataObj, QVariant::Type preferredType) const
139 {
140         QByteArray data;
141         if (!canConvertToMime(mimetype, pDataObj))
142                 return data;
143
144         FORMATETC formatetc = cfFromMime(mimetype);
145         STGMEDIUM s;
146         if (pDataObj->GetData(&formatetc, &s) != S_OK)
147                 return data;
148
149         int dataSize;
150         if (s.tymed == TYMED_ENHMF) {
151                 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
152                 data.resize(dataSize);
153                 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize, (LPBYTE)data.data());
154         } else if (s.tymed == TYMED_MFPICT) {
155                 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
156                 data.resize(dataSize);
157                 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize, (LPBYTE)data.data());
158         }
159         data.detach();
160         ReleaseStgMedium(&s);
161
162         return data;
163 }
164
165
166 QVector<FORMATETC> QWindowsMimeMetafile::formatsForMime(
167         QString const & mimetype, QMimeData const * mimedata) const
168 {
169         QVector<FORMATETC> formats;
170         formats += cfFromMime(mimetype);
171         return formats;
172 }
173
174 static QWindowsMimeMetafile * metafileWindowsMime;
175
176 #endif // Q_WS_WIN
177
178 #ifdef Q_WS_MACX
179
180 class QMacPasteboardMimeGraphics : public QMacPasteboardMime {
181 public:
182         QMacPasteboardMimeGraphics()
183                 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
184         {}
185         QString convertorName();
186         QString flavorFor(QString const & mime);
187         QString mimeFor(QString flav);
188         bool canConvert(QString const & mime, QString flav);
189         QVariant convertToMime(QString const & mime, QList<QByteArray> data, QString flav);
190         QList<QByteArray> convertFromMime(QString const & mime, QVariant data, QString flav);
191 };
192
193
194 QString QMacPasteboardMimeGraphics::convertorName()
195 {
196         return "Graphics";
197 }
198
199
200 QString QMacPasteboardMimeGraphics::flavorFor(QString const & mime)
201 {
202         LYXERR(Debug::ACTION, "flavorFor " << fromqstr(mime));
203         if (mime == QLatin1String(pdf_mime_type))
204                 return QLatin1String("com.adobe.pdf");
205         return QString();
206 }
207
208
209 QString QMacPasteboardMimeGraphics::mimeFor(QString flav)
210 {
211         LYXERR(Debug::ACTION, "mimeFor " << fromqstr(flav));
212         if (flav == QLatin1String("com.adobe.pdf"))
213                 return QLatin1String(pdf_mime_type);
214         return QString();
215 }
216
217
218 bool QMacPasteboardMimeGraphics::canConvert(QString const & mime, QString flav)
219 {
220         return mimeFor(flav) == mime;
221 }
222
223
224 QVariant QMacPasteboardMimeGraphics::convertToMime(QString const & mime, QList<QByteArray> data, QString)
225 {
226         if(data.count() > 1)
227                 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
228         return data.first();
229 }
230
231
232 QList<QByteArray> QMacPasteboardMimeGraphics::convertFromMime(QString const & mime, QVariant data, QString)
233 {
234         QList<QByteArray> ret;
235         ret.append(data.toByteArray());
236         return ret;
237 }
238
239 static QMacPasteboardMimeGraphics * graphicsPasteboardMime;
240
241 #endif // Q_WS_MACX
242
243
244 GuiClipboard::GuiClipboard()
245 {
246         connect(qApp->clipboard(), SIGNAL(dataChanged()),
247                 this, SLOT(on_dataChanged()));
248         // initialize clipboard status.
249         on_dataChanged();
250         
251 #ifdef Q_WS_MACX
252         if (!graphicsPasteboardMime)
253                 graphicsPasteboardMime = new QMacPasteboardMimeGraphics();
254 #endif // Q_WS_MACX
255
256 #ifdef Q_WS_WIN
257         if (!metafileWindowsMime)
258                 metafileWindowsMime = new QWindowsMimeMetafile();
259 #endif // Q_WS_WIN
260 }
261
262
263 GuiClipboard::~GuiClipboard()
264 {
265 #ifdef Q_WS_MACX
266         closeAllLinkBackLinks();
267 #endif // Q_WS_MACX
268 }
269
270
271 string const GuiClipboard::getAsLyX() const
272 {
273         LYXERR(Debug::ACTION, "GuiClipboard::getAsLyX(): `");
274         // We don't convert encodings here since the encoding of the
275         // clipboard contents is specified in the data itself
276         QMimeData const * source =
277                 qApp->clipboard()->mimeData(QClipboard::Clipboard);
278         if (!source) {
279                 LYXERR(Debug::ACTION, "' (no QMimeData)");
280                 return string();
281         }
282
283         if (source->hasFormat(lyx_mime_type)) {
284                 // data from ourself or some other LyX instance
285                 QByteArray const ar = source->data(lyx_mime_type);
286                 string const s(ar.data(), ar.count());
287                 LYXERR(Debug::ACTION, s << "'");
288                 return s;
289         }
290         LYXERR(Debug::ACTION, "'");
291         return string();
292 }
293
294
295 FileName GuiClipboard::getPastedGraphicsFileName(Cursor const & cur,
296         Clipboard::GraphicsType & type) const
297 {
298         // create file dialog filter according to the existing types in the clipboard
299         vector<Clipboard::GraphicsType> types;
300         if (hasGraphicsContents(Clipboard::EmfGraphicsType))
301                 types.push_back(Clipboard::EmfGraphicsType);
302         if (hasGraphicsContents(Clipboard::WmfGraphicsType))
303                 types.push_back(Clipboard::WmfGraphicsType);
304         if (hasGraphicsContents(Clipboard::LinkBackGraphicsType))
305                 types.push_back(Clipboard::LinkBackGraphicsType);
306         if (hasGraphicsContents(Clipboard::PdfGraphicsType))
307                 types.push_back(Clipboard::PdfGraphicsType);
308         if (hasGraphicsContents(Clipboard::PngGraphicsType))
309                 types.push_back(Clipboard::PngGraphicsType);
310         if (hasGraphicsContents(Clipboard::JpegGraphicsType))
311                 types.push_back(Clipboard::JpegGraphicsType);
312         
313         BOOST_ASSERT(!types.empty());
314         
315         // select prefered type if AnyGraphicsType was passed
316         if (type == Clipboard::AnyGraphicsType)
317                 type = types.front();
318         
319         // which extension?
320         map<Clipboard::GraphicsType, string> extensions;
321         map<Clipboard::GraphicsType, docstring> typeNames;
322         
323         extensions[Clipboard::EmfGraphicsType] = "emf";
324         extensions[Clipboard::WmfGraphicsType] = "wmf";
325         extensions[Clipboard::LinkBackGraphicsType] = "linkback";
326         extensions[Clipboard::PdfGraphicsType] = "pdf";
327         extensions[Clipboard::PngGraphicsType] = "png";
328         extensions[Clipboard::JpegGraphicsType] = "jpeg";
329         
330         typeNames[Clipboard::EmfGraphicsType] = _("Enhanced Metafile");
331         typeNames[Clipboard::WmfGraphicsType] = _("Windows Metafile");
332         typeNames[Clipboard::LinkBackGraphicsType] = _("LinkBack PDF");
333         typeNames[Clipboard::PdfGraphicsType] = _("PDF");
334         typeNames[Clipboard::PngGraphicsType] = _("PNG");
335         typeNames[Clipboard::JpegGraphicsType] = _("JPEG");
336         
337         // find unused filename with primary extension
338         string document_path = cur.buffer().fileName().onlyPath().absFilename();
339         unsigned newfile_number = 0;
340         FileName filename;
341         do {
342                 ++newfile_number;
343                 filename = FileName(addName(document_path,
344                         to_utf8(_("pasted"))
345                         + convert<string>(newfile_number) + "."
346                         + extensions[type]));
347         } while (filename.isReadableFile());
348         
349         while (true) {
350                 // create file type filter, putting the prefered on to the front
351                 docstring filterSpec;
352                 for (size_t i = 0; i != types.size(); ++i) {
353                         docstring s = bformat(_("%1$s Files"), typeNames[types[i]])
354                                 + " (*." + from_ascii(extensions[types[i]]) + ")";
355                         if (types[i] == type)
356                                 filterSpec = s + filterSpec;
357                         else
358                                 filterSpec += ";;" + s;
359                 }
360                 FileFilterList const filter(filterSpec);
361                 
362                 // show save dialog for the graphic
363                 FileDialog dlg(qt_("Choose a filename to save the pasted graphic as"));
364                 FileDialog::Result result =
365                 dlg.save(toqstr(filename.onlyPath().absFilename()), filter,
366                          toqstr(filename.onlyFileName()));
367                 
368                 if (result.first == FileDialog::Later)
369                         return FileName();
370                 
371                 string newFilename = fromqstr(result.second);
372                 if (newFilename.empty()) {
373                         cur.bv().message(_("Canceled."));
374                         return FileName();
375                 }
376                 filename.set(newFilename);
377                 
378                 // check the extension (the user could have changed it)
379                 if (!suffixIs(ascii_lowercase(filename.absFilename()),
380                               "." + extensions[type])) {
381                         // the user changed the extension. Check if the type is available
382                         size_t i;
383                         for (i = 1; i != types.size(); ++i) {
384                                 if (suffixIs(ascii_lowercase(filename.absFilename()),
385                                              "." + extensions[types[i]])) {
386                                         type = types[i];
387                                         break;
388                                 }
389                         }
390                         
391                         // invalid extension found, or none at all. In the latter
392                         // case set the default extensions.
393                         if (i == types.size()
394                             && filename.onlyFileName().find('.') == string::npos) {
395                                 filename.changeExtension("." + extensions[type]);
396                         }
397                 }
398                 
399                 // check whether the file exists and warn the user
400                 if (!filename.exists())
401                         break;
402                 int ret = frontend::Alert::prompt(
403                         _("Overwrite external file?"),
404                         bformat(_("File %1$s already exists, do you want to overwrite it?"),
405                         from_utf8(filename.absFilename())), 1, 1, _("&Overwrite"), _("&Cancel"));
406                 if (ret == 0)
407                         // overwrite, hence break the dialog loop
408                         break;
409                 
410                 // not overwrite, hence show the dialog again (i.e. loop)
411         }
412         
413         return filename;
414 }
415
416
417 FileName GuiClipboard::getAsGraphics(Cursor const & cur, GraphicsType type) const
418 {
419         // get the filename from the user
420         FileName filename = getPastedGraphicsFileName(cur, type);
421         if (filename.empty())
422                 return FileName();
423
424         // handle image cases first
425         if (type == PngGraphicsType || type == JpegGraphicsType) {
426                 // get image from QImage from clipboard
427                 QImage image = qApp->clipboard()->image();
428                 if (image.isNull()) {
429                         LYXERR(Debug::ACTION, "No image in clipboard");
430                         return FileName();
431                 }
432
433                 // convert into graphics format
434                 QByteArray ar;
435                 QBuffer buffer(&ar);
436                 buffer.open(QIODevice::WriteOnly);
437                 if (type == PngGraphicsType)
438                         image.save(toqstr(filename.absFilename()), "PNG");
439                 else if (type == JpegGraphicsType)
440                         image.save(toqstr(filename.absFilename()), "JPEG");
441                 else
442                         BOOST_ASSERT(false);
443                 
444                 return filename;
445         }
446         
447         // get mime data
448         QMimeData const * source =
449         qApp->clipboard()->mimeData(QClipboard::Clipboard);
450         if (!source) {
451                 LYXERR(Debug::ACTION, "0 bytes (no QMimeData)");
452                 return FileName();
453         }
454         
455         // get mime for type
456         QString mime;
457         switch (type) {
458         case PdfGraphicsType: mime = pdf_mime_type; break;
459         case LinkBackGraphicsType: mime = pdf_mime_type; break;
460         case EmfGraphicsType: mime = emf_mime_type; break;
461         case WmfGraphicsType: mime = wmf_mime_type; break;
462         default: BOOST_ASSERT(false);
463         }
464         
465         // get data
466         if (!source->hasFormat(mime))
467                 return FileName();
468         // data from ourself or some other LyX instance
469         QByteArray const ar = source->data(mime);
470         LYXERR(Debug::ACTION, "Getting from clipboard: mime = " << mime.data()
471                << "length = " << ar.count());
472         
473         QFile f(toqstr(filename.absFilename()));
474         if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
475                 LYXERR(Debug::ACTION, "Error opening file "
476                        << filename.absFilename() << " for writing");
477                 return FileName();
478         }
479         
480         // write the (LinkBack) PDF data
481         f.write(ar);
482         if (type == LinkBackGraphicsType) {
483 #ifdef Q_WS_MACX
484                 void const * linkBackData;
485                 unsigned linkBackLen;
486                 getLinkBackData(&linkBackData, &linkBackLen);
487                 f.write((char *)linkBackData, linkBackLen);
488                 quint32 pdfLen = ar.size();
489                 QDataStream ds(&f);
490                 ds << pdfLen; // big endian by default
491 #else
492                 // only non-Mac this should never happen
493                 BOOST_ASSERT(false);
494 #endif // Q_WS_MACX
495         }
496
497         f.close();
498         return filename;
499 }
500
501
502 docstring const GuiClipboard::getAsText() const
503 {
504         // text data from other applications
505         QString const str = qApp->clipboard()->text(QClipboard::Clipboard)
506                                 .normalized(QString::NormalizationForm_C);
507         LYXERR(Debug::ACTION, "GuiClipboard::getAsText(): `" << fromqstr(str) << "'");
508         if (str.isNull())
509                 return docstring();
510
511         return internalLineEnding(qstring_to_ucs4(str));
512 }
513
514
515 void GuiClipboard::put(string const & lyx, docstring const & text)
516 {
517         LYXERR(Debug::ACTION, "GuiClipboard::put(`" << lyx << "' `"
518                               << to_utf8(text) << "')");
519         // We don't convert the encoding of lyx since the encoding of the
520         // clipboard contents is specified in the data itself
521         QMimeData * data = new QMimeData;
522         if (!lyx.empty()) {
523                 QByteArray const qlyx(lyx.c_str(), lyx.size());
524                 data->setData(lyx_mime_type, qlyx);
525         }
526         // Don't test for text.empty() since we want to be able to clear the
527         // clipboard.
528         QString const qtext = toqstr(text);
529         data->setText(qtext);
530         qApp->clipboard()->setMimeData(data, QClipboard::Clipboard);
531 }
532
533
534 bool GuiClipboard::hasLyXContents() const
535 {
536         QMimeData const * const source =
537                 qApp->clipboard()->mimeData(QClipboard::Clipboard);
538         return source && source->hasFormat(lyx_mime_type);
539 }
540
541
542 bool GuiClipboard::hasGraphicsContents(Clipboard::GraphicsType type) const
543 {
544         if (type == AnyGraphicsType) {
545                 return hasGraphicsContents(PdfGraphicsType)
546                         || hasGraphicsContents(PngGraphicsType)
547                         || hasGraphicsContents(JpegGraphicsType)
548                         || hasGraphicsContents(EmfGraphicsType)
549                         || hasGraphicsContents(WmfGraphicsType)
550                         || hasGraphicsContents(LinkBackGraphicsType);
551         }
552
553         QMimeData const * const source =
554         qApp->clipboard()->mimeData(QClipboard::Clipboard);
555
556         // handle image cases first
557         if (type == PngGraphicsType || type == JpegGraphicsType)
558                 return source->hasImage();
559
560         // handle LinkBack for Mac
561 #ifdef Q_WS_MACX
562         if (type == LinkBackGraphicsType)
563                 return isLinkBackDataInPasteboard();
564 #else
565         if (type == LinkBackGraphicsType)
566                 return false;
567 #endif // Q_WS_MACX
568         
569         // get mime data
570         QStringList const & formats = source->formats();
571         LYXERR(Debug::ACTION, "We found " << formats.size() << " formats");
572         for (int i = 0; i < formats.size(); ++i) {
573                 LYXERR(Debug::ACTION, "Found format " << fromqstr(formats[i]));
574         }
575
576         // compute mime for type
577         QString mime;
578         switch (type) {
579         case EmfGraphicsType: mime = emf_mime_type; break;
580         case WmfGraphicsType: mime = wmf_mime_type; break;
581         case PdfGraphicsType: mime = pdf_mime_type; break;
582         default: BOOST_ASSERT(false);
583         }
584         
585         return source && source->hasFormat(mime);
586 }
587
588
589 bool GuiClipboard::isInternal() const
590 {
591         // ownsClipboard() is also true for stuff coming from dialogs, e.g.
592         // the preamble dialog
593         // FIXME: This does only work on X11, since ownsClipboard() is
594         // hardwired to return false on Windows and OS X.
595         return qApp->clipboard()->ownsClipboard() && hasLyXContents();
596 }
597
598
599 bool GuiClipboard::hasInternal() const
600 {
601         // Windows and Mac OS X does not have the concept of ownership;
602         // the clipboard is a fully global resource so all applications 
603         // are notified of changes.
604 #if (defined(Q_WS_X11))
605         return true;
606 #else
607         return false;
608 #endif
609 }
610
611
612 void GuiClipboard::on_dataChanged()
613 {
614         QMimeData const * const source =
615         qApp->clipboard()->mimeData(QClipboard::Clipboard);
616         QStringList l = source->formats();
617         LYXERR(Debug::ACTION, "Qt Clipboard changed. We found the following mime types:");
618         for (int i = 0; i < l.count(); i++) {
619                 LYXERR(Debug::ACTION, fromqstr(l.value(i)));
620         }
621         
622         text_clipboard_empty_ = qApp->clipboard()->
623                 text(QClipboard::Clipboard).isEmpty();
624
625         has_lyx_contents_ = hasLyXContents();
626         has_graphics_contents_ = hasGraphicsContents();
627 }
628
629
630 bool GuiClipboard::empty() const
631 {
632         // We need to check both the plaintext and the LyX version of the
633         // clipboard. The plaintext version is empty if the LyX version
634         // contains only one inset, and the LyX version is empty if the
635         // clipboard does not come from LyX.
636         if (!text_clipboard_empty_)
637                 return false;
638         return !has_lyx_contents_ && !has_graphics_contents_;
639 }
640
641 } // namespace frontend
642 } // namespace lyx
643
644 #include "GuiClipboard_moc.cpp"