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.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "FileDialog.h"
17 #include "GuiClipboard.h"
18 #include "qt_helpers.h"
21 #include "BufferView.h"
24 #include "support/assert.h"
25 #include "support/convert.h"
26 #include "support/debug.h"
27 #include "support/filetools.h"
28 #include "support/FileFilterList.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
32 #include "support/linkback/LinkBackProxy.h"
35 #include "frontends/alert.h"
37 #include <QApplication>
40 #include <QDataStream>
43 #include <QMacPasteboardMime>
46 #include <QStringList>
49 #include <QWindowsMime>
56 #include <boost/shared_ptr.hpp>
61 using namespace lyx::support;
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";
74 static FORMATETC cfFromMime(QString const & mimetype)
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;
85 formatetc.dwAspect = DVASPECT_CONTENT;
86 formatetc.lindex = -1;
91 class QWindowsMimeMetafile : public QWindowsMime {
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;
102 QString QWindowsMimeMetafile::mimeForFormat(FORMATETC const & formatetc) const
105 if (formatetc.cfFormat == CF_ENHMETAFILE)
107 else if (formatetc.cfFormat == CF_METAFILEPICT)
113 bool QWindowsMimeMetafile::canConvertFromMime(FORMATETC const & formatetc,
114 QMimeData const * mimedata) const
120 bool QWindowsMimeMetafile::canConvertToMime(QString const & mimetype,
121 IDataObject * pDataObj) const
123 if (mimetype != emf_mime_type && mimetype != wmf_mime_type)
125 FORMATETC formatetc = cfFromMime(mimetype);
126 return pDataObj->QueryGetData(&formatetc) == S_OK;
130 bool QWindowsMimeMetafile::convertFromMime(FORMATETC const & formatetc,
131 QMimeData const * mimedata, STGMEDIUM * pmedium) const
137 QVariant QWindowsMimeMetafile::convertToMime(QString const & mimetype,
138 IDataObject * pDataObj, QVariant::Type preferredType) const
141 if (!canConvertToMime(mimetype, pDataObj))
144 FORMATETC formatetc = cfFromMime(mimetype);
146 if (pDataObj->GetData(&formatetc, &s) != S_OK)
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());
160 ReleaseStgMedium(&s);
166 QVector<FORMATETC> QWindowsMimeMetafile::formatsForMime(
167 QString const & mimetype, QMimeData const * mimedata) const
169 QVector<FORMATETC> formats;
170 formats += cfFromMime(mimetype);
174 static boost::shared_ptr<QWindowsMimeMetafile> metafileWindowsMime;
180 class QMacPasteboardMimeGraphics : public QMacPasteboardMime {
182 QMacPasteboardMimeGraphics()
183 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
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);
194 QString QMacPasteboardMimeGraphics::convertorName()
200 QString QMacPasteboardMimeGraphics::flavorFor(QString const & mime)
202 LYXERR(Debug::ACTION, "flavorFor " << fromqstr(mime));
203 if (mime == QLatin1String(pdf_mime_type))
204 return QLatin1String("com.adobe.pdf");
209 QString QMacPasteboardMimeGraphics::mimeFor(QString flav)
211 LYXERR(Debug::ACTION, "mimeFor " << fromqstr(flav));
212 if (flav == QLatin1String("com.adobe.pdf"))
213 return QLatin1String(pdf_mime_type);
218 bool QMacPasteboardMimeGraphics::canConvert(QString const & mime, QString flav)
220 return mimeFor(flav) == mime;
224 QVariant QMacPasteboardMimeGraphics::convertToMime(QString const & mime, QList<QByteArray> data, QString)
227 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
232 QList<QByteArray> QMacPasteboardMimeGraphics::convertFromMime(QString const & mime, QVariant data, QString)
234 QList<QByteArray> ret;
235 ret.append(data.toByteArray());
239 static boost::shared_ptr<QMacPasteboardMimeGraphics> graphicsPasteboardMime;
244 GuiClipboard::GuiClipboard()
246 connect(qApp->clipboard(), SIGNAL(dataChanged()),
247 this, SLOT(on_dataChanged()));
248 // initialize clipboard status.
252 if (!graphicsPasteboardMime)
253 graphicsPasteboardMime =
254 boost::shared_ptr<QMacPasteboardMimeGraphics>
255 (new QMacPasteboardMimeGraphics());
259 if (!metafileWindowsMime)
260 metafileWindowsMime =
261 boost::shared_ptr<QWindowsMimeMetafile>
262 (new QWindowsMimeMetafile());
267 GuiClipboard::~GuiClipboard()
270 closeAllLinkBackLinks();
275 string const GuiClipboard::getAsLyX() const
277 LYXERR(Debug::ACTION, "GuiClipboard::getAsLyX(): `");
278 // We don't convert encodings here since the encoding of the
279 // clipboard contents is specified in the data itself
280 QMimeData const * source =
281 qApp->clipboard()->mimeData(QClipboard::Clipboard);
283 LYXERR(Debug::ACTION, "' (no QMimeData)");
287 if (source->hasFormat(lyx_mime_type)) {
288 // data from ourself or some other LyX instance
289 QByteArray const ar = source->data(lyx_mime_type);
290 string const s(ar.data(), ar.count());
291 LYXERR(Debug::ACTION, s << "'");
294 LYXERR(Debug::ACTION, "'");
299 FileName GuiClipboard::getPastedGraphicsFileName(Cursor const & cur,
300 Clipboard::GraphicsType & type) const
302 // create file dialog filter according to the existing types in the clipboard
303 vector<Clipboard::GraphicsType> types;
304 if (hasGraphicsContents(Clipboard::EmfGraphicsType))
305 types.push_back(Clipboard::EmfGraphicsType);
306 if (hasGraphicsContents(Clipboard::WmfGraphicsType))
307 types.push_back(Clipboard::WmfGraphicsType);
308 if (hasGraphicsContents(Clipboard::LinkBackGraphicsType))
309 types.push_back(Clipboard::LinkBackGraphicsType);
310 if (hasGraphicsContents(Clipboard::PdfGraphicsType))
311 types.push_back(Clipboard::PdfGraphicsType);
312 if (hasGraphicsContents(Clipboard::PngGraphicsType))
313 types.push_back(Clipboard::PngGraphicsType);
314 if (hasGraphicsContents(Clipboard::JpegGraphicsType))
315 types.push_back(Clipboard::JpegGraphicsType);
317 LASSERT(!types.empty(), /**/);
319 // select prefered type if AnyGraphicsType was passed
320 if (type == Clipboard::AnyGraphicsType)
321 type = types.front();
324 map<Clipboard::GraphicsType, string> extensions;
325 map<Clipboard::GraphicsType, docstring> typeNames;
327 extensions[Clipboard::EmfGraphicsType] = "emf";
328 extensions[Clipboard::WmfGraphicsType] = "wmf";
329 extensions[Clipboard::LinkBackGraphicsType] = "linkback";
330 extensions[Clipboard::PdfGraphicsType] = "pdf";
331 extensions[Clipboard::PngGraphicsType] = "png";
332 extensions[Clipboard::JpegGraphicsType] = "jpeg";
334 typeNames[Clipboard::EmfGraphicsType] = _("Enhanced Metafile");
335 typeNames[Clipboard::WmfGraphicsType] = _("Windows Metafile");
336 typeNames[Clipboard::LinkBackGraphicsType] = _("LinkBack PDF");
337 typeNames[Clipboard::PdfGraphicsType] = _("PDF");
338 typeNames[Clipboard::PngGraphicsType] = _("PNG");
339 typeNames[Clipboard::JpegGraphicsType] = _("JPEG");
341 // find unused filename with primary extension
342 string document_path = cur.buffer().fileName().onlyPath().absFilename();
343 unsigned newfile_number = 0;
347 filename = FileName(addName(document_path,
349 + convert<string>(newfile_number) + "."
350 + extensions[type]));
351 } while (filename.isReadableFile());
354 // create file type filter, putting the prefered on to the front
355 docstring filterSpec;
356 for (size_t i = 0; i != types.size(); ++i) {
357 docstring s = bformat(_("%1$s Files"), typeNames[types[i]])
358 + " (*." + from_ascii(extensions[types[i]]) + ")";
359 if (types[i] == type)
360 filterSpec = s + filterSpec;
362 filterSpec += ";;" + s;
364 FileFilterList const filter(filterSpec);
366 // show save dialog for the graphic
367 FileDialog dlg(qt_("Choose a filename to save the pasted graphic as"));
368 FileDialog::Result result =
369 dlg.save(toqstr(filename.onlyPath().absFilename()), filter,
370 toqstr(filename.onlyFileName()));
372 if (result.first == FileDialog::Later)
375 string newFilename = fromqstr(result.second);
376 if (newFilename.empty()) {
377 cur.bv().message(_("Canceled."));
380 filename.set(newFilename);
382 // check the extension (the user could have changed it)
383 if (!suffixIs(ascii_lowercase(filename.absFilename()),
384 "." + extensions[type])) {
385 // the user changed the extension. Check if the type is available
387 for (i = 1; i != types.size(); ++i) {
388 if (suffixIs(ascii_lowercase(filename.absFilename()),
389 "." + extensions[types[i]])) {
395 // invalid extension found, or none at all. In the latter
396 // case set the default extensions.
397 if (i == types.size()
398 && filename.onlyFileName().find('.') == string::npos) {
399 filename.changeExtension("." + extensions[type]);
403 // check whether the file exists and warn the user
404 if (!filename.exists())
406 int ret = frontend::Alert::prompt(
407 _("Overwrite external file?"),
408 bformat(_("File %1$s already exists, do you want to overwrite it?"),
409 from_utf8(filename.absFilename())), 1, 1, _("&Overwrite"), _("&Cancel"));
411 // overwrite, hence break the dialog loop
414 // not overwrite, hence show the dialog again (i.e. loop)
421 FileName GuiClipboard::getAsGraphics(Cursor const & cur, GraphicsType type) const
423 // get the filename from the user
424 FileName filename = getPastedGraphicsFileName(cur, type);
425 if (filename.empty())
428 // handle image cases first
429 if (type == PngGraphicsType || type == JpegGraphicsType) {
430 // get image from QImage from clipboard
431 QImage image = qApp->clipboard()->image();
432 if (image.isNull()) {
433 LYXERR(Debug::ACTION, "No image in clipboard");
437 // convert into graphics format
440 buffer.open(QIODevice::WriteOnly);
441 if (type == PngGraphicsType)
442 image.save(toqstr(filename.absFilename()), "PNG");
443 else if (type == JpegGraphicsType)
444 image.save(toqstr(filename.absFilename()), "JPEG");
446 LASSERT(false, /**/);
452 QMimeData const * source =
453 qApp->clipboard()->mimeData(QClipboard::Clipboard);
455 LYXERR(Debug::ACTION, "0 bytes (no QMimeData)");
462 case PdfGraphicsType: mime = pdf_mime_type; break;
463 case LinkBackGraphicsType: mime = pdf_mime_type; break;
464 case EmfGraphicsType: mime = emf_mime_type; break;
465 case WmfGraphicsType: mime = wmf_mime_type; break;
466 default: LASSERT(false, /**/);
470 if (!source->hasFormat(mime))
472 // data from ourself or some other LyX instance
473 QByteArray const ar = source->data(mime);
474 LYXERR(Debug::ACTION, "Getting from clipboard: mime = " << mime.data()
475 << "length = " << ar.count());
477 QFile f(toqstr(filename.absFilename()));
478 if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
479 LYXERR(Debug::ACTION, "Error opening file "
480 << filename.absFilename() << " for writing");
484 // write the (LinkBack) PDF data
486 if (type == LinkBackGraphicsType) {
488 void const * linkBackData;
489 unsigned linkBackLen;
490 getLinkBackData(&linkBackData, &linkBackLen);
491 f.write((char *)linkBackData, linkBackLen);
492 quint32 pdfLen = ar.size();
494 ds << pdfLen; // big endian by default
496 // only non-Mac this should never happen
497 LASSERT(false, /**/);
506 docstring const GuiClipboard::getAsText() const
508 // text data from other applications
509 QString const str = qApp->clipboard()->text(QClipboard::Clipboard)
510 .normalized(QString::NormalizationForm_C);
511 LYXERR(Debug::ACTION, "GuiClipboard::getAsText(): `" << fromqstr(str) << "'");
515 return internalLineEnding(qstring_to_ucs4(str));
519 void GuiClipboard::put(string const & lyx, docstring const & text)
521 LYXERR(Debug::ACTION, "GuiClipboard::put(`" << lyx << "' `"
522 << to_utf8(text) << "')");
523 // We don't convert the encoding of lyx since the encoding of the
524 // clipboard contents is specified in the data itself
525 QMimeData * data = new QMimeData;
527 QByteArray const qlyx(lyx.c_str(), lyx.size());
528 data->setData(lyx_mime_type, qlyx);
530 // Don't test for text.empty() since we want to be able to clear the
532 QString const qtext = toqstr(text);
533 data->setText(qtext);
534 qApp->clipboard()->setMimeData(data, QClipboard::Clipboard);
538 bool GuiClipboard::hasLyXContents() const
540 QMimeData const * const source =
541 qApp->clipboard()->mimeData(QClipboard::Clipboard);
542 return source && source->hasFormat(lyx_mime_type);
546 bool GuiClipboard::hasGraphicsContents(Clipboard::GraphicsType type) const
548 if (type == AnyGraphicsType) {
549 return hasGraphicsContents(PdfGraphicsType)
550 || hasGraphicsContents(PngGraphicsType)
551 || hasGraphicsContents(JpegGraphicsType)
552 || hasGraphicsContents(EmfGraphicsType)
553 || hasGraphicsContents(WmfGraphicsType)
554 || hasGraphicsContents(LinkBackGraphicsType);
557 QMimeData const * const source =
558 qApp->clipboard()->mimeData(QClipboard::Clipboard);
560 // handle image cases first
561 if (type == PngGraphicsType || type == JpegGraphicsType)
562 return source->hasImage();
564 // handle LinkBack for Mac
566 if (type == LinkBackGraphicsType)
567 return isLinkBackDataInPasteboard();
569 if (type == LinkBackGraphicsType)
574 QStringList const & formats = source->formats();
575 LYXERR(Debug::ACTION, "We found " << formats.size() << " formats");
576 for (int i = 0; i < formats.size(); ++i) {
577 LYXERR(Debug::ACTION, "Found format " << fromqstr(formats[i]));
580 // compute mime for type
583 case EmfGraphicsType: mime = emf_mime_type; break;
584 case WmfGraphicsType: mime = wmf_mime_type; break;
585 case PdfGraphicsType: mime = pdf_mime_type; break;
586 default: LASSERT(false, /**/);
589 return source && source->hasFormat(mime);
593 bool GuiClipboard::isInternal() const
595 // ownsClipboard() is also true for stuff coming from dialogs, e.g.
596 // the preamble dialog
597 // FIXME: This does only work on X11, since ownsClipboard() is
598 // hardwired to return false on Windows and OS X.
599 return qApp->clipboard()->ownsClipboard() && hasLyXContents();
603 bool GuiClipboard::hasInternal() const
605 // Windows and Mac OS X does not have the concept of ownership;
606 // the clipboard is a fully global resource so all applications
607 // are notified of changes.
608 #if (defined(Q_WS_X11))
616 void GuiClipboard::on_dataChanged()
618 QMimeData const * const source =
619 qApp->clipboard()->mimeData(QClipboard::Clipboard);
620 QStringList l = source->formats();
621 LYXERR(Debug::ACTION, "Qt Clipboard changed. We found the following mime types:");
622 for (int i = 0; i < l.count(); i++) {
623 LYXERR(Debug::ACTION, fromqstr(l.value(i)));
626 text_clipboard_empty_ = qApp->clipboard()->
627 text(QClipboard::Clipboard).isEmpty();
629 has_lyx_contents_ = hasLyXContents();
630 has_graphics_contents_ = hasGraphicsContents();
634 bool GuiClipboard::empty() const
636 // We need to check both the plaintext and the LyX version of the
637 // clipboard. The plaintext version is empty if the LyX version
638 // contains only one inset, and the LyX version is empty if the
639 // clipboard does not come from LyX.
640 if (!text_clipboard_empty_)
642 return !has_lyx_contents_ && !has_graphics_contents_;
645 } // namespace frontend
648 #include "GuiClipboard_moc.cpp"