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 "frontends/alert.h"
20 #include "BufferView.h"
22 #include "GuiClipboard.h"
23 #include "qt_helpers.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 <QApplication>
35 #include <QDataStream>
38 #include <QMacPasteboardMime>
41 #include <QStringList>
43 #include "boost/assert.hpp"
48 #include "support/linkback/LinkBackProxy.h"
52 using namespace lyx::support;
54 static char const * const lyx_mime_type = "application/x-lyx";
55 static char const * const pdf_mime_type = "application/pdf";
63 class QMacPasteboardMimeGraphics : public QMacPasteboardMime {
65 QMacPasteboardMimeGraphics()
66 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL) {}
67 ~QMacPasteboardMimeGraphics() {}
68 QString convertorName();
69 QString flavorFor(const QString &mime);
70 QString mimeFor(QString flav);
71 bool canConvert(const QString &mime, QString flav);
72 QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
73 QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
77 QString QMacPasteboardMimeGraphics::convertorName()
83 QString QMacPasteboardMimeGraphics::flavorFor(const QString &mime)
85 LYXERR(Debug::ACTION, "flavorFor " << fromqstr(mime));
86 if (mime == QLatin1String(pdf_mime_type))
87 return QLatin1String("com.adobe.pdf");
92 QString QMacPasteboardMimeGraphics::mimeFor(QString flav)
94 LYXERR(Debug::ACTION, "mimeFor " << fromqstr(flav));
95 if (flav == QLatin1String("com.adobe.pdf"))
96 return QLatin1String(pdf_mime_type);
101 bool QMacPasteboardMimeGraphics::canConvert(const QString &mime, QString flav)
103 return mimeFor(flav) == mime;
107 QVariant QMacPasteboardMimeGraphics::convertToMime(const QString &mime, QList<QByteArray> data, QString)
110 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
115 QList<QByteArray> QMacPasteboardMimeGraphics::convertFromMime(const QString &mime, QVariant data, QString)
117 QList<QByteArray> ret;
118 ret.append(data.toByteArray());
122 static QMacPasteboardMimeGraphics * graphicsPasteboardMime;
127 GuiClipboard::GuiClipboard()
129 connect(qApp->clipboard(), SIGNAL(dataChanged()),
130 this, SLOT(on_dataChanged()));
131 // initialize clipboard status.
135 if (!graphicsPasteboardMime)
136 graphicsPasteboardMime = new QMacPasteboardMimeGraphics();
141 GuiClipboard::~GuiClipboard()
144 closeAllLinkBackLinks();
149 string const GuiClipboard::getAsLyX() const
151 LYXERR(Debug::ACTION, "GuiClipboard::getAsLyX(): `");
152 // We don't convert encodings here since the encoding of the
153 // clipboard contents is specified in the data itself
154 QMimeData const * source =
155 qApp->clipboard()->mimeData(QClipboard::Clipboard);
157 LYXERR(Debug::ACTION, "' (no QMimeData)");
161 if (source->hasFormat(lyx_mime_type)) {
162 // data from ourself or some other LyX instance
163 QByteArray const ar = source->data(lyx_mime_type);
164 string const s(ar.data(), ar.count());
165 LYXERR(Debug::ACTION, s << "'");
168 LYXERR(Debug::ACTION, "'");
173 FileName GuiClipboard::getPastedGraphicsFileName(Cursor const & cur,
174 Clipboard::GraphicsType & type) const
176 // create file dialog filter according to the existing types in the clipboard
177 vector<Clipboard::GraphicsType> types;
178 if (hasGraphicsContents(Clipboard::LinkBackGraphicsType))
179 types.push_back(Clipboard::LinkBackGraphicsType);
180 if (hasGraphicsContents(Clipboard::PdfGraphicsType))
181 types.push_back(Clipboard::PdfGraphicsType);
182 if (hasGraphicsContents(Clipboard::PngGraphicsType))
183 types.push_back(Clipboard::PngGraphicsType);
184 if (hasGraphicsContents(Clipboard::JpegGraphicsType))
185 types.push_back(Clipboard::JpegGraphicsType);
187 BOOST_ASSERT(!types.empty());
189 // select prefered type if AnyGraphicsType was passed
190 if (type == Clipboard::AnyGraphicsType)
191 type = types.front();
194 map<Clipboard::GraphicsType, string> extensions;
195 map<Clipboard::GraphicsType, docstring> typeNames;
197 extensions[Clipboard::LinkBackGraphicsType] = "linkback";
198 extensions[Clipboard::PdfGraphicsType] = "pdf";
199 extensions[Clipboard::PngGraphicsType] = "png";
200 extensions[Clipboard::JpegGraphicsType] = "jpeg";
202 typeNames[Clipboard::LinkBackGraphicsType] = _("LinkBack PDF");
203 typeNames[Clipboard::PdfGraphicsType] = _("PDF");
204 typeNames[Clipboard::PngGraphicsType] = _("PNG");
205 typeNames[Clipboard::JpegGraphicsType] = _("JPEG");
207 // find unused filename with primary extension
208 string document_path = cur.buffer().fileName().onlyPath().absFilename();
209 unsigned newfile_number = 0;
214 = FileName(addName(document_path,
216 + convert<string>(newfile_number) + "."
217 + extensions[type]));
218 } while (filename.isReadableFile());
221 // create file type filter, putting the prefered on to the front
222 docstring filterSpec;
223 for (unsigned i = 0; i < types.size(); ++i) {
224 docstring s = bformat(_("%1$s Files"), typeNames[types[i]])
225 + " (*." + from_ascii(extensions[types[i]]) + ")";
226 if (types[i] == type)
227 filterSpec = s + filterSpec;
229 filterSpec += ";;" + s;
231 FileFilterList const filter(filterSpec);
233 // show save dialog for the graphic
234 FileDialog dlg(_("Choose a filename to save the pasted graphic as"));
235 FileDialog::Result result =
236 dlg.save(from_utf8(filename.onlyPath().absFilename()), filter,
237 from_utf8(filename.onlyFileName()));
239 if (result.first == FileDialog::Later)
242 string newFilename = to_utf8(result.second);
243 if (newFilename.empty()) {
244 cur.bv().message(_("Canceled."));
247 filename.set(newFilename);
249 // check the extension (the user could have changed it)
250 if (!suffixIs(ascii_lowercase(filename.absFilename()),
251 "." + extensions[type])) {
252 // the user changed the extension. Check if the type is available
254 for (i = 1; i < types.size(); ++i) {
255 if (suffixIs(ascii_lowercase(filename.absFilename()),
256 "." + extensions[types[i]])) {
262 // invalid extension found, or none at all. In the latter
263 // case set the default extensions.
264 if (i == types.size()
265 && filename.onlyFileName().find('.') == string::npos) {
266 filename.changeExtension("." + extensions[type]);
270 // check whether the file exists and warn the user
271 if (!filename.exists())
273 int ret = frontend::Alert::prompt(
274 _("Overwrite external file?"),
275 bformat(_("File %1$s already exists, do you want to overwrite it"),
276 from_utf8(filename.absFilename())), 1, 1, _("&Overwrite"), _("&Cancel"));
278 // overwrite, hence break the dialog loop
281 // not overwrite, hence show the dialog again (i.e. loop)
288 FileName GuiClipboard::getAsGraphics(Cursor const & cur, GraphicsType type) const
290 // get the filename from the user
291 FileName filename = getPastedGraphicsFileName(cur, type);
292 if (filename.empty())
295 // handle image cases first
296 if (type == PngGraphicsType || type == JpegGraphicsType) {
297 // get image from QImage from clipboard
298 QImage image = qApp->clipboard()->image();
299 if (image.isNull()) {
300 LYXERR(Debug::ACTION, "No image in clipboard");
304 // convert into graphics format
307 buffer.open(QIODevice::WriteOnly);
308 if (type == PngGraphicsType)
309 image.save(toqstr(filename.absFilename()), "PNG");
310 else if (type == JpegGraphicsType)
311 image.save(toqstr(filename.absFilename()), "JPEG");
319 QMimeData const * source =
320 qApp->clipboard()->mimeData(QClipboard::Clipboard);
322 LYXERR(Debug::ACTION, "0 bytes (no QMimeData)");
329 case PdfGraphicsType: mime = pdf_mime_type; break;
330 case LinkBackGraphicsType: mime = pdf_mime_type; break;
331 default: BOOST_ASSERT(false);
335 if (!source->hasFormat(mime))
337 // data from ourself or some other LyX instance
338 QByteArray const ar = source->data(mime);
339 LYXERR(Debug::ACTION, "Getting from clipboard: mime = " << mime.data()
340 << "length = " << ar.count());
342 QFile f(toqstr(filename.absFilename()));
343 if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
344 LYXERR(Debug::ACTION, "Error opening file "
345 << filename.absFilename() << " for writing");
349 // write the (LinkBack) PDF data
351 if (type == LinkBackGraphicsType) {
353 void const * linkBackData;
354 unsigned linkBackLen;
355 getLinkBackData(&linkBackData, &linkBackLen);
356 f.write((char *)linkBackData, linkBackLen);
357 quint32 pdfLen = ar.size();
359 ds << pdfLen; // big endian by default
361 // only non-Mac this should never happen
371 docstring const GuiClipboard::getAsText() const
373 // text data from other applications
374 QString const str = qApp->clipboard()->text(QClipboard::Clipboard)
375 .normalized(QString::NormalizationForm_C);
376 LYXERR(Debug::ACTION, "GuiClipboard::getAsText(): `" << fromqstr(str) << "'");
380 return internalLineEnding(qstring_to_ucs4(str));
384 void GuiClipboard::put(string const & lyx, docstring const & text)
386 LYXERR(Debug::ACTION, "GuiClipboard::put(`" << lyx << "' `"
387 << to_utf8(text) << "')");
388 // We don't convert the encoding of lyx since the encoding of the
389 // clipboard contents is specified in the data itself
390 QMimeData * data = new QMimeData;
392 QByteArray const qlyx(lyx.c_str(), lyx.size());
393 data->setData(lyx_mime_type, qlyx);
395 // Don't test for text.empty() since we want to be able to clear the
397 QString const qtext = toqstr(text);
398 data->setText(qtext);
399 qApp->clipboard()->setMimeData(data, QClipboard::Clipboard);
403 bool GuiClipboard::hasLyXContents() const
405 QMimeData const * const source =
406 qApp->clipboard()->mimeData(QClipboard::Clipboard);
407 return source && source->hasFormat(lyx_mime_type);
411 bool GuiClipboard::hasGraphicsContents(Clipboard::GraphicsType type) const
413 if (type == AnyGraphicsType) {
414 return hasGraphicsContents(PdfGraphicsType)
415 || hasGraphicsContents(PngGraphicsType)
416 || hasGraphicsContents(JpegGraphicsType)
417 || hasGraphicsContents(LinkBackGraphicsType);
420 QMimeData const * const source =
421 qApp->clipboard()->mimeData(QClipboard::Clipboard);
423 // handle image cases first
424 if (type == PngGraphicsType || type == JpegGraphicsType)
425 return source->hasImage();
427 // handle LinkBack for Mac
429 if (type == LinkBackGraphicsType)
430 return isLinkBackDataInPasteboard();
432 if (type == LinkBackGraphicsType)
437 QStringList const & formats = source->formats();
438 LYXERR(Debug::ACTION, "We found " << formats.size() << " formats");
439 for (int i = 0; i < formats.size(); ++i) {
440 LYXERR(Debug::ACTION, "Found format " << fromqstr(formats[i]));
443 // compute mime for type
446 case PdfGraphicsType: mime = pdf_mime_type; break;
447 default: BOOST_ASSERT(false);
450 return source && source->hasFormat(mime);
454 bool GuiClipboard::isInternal() const
456 // ownsClipboard() is also true for stuff coming from dialogs, e.g.
457 // the preamble dialog
458 // FIXME: This does only work on X11, since ownsClipboard() is
459 // hardwired to return false on Windows and OS X.
460 return qApp->clipboard()->ownsClipboard() && hasLyXContents();
464 bool GuiClipboard::hasInternal() const
466 // Windows and Mac OS X does not have the concept of ownership;
467 // the clipboard is a fully global resource so all applications
468 // are notified of changes.
469 #if (defined(Q_WS_X11))
477 void GuiClipboard::on_dataChanged()
479 QMimeData const * const source =
480 qApp->clipboard()->mimeData(QClipboard::Clipboard);
481 QStringList l = source->formats();
482 LYXERR(Debug::ACTION, "Qt Clipboard changed. We found the following mime types:");
483 for (int i = 0; i < l.count(); i++) {
484 LYXERR(Debug::ACTION, fromqstr(l.value(i)));
487 text_clipboard_empty_ = qApp->clipboard()->
488 text(QClipboard::Clipboard).isEmpty();
490 has_lyx_contents_ = hasLyXContents();
491 has_graphics_contents_ = hasGraphicsContents();
495 bool GuiClipboard::empty() const
497 // We need to check both the plaintext and the LyX version of the
498 // clipboard. The plaintext version is empty if the LyX version
499 // contains only one inset, and the LyX version is empty if the
500 // clipboard does not come from LyX.
501 if (!text_clipboard_empty_)
503 return !has_lyx_contents_ && !has_graphics_contents_;
506 } // namespace frontend
509 #include "GuiClipboard_moc.cpp"