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 "support/FileName.h"
18 #include "GuiClipboard.h"
19 #include "qt_helpers.h"
22 #include "BufferView.h"
25 #include "support/lassert.h"
26 #include "support/convert.h"
27 #include "support/debug.h"
28 #include "support/filetools.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/lyxtime.h"
34 #include "support/linkback/LinkBackProxy.h"
37 #include "frontends/alert.h"
39 #include <QApplication>
42 #include <QDataStream>
47 #include <QStringList>
48 #include <QTextDocument>
51 #include <boost/crc.hpp>
58 using namespace lyx::support;
65 static QMimeData const * read_clipboard()
67 LYXERR(Debug::CLIPBOARD, "Getting Clipboard");
68 QMimeData const * source =
69 qApp->clipboard()->mimeData(QClipboard::Clipboard);
71 LYXERR0("0 bytes (no QMimeData)");
74 // It appears that doing IO between getting a mimeData object
75 // and using it can cause a crash (maybe Qt used IO
76 // as an excuse to free() it? Anyway let's not introduce
77 // any new IO here, so e.g. leave the following line commented.
78 // lyxerr << "Got Clipboard (" << (long) source << ")\n" ;
83 void CacheMimeData::update()
85 time_t const start_time = current_time();
86 LYXERR(Debug::CLIPBOARD, "Creating CacheMimeData object");
87 cached_formats_ = read_clipboard()->formats();
89 // Qt times out after 5 seconds if it does not recieve a response.
90 if (current_time() - start_time > 3) {
91 LYXERR0("No timely response from clipboard, perhaps process "
92 << "holding clipboard is frozen?");
97 QByteArray CacheMimeData::data(QString const & mimeType) const
99 return read_clipboard()->data(mimeType);
103 QString const lyxMimeType(){ return "application/x-lyx"; }
104 QString const texMimeType(){ return "text/x-tex"; }
105 QString const latexMimeType(){ return "application/x-latex"; }
106 QString const pdfMimeType(){ return "application/pdf"; }
107 QString const emfMimeType(){ return "image/x-emf"; }
108 QString const wmfMimeType(){ return "image/x-wmf"; }
111 GuiClipboard::GuiClipboard()
113 connect(qApp->clipboard(), SIGNAL(dataChanged()),
114 this, SLOT(on_dataChanged()));
115 // initialize clipboard status.
120 string const GuiClipboard::getAsLyX() const
122 LYXERR(Debug::CLIPBOARD, "GuiClipboard::getAsLyX(): `");
123 // We don't convert encodings here since the encoding of the
124 // clipboard contents is specified in the data itself
125 if (cache_.hasFormat(lyxMimeType())) {
126 // data from ourself or some other LyX instance
127 QByteArray const ar = cache_.data(lyxMimeType());
128 string const s(ar.data(), ar.count());
129 LYXERR(Debug::CLIPBOARD, s << "'");
132 LYXERR(Debug::CLIPBOARD, "'");
137 FileName GuiClipboard::getPastedGraphicsFileName(Cursor const & cur,
138 Clipboard::GraphicsType & type) const
140 // create file dialog filter according to the existing types in the clipboard
141 vector<Clipboard::GraphicsType> types;
142 if (hasGraphicsContents(Clipboard::EmfGraphicsType))
143 types.push_back(Clipboard::EmfGraphicsType);
144 if (hasGraphicsContents(Clipboard::WmfGraphicsType))
145 types.push_back(Clipboard::WmfGraphicsType);
146 if (hasGraphicsContents(Clipboard::LinkBackGraphicsType))
147 types.push_back(Clipboard::LinkBackGraphicsType);
148 if (hasGraphicsContents(Clipboard::PdfGraphicsType))
149 types.push_back(Clipboard::PdfGraphicsType);
150 if (hasGraphicsContents(Clipboard::PngGraphicsType))
151 types.push_back(Clipboard::PngGraphicsType);
152 if (hasGraphicsContents(Clipboard::JpegGraphicsType))
153 types.push_back(Clipboard::JpegGraphicsType);
155 LASSERT(!types.empty(), return FileName());
157 // select prefered type if AnyGraphicsType was passed
158 if (type == Clipboard::AnyGraphicsType)
159 type = types.front();
162 map<Clipboard::GraphicsType, string> extensions;
163 map<Clipboard::GraphicsType, docstring> typeNames;
165 extensions[Clipboard::EmfGraphicsType] = "emf";
166 extensions[Clipboard::WmfGraphicsType] = "wmf";
167 extensions[Clipboard::LinkBackGraphicsType] = "linkback";
168 extensions[Clipboard::PdfGraphicsType] = "pdf";
169 extensions[Clipboard::PngGraphicsType] = "png";
170 extensions[Clipboard::JpegGraphicsType] = "jpeg";
172 typeNames[Clipboard::EmfGraphicsType] = _("Enhanced Metafile");
173 typeNames[Clipboard::WmfGraphicsType] = _("Windows Metafile");
174 typeNames[Clipboard::LinkBackGraphicsType] = _("LinkBack PDF");
175 typeNames[Clipboard::PdfGraphicsType] = _("PDF");
176 typeNames[Clipboard::PngGraphicsType] = _("PNG");
177 typeNames[Clipboard::JpegGraphicsType] = _("JPEG");
179 // find unused filename with primary extension
180 string document_path = cur.buffer()->fileName().onlyPath().absFileName();
181 unsigned newfile_number = 0;
185 filename = FileName(addName(document_path,
187 + convert<string>(newfile_number) + "."
188 + extensions[type]));
189 } while (filename.isReadableFile());
192 // create file type filter, putting the prefered on to the front
194 for (size_t i = 0; i != types.size(); ++i) {
195 docstring s = bformat(_("%1$s Files"), typeNames[types[i]])
196 + " (*." + from_ascii(extensions[types[i]]) + ")";
197 if (types[i] == type)
198 filter.prepend(toqstr(s));
200 filter.append(toqstr(s));
202 filter = fileFilters(filter.join(";;"));
204 // show save dialog for the graphic
205 FileDialog dlg(qt_("Choose a filename to save the pasted graphic as"));
206 FileDialog::Result result =
207 dlg.save(toqstr(filename.onlyPath().absFileName()), filter,
208 toqstr(filename.onlyFileName()));
210 if (result.first == FileDialog::Later)
213 string newFilename = fromqstr(result.second);
214 if (newFilename.empty()) {
215 cur.bv().message(_("Canceled."));
218 filename.set(newFilename);
220 // check the extension (the user could have changed it)
221 if (!suffixIs(ascii_lowercase(filename.absFileName()),
222 "." + extensions[type])) {
223 // the user changed the extension. Check if the type is available
225 for (i = 1; i != types.size(); ++i) {
226 if (suffixIs(ascii_lowercase(filename.absFileName()),
227 "." + extensions[types[i]])) {
233 // invalid extension found, or none at all. In the latter
234 // case set the default extensions.
235 if (i == types.size()
236 && filename.onlyFileName().find('.') == string::npos) {
237 filename.changeExtension("." + extensions[type]);
241 // check whether the file exists and warn the user
242 if (!filename.exists())
244 int ret = frontend::Alert::prompt(
245 _("Overwrite external file?"),
246 bformat(_("File %1$s already exists, do you want to overwrite it?"),
247 from_utf8(filename.absFileName())), 1, 1, _("&Overwrite"), _("&Cancel"));
249 // overwrite, hence break the dialog loop
252 // not overwrite, hence show the dialog again (i.e. loop)
259 FileName GuiClipboard::getAsGraphics(Cursor const & cur, GraphicsType type) const
261 // get the filename from the user
262 FileName filename = getPastedGraphicsFileName(cur, type);
263 if (filename.empty())
266 // handle image cases first
267 if (type == PngGraphicsType || type == JpegGraphicsType) {
268 // get image from QImage from clipboard
269 QImage image = qApp->clipboard()->image();
270 if (image.isNull()) {
271 LYXERR(Debug::CLIPBOARD, "No image in clipboard");
275 // convert into graphics format
278 buffer.open(QIODevice::WriteOnly);
279 if (type == PngGraphicsType)
280 image.save(toqstr(filename.absFileName()), "PNG");
281 else if (type == JpegGraphicsType)
282 image.save(toqstr(filename.absFileName()), "JPEG");
292 case PdfGraphicsType: mime = pdfMimeType(); break;
293 case LinkBackGraphicsType: mime = pdfMimeType(); break;
294 case EmfGraphicsType: mime = emfMimeType(); break;
295 case WmfGraphicsType: mime = wmfMimeType(); break;
296 default: LASSERT(false, return FileName());
300 if (!cache_.hasFormat(mime))
302 // data from ourself or some other LyX instance
303 QByteArray const ar = cache_.data(mime);
304 LYXERR(Debug::CLIPBOARD, "Getting from clipboard: mime = " << mime.constData()
305 << "length = " << ar.count());
307 QFile f(toqstr(filename.absFileName()));
308 if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
309 LYXERR(Debug::CLIPBOARD, "Error opening file "
310 << filename.absFileName() << " for writing");
314 // write the (LinkBack) PDF data
316 if (type == LinkBackGraphicsType) {
318 void const * linkBackData;
319 unsigned linkBackLen;
320 getLinkBackData(&linkBackData, &linkBackLen);
321 f.write((char *)linkBackData, linkBackLen);
322 quint32 pdfLen = ar.size();
324 ds << pdfLen; // big endian by default
326 // only non-Mac this should never happen
338 * Tidy up a HTML chunk coming from the clipboard.
339 * This is needed since different applications put different kinds of HTML
341 * - With or without the <?xml> tag
342 * - With or without the <!DOCTYPE> tag
343 * - With or without the <html> tag
344 * - With or without the <body> tag
345 * - With or without the <p> tag
346 * Since we are going to write a HTML file for external converters we need
347 * to ensure that it is a well formed HTML file, including all the mentioned tags.
349 QString tidyHtml(QString input)
351 // Misuse QTextDocument to cleanup the HTML.
352 // As a side effect, all visual markup like <tt> is converted to CSS,
353 // which is ignored by gnuhtml2latex.
354 // While this may be seen as a bug by some people it is actually a
355 // good thing, since we do import structure, but ignore all visual
357 QTextDocument converter;
358 converter.setHtml(input);
359 return converter.toHtml("utf-8");
364 docstring const GuiClipboard::getAsText(TextType type) const
366 // text data from other applications
367 if ((type == AnyTextType || type == LyXOrPlainTextType) && hasTextContents(LyXTextType))
369 if (type == AnyTextType && hasTextContents(LaTeXTextType))
370 type = LaTeXTextType;
371 if (type == AnyTextType && hasTextContents(HtmlTextType))
376 // must not convert to docstring, since file can contain
377 // mixed encodings (use getAsLyX() instead)
380 case LyXOrPlainTextType:
382 str = qApp->clipboard()->text(QClipboard::Clipboard)
383 .normalized(QString::NormalizationForm_C);
385 case LaTeXTextType: {
386 QMimeData const * source =
387 qApp->clipboard()->mimeData(QClipboard::Clipboard);
389 // First try LaTeX, then TeX (we do not distinguish
390 // for clipboard purposes)
391 if (source->hasFormat(latexMimeType())) {
392 str = source->data(latexMimeType());
393 str = str.normalized(QString::NormalizationForm_C);
394 } else if (source->hasFormat(texMimeType())) {
395 str = source->data(texMimeType());
396 str = str.normalized(QString::NormalizationForm_C);
402 QString subtype = "html";
403 str = qApp->clipboard()->text(subtype, QClipboard::Clipboard)
404 .normalized(QString::NormalizationForm_C);
409 LYXERR(Debug::CLIPBOARD, "GuiClipboard::getAsText(" << type << "): `" << str << "'");
413 return internalLineEnding(str);
417 void GuiClipboard::put(string const & text) const
419 qApp->clipboard()->setText(toqstr(text));
423 void GuiClipboard::put(string const & lyx, docstring const & html, docstring const & text)
425 LYXERR(Debug::CLIPBOARD, "GuiClipboard::put(`" << lyx << "' `"
426 << to_utf8(html) << "' `" << to_utf8(text) << "')");
427 // We don't convert the encoding of lyx since the encoding of the
428 // clipboard contents is specified in the data itself
429 QMimeData * data = new QMimeData;
431 QByteArray const qlyx(lyx.c_str(), lyx.size());
432 data->setData(lyxMimeType(), qlyx);
433 // If the OS has not the concept of clipboard ownership,
434 // we recognize internal data through its checksum.
435 if (!hasInternal()) {
436 boost::crc_32_type crc32;
437 crc32.process_bytes(lyx.c_str(), lyx.size());
438 checksum = crc32.checksum();
441 // Don't test for text.empty() since we want to be able to clear the
443 QString const qtext = toqstr(text);
444 data->setText(qtext);
445 QString const qhtml = toqstr(html);
446 data->setHtml(qhtml);
447 qApp->clipboard()->setMimeData(data, QClipboard::Clipboard);
451 bool GuiClipboard::hasTextContents(Clipboard::TextType type) const
455 return cache_.hasFormat(lyxMimeType()) || cache_.hasText() ||
456 cache_.hasHtml() || cache_.hasFormat(latexMimeType()) ||
457 cache_.hasFormat(texMimeType());
458 case LyXOrPlainTextType:
459 return cache_.hasFormat(lyxMimeType()) || cache_.hasText();
461 return cache_.hasFormat(lyxMimeType());
463 return cache_.hasText();
465 return cache_.hasHtml();
467 return cache_.hasFormat(latexMimeType()) ||
468 cache_.hasFormat(texMimeType());
475 bool GuiClipboard::hasGraphicsContents(Clipboard::GraphicsType type) const
477 if (type == AnyGraphicsType) {
478 return hasGraphicsContents(PdfGraphicsType)
479 || hasGraphicsContents(PngGraphicsType)
480 || hasGraphicsContents(JpegGraphicsType)
481 || hasGraphicsContents(EmfGraphicsType)
482 || hasGraphicsContents(WmfGraphicsType)
483 || hasGraphicsContents(LinkBackGraphicsType);
486 // handle image cases first
487 if (type == PngGraphicsType || type == JpegGraphicsType)
488 return cache_.hasImage();
490 // handle LinkBack for Mac
491 if (type == LinkBackGraphicsType)
493 return isLinkBackDataInPasteboard();
499 QStringList const & formats = cache_.formats();
500 LYXERR(Debug::CLIPBOARD, "We found " << formats.size() << " formats");
501 for (int i = 0; i < formats.size(); ++i)
502 LYXERR(Debug::CLIPBOARD, "Found format " << formats[i]);
504 // compute mime for type
507 case EmfGraphicsType: mime = emfMimeType(); break;
508 case WmfGraphicsType: mime = wmfMimeType(); break;
509 case PdfGraphicsType: mime = pdfMimeType(); break;
510 default: LASSERT(false, return false);
513 return cache_.hasFormat(mime);
517 bool GuiClipboard::isInternal() const
519 if (!hasTextContents(LyXTextType))
522 // ownsClipboard() is also true for stuff coming from dialogs, e.g.
523 // the preamble dialog. This does only work on X11 and Windows, since
524 // ownsClipboard() is hardwired to return false on OS X.
526 return qApp->clipboard()->ownsClipboard();
528 // We are running on OS X: Check whether clipboard data is from
529 // ourself by comparing its checksum with the stored one.
530 QByteArray const ar = cache_.data(lyxMimeType());
531 string const data(ar.data(), ar.count());
532 boost::crc_32_type crc32;
533 crc32.process_bytes(data.c_str(), data.size());
534 return checksum == crc32.checksum();
538 bool GuiClipboard::hasInternal() const
540 // Windows and Mac OS X does not have the concept of ownership;
541 // the clipboard is a fully global resource so all applications
542 // are notified of changes. However, on Windows ownership is
543 // emulated by Qt through the OleIsCurrentClipboard() API, while
544 // on Mac OS X we deal with this issue by ourself.
553 void GuiClipboard::on_dataChanged()
556 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
557 // Retry on Windows (#10109)
558 if (cache_.formats().count() == 0) {
559 QTimer::singleShot(100, this, SLOT(update()));
564 void GuiClipboard::update()
566 //Note: we do not really need to run cache_.update() unless the
567 //data has been changed *and* the GuiClipboard has been queried.
568 //However if run cache_.update() the moment a process grabs the
569 //clipboard, the process holding the clipboard presumably won't
570 //yet be frozen, and so we won't need to wait 5 seconds for Qt
571 //to time-out waiting for the clipboard.
573 QStringList l = cache_.formats();
574 LYXERR(Debug::CLIPBOARD, "Qt Clipboard changed. We found the following mime types:");
575 for (int i = 0; i < l.count(); i++)
576 LYXERR(Debug::CLIPBOARD, l.value(i));
578 plaintext_clipboard_empty_ = qApp->clipboard()->
579 text(QClipboard::Clipboard).isEmpty();
581 has_text_contents_ = hasTextContents();
582 has_graphics_contents_ = hasGraphicsContents();
586 bool GuiClipboard::empty() const
588 // We need to check both the plaintext and the LyX version of the
589 // clipboard. The plaintext version is empty if the LyX version
590 // contains only one inset, and the LyX version is empty if the
591 // clipboard does not come from LyX.
592 if (!plaintext_clipboard_empty_)
594 return !has_text_contents_ && !has_graphics_contents_;
597 } // namespace frontend
600 #include "moc_GuiClipboard.cpp"