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/lassert.h"
25 #include "support/convert.h"
26 #include "support/debug.h"
27 #include "support/filetools.h"
28 #include "support/gettext.h"
29 #include "support/lstrings.h"
30 #include "support/lyxtime.h"
33 #include "support/linkback/LinkBackProxy.h"
36 #include "frontends/alert.h"
38 #include <QApplication>
41 #include <QDataStream>
46 #include <QStringList>
47 #include <QTextDocument>
49 #include <boost/crc.hpp>
56 using namespace lyx::support;
63 static QMimeData const * read_clipboard()
65 LYXERR(Debug::ACTION, "Getting Clipboard");
66 QMimeData const * source =
67 qApp->clipboard()->mimeData(QClipboard::Clipboard);
69 LYXERR0("0 bytes (no QMimeData)");
72 // It appears that doing IO between getting a mimeData object
73 // and using it can cause a crash (maybe Qt used IO
74 // as an excuse to free() it? Anyway let's not introduce
75 // any new IO here, so e.g. leave the following line commented.
76 // lyxerr << "Got Clipboard (" << (long) source << ")\n" ;
81 void CacheMimeData::update()
83 time_t const start_time = current_time();
84 LYXERR(Debug::ACTION, "Creating CacheMimeData object");
85 cached_formats_ = read_clipboard()->formats();
87 // Qt times out after 5 seconds if it does not recieve a response.
88 if (current_time() - start_time > 3) {
89 LYXERR0("No timely response from clipboard, perhaps process "
90 << "holding clipboard is frozen?");
95 QByteArray CacheMimeData::data(QString const & mimeType) const
97 return read_clipboard()->data(mimeType);
101 QString const lyxMimeType(){ return "application/x-lyx"; }
102 QString const texMimeType(){ return "text/x-tex"; }
103 QString const latexMimeType(){ return "application/x-latex"; }
104 QString const pdfMimeType(){ return "application/pdf"; }
105 QString const emfMimeType(){ return "image/x-emf"; }
106 QString const wmfMimeType(){ return "image/x-wmf"; }
109 GuiClipboard::GuiClipboard()
111 connect(qApp->clipboard(), SIGNAL(dataChanged()),
112 this, SLOT(on_dataChanged()));
113 // initialize clipboard status.
118 string const GuiClipboard::getAsLyX() const
120 LYXERR(Debug::ACTION, "GuiClipboard::getAsLyX(): `");
121 // We don't convert encodings here since the encoding of the
122 // clipboard contents is specified in the data itself
123 if (cache_.hasFormat(lyxMimeType())) {
124 // data from ourself or some other LyX instance
125 QByteArray const ar = cache_.data(lyxMimeType());
126 string const s(ar.data(), ar.count());
127 LYXERR(Debug::ACTION, s << "'");
130 LYXERR(Debug::ACTION, "'");
135 FileName GuiClipboard::getPastedGraphicsFileName(Cursor const & cur,
136 Clipboard::GraphicsType & type) const
138 // create file dialog filter according to the existing types in the clipboard
139 vector<Clipboard::GraphicsType> types;
140 if (hasGraphicsContents(Clipboard::EmfGraphicsType))
141 types.push_back(Clipboard::EmfGraphicsType);
142 if (hasGraphicsContents(Clipboard::WmfGraphicsType))
143 types.push_back(Clipboard::WmfGraphicsType);
144 if (hasGraphicsContents(Clipboard::LinkBackGraphicsType))
145 types.push_back(Clipboard::LinkBackGraphicsType);
146 if (hasGraphicsContents(Clipboard::PdfGraphicsType))
147 types.push_back(Clipboard::PdfGraphicsType);
148 if (hasGraphicsContents(Clipboard::PngGraphicsType))
149 types.push_back(Clipboard::PngGraphicsType);
150 if (hasGraphicsContents(Clipboard::JpegGraphicsType))
151 types.push_back(Clipboard::JpegGraphicsType);
153 LASSERT(!types.empty(), return FileName());
155 // select prefered type if AnyGraphicsType was passed
156 if (type == Clipboard::AnyGraphicsType)
157 type = types.front();
160 map<Clipboard::GraphicsType, string> extensions;
161 map<Clipboard::GraphicsType, docstring> typeNames;
163 extensions[Clipboard::EmfGraphicsType] = "emf";
164 extensions[Clipboard::WmfGraphicsType] = "wmf";
165 extensions[Clipboard::LinkBackGraphicsType] = "linkback";
166 extensions[Clipboard::PdfGraphicsType] = "pdf";
167 extensions[Clipboard::PngGraphicsType] = "png";
168 extensions[Clipboard::JpegGraphicsType] = "jpeg";
170 typeNames[Clipboard::EmfGraphicsType] = _("Enhanced Metafile");
171 typeNames[Clipboard::WmfGraphicsType] = _("Windows Metafile");
172 typeNames[Clipboard::LinkBackGraphicsType] = _("LinkBack PDF");
173 typeNames[Clipboard::PdfGraphicsType] = _("PDF");
174 typeNames[Clipboard::PngGraphicsType] = _("PNG");
175 typeNames[Clipboard::JpegGraphicsType] = _("JPEG");
177 // find unused filename with primary extension
178 string document_path = cur.buffer()->fileName().onlyPath().absFileName();
179 unsigned newfile_number = 0;
183 filename = FileName(addName(document_path,
185 + convert<string>(newfile_number) + "."
186 + extensions[type]));
187 } while (filename.isReadableFile());
190 // create file type filter, putting the prefered on to the front
192 for (size_t i = 0; i != types.size(); ++i) {
193 docstring s = bformat(_("%1$s Files"), typeNames[types[i]])
194 + " (*." + from_ascii(extensions[types[i]]) + ")";
195 if (types[i] == type)
196 filter.prepend(toqstr(s));
198 filter.append(toqstr(s));
200 filter = fileFilters(filter.join(";;"));
202 // show save dialog for the graphic
203 FileDialog dlg(qt_("Choose a filename to save the pasted graphic as"));
204 FileDialog::Result result =
205 dlg.save(toqstr(filename.onlyPath().absFileName()), filter,
206 toqstr(filename.onlyFileName()));
208 if (result.first == FileDialog::Later)
211 string newFilename = fromqstr(result.second);
212 if (newFilename.empty()) {
213 cur.bv().message(_("Canceled."));
216 filename.set(newFilename);
218 // check the extension (the user could have changed it)
219 if (!suffixIs(ascii_lowercase(filename.absFileName()),
220 "." + extensions[type])) {
221 // the user changed the extension. Check if the type is available
223 for (i = 1; i != types.size(); ++i) {
224 if (suffixIs(ascii_lowercase(filename.absFileName()),
225 "." + extensions[types[i]])) {
231 // invalid extension found, or none at all. In the latter
232 // case set the default extensions.
233 if (i == types.size()
234 && filename.onlyFileName().find('.') == string::npos) {
235 filename.changeExtension("." + extensions[type]);
239 // check whether the file exists and warn the user
240 if (!filename.exists())
242 int ret = frontend::Alert::prompt(
243 _("Overwrite external file?"),
244 bformat(_("File %1$s already exists, do you want to overwrite it?"),
245 from_utf8(filename.absFileName())), 1, 1, _("&Overwrite"), _("&Cancel"));
247 // overwrite, hence break the dialog loop
250 // not overwrite, hence show the dialog again (i.e. loop)
257 FileName GuiClipboard::getAsGraphics(Cursor const & cur, GraphicsType type) const
259 // get the filename from the user
260 FileName filename = getPastedGraphicsFileName(cur, type);
261 if (filename.empty())
264 // handle image cases first
265 if (type == PngGraphicsType || type == JpegGraphicsType) {
266 // get image from QImage from clipboard
267 QImage image = qApp->clipboard()->image();
268 if (image.isNull()) {
269 LYXERR(Debug::ACTION, "No image in clipboard");
273 // convert into graphics format
276 buffer.open(QIODevice::WriteOnly);
277 if (type == PngGraphicsType)
278 image.save(toqstr(filename.absFileName()), "PNG");
279 else if (type == JpegGraphicsType)
280 image.save(toqstr(filename.absFileName()), "JPEG");
290 case PdfGraphicsType: mime = pdfMimeType(); break;
291 case LinkBackGraphicsType: mime = pdfMimeType(); break;
292 case EmfGraphicsType: mime = emfMimeType(); break;
293 case WmfGraphicsType: mime = wmfMimeType(); break;
294 default: LASSERT(false, return FileName());
298 if (!cache_.hasFormat(mime))
300 // data from ourself or some other LyX instance
301 QByteArray const ar = cache_.data(mime);
302 LYXERR(Debug::ACTION, "Getting from clipboard: mime = " << mime.constData()
303 << "length = " << ar.count());
305 QFile f(toqstr(filename.absFileName()));
306 if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
307 LYXERR(Debug::ACTION, "Error opening file "
308 << filename.absFileName() << " for writing");
312 // write the (LinkBack) PDF data
314 if (type == LinkBackGraphicsType) {
316 void const * linkBackData;
317 unsigned linkBackLen;
318 getLinkBackData(&linkBackData, &linkBackLen);
319 f.write((char *)linkBackData, linkBackLen);
320 quint32 pdfLen = ar.size();
322 ds << pdfLen; // big endian by default
324 // only non-Mac this should never happen
336 * Tidy up a HTML chunk coming from the clipboard.
337 * This is needed since different applications put different kinds of HTML
339 * - With or without the <?xml> tag
340 * - With or without the <!DOCTYPE> tag
341 * - With or without the <html> tag
342 * - With or without the <body> tag
343 * - With or without the <p> tag
344 * Since we are going to write a HTML file for external converters we need
345 * to ensure that it is a well formed HTML file, including all the mentioned tags.
347 QString tidyHtml(QString input)
349 // Misuse QTextDocument to cleanup the HTML.
350 // As a side effect, all visual markup like <tt> is converted to CSS,
351 // which is ignored by gnuhtml2latex.
352 // While this may be seen as a bug by some people it is actually a
353 // good thing, since we do import structure, but ignore all visual
355 QTextDocument converter;
356 converter.setHtml(input);
357 return converter.toHtml("utf-8");
362 docstring const GuiClipboard::getAsText(TextType type) const
364 // text data from other applications
365 if ((type == AnyTextType || type == LyXOrPlainTextType) && hasTextContents(LyXTextType))
367 if (type == AnyTextType && hasTextContents(LaTeXTextType))
368 type = LaTeXTextType;
369 if (type == AnyTextType && hasTextContents(HtmlTextType))
374 // must not convert to docstring, since file can contain
375 // mixed encodings (use getAsLyX() instead)
378 case LyXOrPlainTextType:
380 str = qApp->clipboard()->text(QClipboard::Clipboard)
381 .normalized(QString::NormalizationForm_C);
383 case LaTeXTextType: {
384 QMimeData const * source =
385 qApp->clipboard()->mimeData(QClipboard::Clipboard);
387 // First try LaTeX, then TeX (we do not distinguish
388 // for clipboard purposes)
389 if (source->hasFormat(latexMimeType())) {
390 str = source->data(latexMimeType());
391 str = str.normalized(QString::NormalizationForm_C);
392 } else if (source->hasFormat(texMimeType())) {
393 str = source->data(texMimeType());
394 str = str.normalized(QString::NormalizationForm_C);
400 QString subtype = "html";
401 str = qApp->clipboard()->text(subtype, QClipboard::Clipboard)
402 .normalized(QString::NormalizationForm_C);
407 LYXERR(Debug::ACTION, "GuiClipboard::getAsText(" << type << "): `" << str << "'");
411 return internalLineEnding(str);
415 void GuiClipboard::put(string const & lyx, docstring const & html, docstring const & text)
417 LYXERR(Debug::ACTION, "GuiClipboard::put(`" << lyx << "' `"
418 << to_utf8(html) << "' `" << to_utf8(text) << "')");
419 // We don't convert the encoding of lyx since the encoding of the
420 // clipboard contents is specified in the data itself
421 QMimeData * data = new QMimeData;
423 QByteArray const qlyx(lyx.c_str(), lyx.size());
424 data->setData(lyxMimeType(), qlyx);
425 // If the OS has not the concept of clipboard ownership,
426 // we recognize internal data through its checksum.
427 if (!hasInternal()) {
428 boost::crc_32_type crc32;
429 crc32.process_bytes(lyx.c_str(), lyx.size());
430 checksum = crc32.checksum();
433 // Don't test for text.empty() since we want to be able to clear the
435 QString const qtext = toqstr(text);
436 data->setText(qtext);
437 QString const qhtml = toqstr(html);
438 data->setHtml(qhtml);
439 qApp->clipboard()->setMimeData(data, QClipboard::Clipboard);
443 bool GuiClipboard::hasTextContents(Clipboard::TextType type) const
447 return cache_.hasFormat(lyxMimeType()) || cache_.hasText() ||
448 cache_.hasHtml() || cache_.hasFormat(latexMimeType()) ||
449 cache_.hasFormat(texMimeType());
450 case LyXOrPlainTextType:
451 return cache_.hasFormat(lyxMimeType()) || cache_.hasText();
453 return cache_.hasFormat(lyxMimeType());
455 return cache_.hasText();
457 return cache_.hasHtml();
459 return cache_.hasFormat(latexMimeType()) ||
460 cache_.hasFormat(texMimeType());
467 bool GuiClipboard::hasGraphicsContents(Clipboard::GraphicsType type) const
469 if (type == AnyGraphicsType) {
470 return hasGraphicsContents(PdfGraphicsType)
471 || hasGraphicsContents(PngGraphicsType)
472 || hasGraphicsContents(JpegGraphicsType)
473 || hasGraphicsContents(EmfGraphicsType)
474 || hasGraphicsContents(WmfGraphicsType)
475 || hasGraphicsContents(LinkBackGraphicsType);
478 // handle image cases first
479 if (type == PngGraphicsType || type == JpegGraphicsType)
480 return cache_.hasImage();
482 // handle LinkBack for Mac
483 if (type == LinkBackGraphicsType)
485 return isLinkBackDataInPasteboard();
491 QStringList const & formats = cache_.formats();
492 LYXERR(Debug::ACTION, "We found " << formats.size() << " formats");
493 for (int i = 0; i < formats.size(); ++i)
494 LYXERR(Debug::ACTION, "Found format " << formats[i]);
496 // compute mime for type
499 case EmfGraphicsType: mime = emfMimeType(); break;
500 case WmfGraphicsType: mime = wmfMimeType(); break;
501 case PdfGraphicsType: mime = pdfMimeType(); break;
502 default: LASSERT(false, return false);
505 return cache_.hasFormat(mime);
509 bool GuiClipboard::isInternal() const
511 if (!hasTextContents(LyXTextType))
514 // ownsClipboard() is also true for stuff coming from dialogs, e.g.
515 // the preamble dialog. This does only work on X11 and Windows, since
516 // ownsClipboard() is hardwired to return false on OS X.
518 return qApp->clipboard()->ownsClipboard();
520 // We are running on OS X: Check whether clipboard data is from
521 // ourself by comparing its checksum with the stored one.
522 QByteArray const ar = cache_.data(lyxMimeType());
523 string const data(ar.data(), ar.count());
524 boost::crc_32_type crc32;
525 crc32.process_bytes(data.c_str(), data.size());
526 return checksum == crc32.checksum();
530 bool GuiClipboard::hasInternal() const
532 // Windows and Mac OS X does not have the concept of ownership;
533 // the clipboard is a fully global resource so all applications
534 // are notified of changes. However, on Windows ownership is
535 // emulated by Qt through the OleIsCurrentClipboard() API, while
536 // on Mac OS X we deal with this issue by ourself.
537 #if (defined(Q_WS_X11) || defined(Q_WS_WIN))
545 void GuiClipboard::on_dataChanged()
547 //Note: we do not really need to run cache_.update() unless the
548 //data has been changed *and* the GuiClipboard has been queried.
549 //However if run cache_.update() the moment a process grabs the
550 //clipboard, the process holding the clipboard presumably won't
551 //yet be frozen, and so we won't need to wait 5 seconds for Qt
552 //to time-out waiting for the clipboard.
554 QStringList l = cache_.formats();
555 LYXERR(Debug::ACTION, "Qt Clipboard changed. We found the following mime types:");
556 for (int i = 0; i < l.count(); i++)
557 LYXERR(Debug::ACTION, l.value(i));
559 plaintext_clipboard_empty_ = qApp->clipboard()->
560 text(QClipboard::Clipboard).isEmpty();
562 has_text_contents_ = hasTextContents();
563 has_graphics_contents_ = hasGraphicsContents();
567 bool GuiClipboard::empty() const
569 // We need to check both the plaintext and the LyX version of the
570 // clipboard. The plaintext version is empty if the LyX version
571 // contains only one inset, and the LyX version is empty if the
572 // clipboard does not come from LyX.
573 if (!plaintext_clipboard_empty_)
575 return !has_text_contents_ && !has_graphics_contents_;
578 } // namespace frontend
581 #include "moc_GuiClipboard.cpp"