]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiClipboard.cpp
#8055 add support for system-wide find buffer on Mac
[lyx.git] / src / frontends / qt / GuiClipboard.cpp
1 // -*- C++ -*-
2 /**
3  * \file qt/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 "GuiApplication.h"
16 #include "GuiClipboard.h"
17
18 #include "Buffer.h"
19 #include "BufferView.h"
20 #include "Cursor.h"
21 #include "FileDialog.h"
22 #include "qt_helpers.h"
23
24 #include "support/lassert.h"
25 #include "support/convert.h"
26 #include "support/debug.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/lyxtime.h"
32
33 #ifdef Q_OS_MAC
34 #include "support/linkback/LinkBackProxy.h"
35 #endif // Q_OS_MAC
36
37 #include "frontends/alert.h"
38
39 #include "support/checksum.h"
40
41 #include <QApplication>
42 #include <QBuffer>
43 #include <QClipboard>
44 #include <QDataStream>
45 #include <QFile>
46 #include <QImage>
47 #include <QMimeData>
48 #include <QString>
49 #include <QStringList>
50 #include <QTextDocument>
51 #include <QTimer>
52
53 #include <memory>
54 #include <map>
55 #include <iostream>
56
57 using namespace std;
58 using namespace lyx::support;
59
60
61 namespace lyx {
62
63 namespace frontend {
64
65 static QMimeData const * read_clipboard()
66 {
67         LYXERR(Debug::CLIPBOARD, "Getting Clipboard");
68         QMimeData const * source =
69                 qApp->clipboard()->mimeData(QClipboard::Clipboard);
70         if (!source) {
71                 LYXERR0("0 bytes (no QMimeData)");
72                 return new QMimeData;
73         }
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" ;
79         return source;
80 }
81
82
83 void CacheMimeData::update()
84 {
85         time_t const start_time = current_time();
86         LYXERR(Debug::CLIPBOARD, "Creating CacheMimeData object");
87         cached_formats_ = read_clipboard()->formats();
88
89         // Qt times out after 5 seconds if it does not receive a response.
90         if (current_time() - start_time > 3) {
91                 LYXERR0("No timely response from clipboard, perhaps process "
92                         << "holding clipboard is frozen?");
93         }
94 }
95
96
97 QByteArray CacheMimeData::data(QString const & mimeType) const
98 {
99         return read_clipboard()->data(mimeType);
100 }
101
102
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"; }
109
110
111 GuiClipboard::GuiClipboard()
112 {
113         connect(qApp->clipboard(), SIGNAL(dataChanged()),
114                 this, SLOT(on_dataChanged()));
115         if(qApp->clipboard()->supportsFindBuffer()) {
116                 connect(qApp->clipboard(), SIGNAL(findBufferChanged()),
117                         this, SLOT(on_findChanged()));
118                 on_findChanged();
119         }
120         // initialize clipboard status.
121         update();
122 }
123
124
125 string const GuiClipboard::getAsLyX() const
126 {
127         LYXERR(Debug::CLIPBOARD, "GuiClipboard::getAsLyX(): `");
128         // We don't convert encodings here since the encoding of the
129         // clipboard contents is specified in the data itself
130         if (cache_.hasFormat(lyxMimeType())) {
131                 // data from ourself or some other LyX instance
132                 QByteArray const ar = cache_.data(lyxMimeType());
133                 string const s(ar.data(), ar.count());
134                 LYXERR(Debug::CLIPBOARD, s << "'");
135                 return s;
136         }
137         LYXERR(Debug::CLIPBOARD, "'");
138         return string();
139 }
140
141
142 FileName GuiClipboard::getPastedGraphicsFileName(Cursor const & cur,
143         Clipboard::GraphicsType & type) const
144 {
145         // create file dialog filter according to the existing types in the clipboard
146         vector<Clipboard::GraphicsType> types;
147         if (hasGraphicsContents(Clipboard::EmfGraphicsType))
148                 types.push_back(Clipboard::EmfGraphicsType);
149         if (hasGraphicsContents(Clipboard::WmfGraphicsType))
150                 types.push_back(Clipboard::WmfGraphicsType);
151         if (hasGraphicsContents(Clipboard::LinkBackGraphicsType))
152                 types.push_back(Clipboard::LinkBackGraphicsType);
153         if (hasGraphicsContents(Clipboard::PdfGraphicsType))
154                 types.push_back(Clipboard::PdfGraphicsType);
155         if (hasGraphicsContents(Clipboard::PngGraphicsType))
156                 types.push_back(Clipboard::PngGraphicsType);
157         if (hasGraphicsContents(Clipboard::JpegGraphicsType))
158                 types.push_back(Clipboard::JpegGraphicsType);
159
160         LASSERT(!types.empty(), return FileName());
161
162         // select preferred type if AnyGraphicsType was passed
163         if (type == Clipboard::AnyGraphicsType)
164                 type = types.front();
165
166         // which extension?
167         map<Clipboard::GraphicsType, string> extensions;
168         map<Clipboard::GraphicsType, docstring> typeNames;
169
170         extensions[Clipboard::EmfGraphicsType] = "emf";
171         extensions[Clipboard::WmfGraphicsType] = "wmf";
172         extensions[Clipboard::LinkBackGraphicsType] = "linkback";
173         extensions[Clipboard::PdfGraphicsType] = "pdf";
174         extensions[Clipboard::PngGraphicsType] = "png";
175         extensions[Clipboard::JpegGraphicsType] = "jpeg";
176
177         typeNames[Clipboard::EmfGraphicsType] = _("Enhanced Metafile");
178         typeNames[Clipboard::WmfGraphicsType] = _("Windows Metafile");
179         typeNames[Clipboard::LinkBackGraphicsType] = _("LinkBack PDF");
180         typeNames[Clipboard::PdfGraphicsType] = _("PDF");
181         typeNames[Clipboard::PngGraphicsType] = _("PNG");
182         typeNames[Clipboard::JpegGraphicsType] = _("JPEG");
183
184         // find unused filename with primary extension
185         string document_path = cur.buffer()->fileName().onlyPath().absFileName();
186         unsigned newfile_number = 0;
187         FileName filename;
188         do {
189                 ++newfile_number;
190                 filename = FileName(addName(document_path,
191                         to_utf8(_("pasted"))
192                         + convert<string>(newfile_number) + "."
193                         + extensions[type]));
194         } while (filename.isReadableFile());
195
196         while (true) {
197                 // create file type filter, putting the preferred on to the front
198                 QStringList filter;
199                 for (size_t i = 0; i != types.size(); ++i) {
200                         docstring s = bformat(_("%1$s Files"), typeNames[types[i]])
201                                 + " (*." + from_ascii(extensions[types[i]]) + ")";
202                         if (types[i] == type)
203                                 filter.prepend(toqstr(s));
204                         else
205                                 filter.append(toqstr(s));
206                 }
207                 filter = fileFilters(filter.join(";;"));
208
209                 // show save dialog for the graphic
210                 FileDialog dlg(qt_("Choose a filename to save the pasted graphic as"));
211                 FileDialog::Result result =
212                 dlg.save(toqstr(filename.onlyPath().absFileName()), filter,
213                          toqstr(filename.onlyFileName()));
214
215                 if (result.first == FileDialog::Later)
216                         return FileName();
217
218                 string newFilename = fromqstr(result.second);
219                 if (newFilename.empty()) {
220                         cur.bv().message(_("Canceled."));
221                         return FileName();
222                 }
223                 filename.set(newFilename);
224
225                 // check the extension (the user could have changed it)
226                 if (!suffixIs(ascii_lowercase(filename.absFileName()),
227                               "." + extensions[type])) {
228                         // the user changed the extension. Check if the type is available
229                         size_t i;
230                         for (i = 1; i != types.size(); ++i) {
231                                 if (suffixIs(ascii_lowercase(filename.absFileName()),
232                                              "." + extensions[types[i]])) {
233                                         type = types[i];
234                                         break;
235                                 }
236                         }
237
238                         // invalid extension found, or none at all. In the latter
239                         // case set the default extensions.
240                         if (i == types.size()
241                             && filename.onlyFileName().find('.') == string::npos) {
242                                 filename.changeExtension("." + extensions[type]);
243                         }
244                 }
245
246                 // check whether the file exists and warn the user
247                 if (!filename.exists())
248                         break;
249                 int ret = frontend::Alert::prompt(
250                         _("Overwrite external file?"),
251                         bformat(_("File %1$s already exists, do you want to overwrite it?"),
252                         from_utf8(filename.absFileName())), 1, 1, _("&Overwrite"), _("&Cancel"));
253                 if (ret == 0)
254                         // overwrite, hence break the dialog loop
255                         break;
256
257                 // not overwrite, hence show the dialog again (i.e. loop)
258         }
259
260         return filename;
261 }
262
263
264 FileName GuiClipboard::getAsGraphics(Cursor const & cur, GraphicsType type) const
265 {
266         // get the filename from the user
267         FileName filename = getPastedGraphicsFileName(cur, type);
268         if (filename.empty())
269                 return FileName();
270
271         // handle image cases first
272         if (type == PngGraphicsType || type == JpegGraphicsType) {
273                 // get image from QImage from clipboard
274                 QImage image = qApp->clipboard()->image();
275                 if (image.isNull()) {
276                         LYXERR(Debug::CLIPBOARD, "No image in clipboard");
277                         return FileName();
278                 }
279
280                 // convert into graphics format
281                 QByteArray ar;
282                 QBuffer buffer(&ar);
283                 buffer.open(QIODevice::WriteOnly);
284                 if (type == PngGraphicsType)
285                         image.save(toqstr(filename.absFileName()), "PNG");
286                 else if (type == JpegGraphicsType)
287                         image.save(toqstr(filename.absFileName()), "JPEG");
288                 else
289                         LATTEST(false);
290
291                 return filename;
292         }
293
294         // get mime for type
295         QString mime;
296         switch (type) {
297         case PdfGraphicsType: mime = pdfMimeType(); break;
298         case LinkBackGraphicsType: mime = pdfMimeType(); break;
299         case EmfGraphicsType: mime = emfMimeType(); break;
300         case WmfGraphicsType: mime = wmfMimeType(); break;
301         default: LASSERT(false, return FileName());
302         }
303
304         // get data
305         if (!cache_.hasFormat(mime))
306                 return FileName();
307         // data from ourself or some other LyX instance
308         QByteArray const ar = cache_.data(mime);
309         LYXERR(Debug::CLIPBOARD, "Getting from clipboard: mime = " << mime.constData()
310                << "length = " << ar.count());
311
312         QFile f(toqstr(filename.absFileName()));
313         if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
314                 LYXERR(Debug::CLIPBOARD, "Error opening file "
315                        << filename.absFileName() << " for writing");
316                 return FileName();
317         }
318
319         // write the (LinkBack) PDF data
320         f.write(ar);
321         if (type == LinkBackGraphicsType) {
322 #ifdef Q_OS_MAC
323                 void const * linkBackData;
324                 unsigned linkBackLen;
325                 getLinkBackData(&linkBackData, &linkBackLen);
326                 f.write((char *)linkBackData, linkBackLen);
327                 quint32 pdfLen = ar.size();
328                 QDataStream ds(&f);
329                 ds << pdfLen; // big endian by default
330 #else
331                 // only non-Mac this should never happen
332                 LATTEST(false);
333 #endif // Q_OS_MAC
334         }
335
336         f.close();
337         return filename;
338 }
339
340
341 namespace {
342 /**
343  * Tidy up a HTML chunk coming from the clipboard.
344  * This is needed since different applications put different kinds of HTML
345  * on the clipboard:
346  * - With or without the <?xml> tag
347  * - With or without the <!DOCTYPE> tag
348  * - With or without the <html> tag
349  * - With or without the <body> tag
350  * - With or without the <p> tag
351  * Since we are going to write a HTML file for external converters we need
352  * to ensure that it is a well formed HTML file, including all the mentioned tags.
353  */
354 QString tidyHtml(QString const & input)
355 {
356         // Misuse QTextDocument to cleanup the HTML.
357         // As a side effect, all visual markup like <tt> is converted to CSS,
358         // which is ignored by gnuhtml2latex.
359         // While this may be seen as a bug by some people it is actually a
360         // good thing, since we do import structure, but ignore all visual
361         // clutter.
362         QTextDocument converter;
363         converter.setHtml(input);
364         return converter.toHtml("utf-8");
365 }
366 } // namespace
367
368
369 docstring const GuiClipboard::getAsText(TextType type) const
370 {
371         // text data from other applications
372         if ((type == AnyTextType || type == LyXOrPlainTextType) && hasTextContents(LyXTextType))
373                 type = LyXTextType;
374         if (type == AnyTextType && hasTextContents(LaTeXTextType))
375                 type = LaTeXTextType;
376         if (type == AnyTextType && hasTextContents(HtmlTextType))
377                 type = HtmlTextType;
378         QString str;
379         switch (type) {
380         case LyXTextType:
381                 // must not convert to docstring, since file can contain
382                 // mixed encodings (use getAsLyX() instead)
383                 break;
384         case AnyTextType:
385         case LyXOrPlainTextType:
386         case PlainTextType:
387                 str = qApp->clipboard()->text(QClipboard::Clipboard)
388                                 .normalized(QString::NormalizationForm_C);
389                 break;
390         case LaTeXTextType: {
391                 QMimeData const * source =
392                         qApp->clipboard()->mimeData(QClipboard::Clipboard);
393                 if (source) {
394                         // First try LaTeX, then TeX (we do not distinguish
395                         // for clipboard purposes)
396                         if (source->hasFormat(latexMimeType())) {
397                                 str = source->data(latexMimeType());
398                                 str = str.normalized(QString::NormalizationForm_C);
399                         } else if (source->hasFormat(texMimeType())) {
400                                 str = source->data(texMimeType());
401                                 str = str.normalized(QString::NormalizationForm_C);
402                         }
403                 }
404                 break;
405         }
406         case HtmlTextType: {
407                 QString subtype = "html";
408                 str = qApp->clipboard()->text(subtype, QClipboard::Clipboard)
409                                 .normalized(QString::NormalizationForm_C);
410                 str = tidyHtml(str);
411                 break;
412         }
413         }
414         LYXERR(Debug::CLIPBOARD, "GuiClipboard::getAsText(" << type << "): `" << str << "'");
415         if (str.isNull())
416                 return docstring();
417
418         return internalLineEnding(str);
419 }
420
421
422 void GuiClipboard::put(string const & text) const
423 {
424         qApp->clipboard()->setText(toqstr(text));
425 }
426
427
428 void GuiClipboard::put(string const & lyx, docstring const & html, docstring const & text)
429 {
430         LYXERR(Debug::CLIPBOARD, "GuiClipboard::put(`" << lyx << "' `"
431                               << to_utf8(html) << "' `" << to_utf8(text) << "')");
432         // We don't convert the encoding of lyx since the encoding of the
433         // clipboard contents is specified in the data itself
434         QMimeData * data = new QMimeData;
435         if (!lyx.empty()) {
436                 QByteArray const qlyx(lyx.c_str(), lyx.size());
437                 data->setData(lyxMimeType(), qlyx);
438                 // If the OS has not the concept of clipboard ownership,
439                 // we recognize internal data through its checksum.
440                 if (!hasInternal())
441                         checksum = support::checksum(lyx);
442         }
443         // Don't test for text.empty() since we want to be able to clear the
444         // clipboard.
445         QString const qtext = toqstr(text);
446         data->setText(qtext);
447         QString const qhtml = toqstr(html);
448         data->setHtml(qhtml);
449         qApp->clipboard()->setMimeData(data, QClipboard::Clipboard);
450 }
451
452
453 bool GuiClipboard::hasTextContents(Clipboard::TextType type) const
454 {
455         switch (type) {
456         case AnyTextType:
457                 return cache_.hasFormat(lyxMimeType()) || cache_.hasText() ||
458                        cache_.hasHtml() || cache_.hasFormat(latexMimeType()) ||
459                        cache_.hasFormat(texMimeType());
460         case LyXOrPlainTextType:
461                 return cache_.hasFormat(lyxMimeType()) || cache_.hasText();
462         case LyXTextType:
463                 return cache_.hasFormat(lyxMimeType());
464         case PlainTextType:
465                 return cache_.hasText();
466         case HtmlTextType:
467                 return cache_.hasHtml();
468         case LaTeXTextType:
469                 return cache_.hasFormat(latexMimeType()) ||
470                        cache_.hasFormat(texMimeType());
471         }
472         // shut up compiler
473         return false;
474 }
475
476
477 bool GuiClipboard::hasGraphicsContents(Clipboard::GraphicsType type) const
478 {
479         if (type == AnyGraphicsType) {
480                 return hasGraphicsContents(PdfGraphicsType)
481                         || hasGraphicsContents(PngGraphicsType)
482                         || hasGraphicsContents(JpegGraphicsType)
483                         || hasGraphicsContents(EmfGraphicsType)
484                         || hasGraphicsContents(WmfGraphicsType)
485                         || hasGraphicsContents(LinkBackGraphicsType);
486         }
487
488         // handle image cases first
489         if (type == PngGraphicsType || type == JpegGraphicsType)
490                 return cache_.hasImage();
491
492         // handle LinkBack for Mac
493         if (type == LinkBackGraphicsType)
494 #ifdef Q_OS_MAC
495                 return isLinkBackDataInPasteboard();
496 #else
497                 return false;
498 #endif // Q_OS_MAC
499
500         // get mime data
501         QStringList const & formats = cache_.formats();
502         LYXERR(Debug::CLIPBOARD, "We found " << formats.size() << " formats");
503         for (int i = 0; i < formats.size(); ++i)
504                 LYXERR(Debug::CLIPBOARD, "Found format " << formats[i]);
505
506         // compute mime for type
507         QString mime;
508         switch (type) {
509         case EmfGraphicsType: mime = emfMimeType(); break;
510         case WmfGraphicsType: mime = wmfMimeType(); break;
511         case PdfGraphicsType: mime = pdfMimeType(); break;
512         default: LASSERT(false, return false);
513         }
514
515         return cache_.hasFormat(mime);
516 }
517
518
519 bool GuiClipboard::isInternal() const
520 {
521         if (!hasTextContents(LyXTextType))
522                 return false;
523
524         // ownsClipboard() is also true for stuff coming from dialogs, e.g.
525         // the preamble dialog. This does only work on X11 and Windows, since
526         // ownsClipboard() is hardwired to return false on OS X.
527         if (hasInternal())
528                 return qApp->clipboard()->ownsClipboard();
529
530         // We are running on OS X: Check whether clipboard data is from
531         // ourself by comparing its checksum with the stored one.
532         QByteArray const ar = cache_.data(lyxMimeType());
533         string const data(ar.data(), ar.count());
534         return checksum == static_cast<std::uint32_t>(support::checksum(data));
535 }
536
537
538 bool GuiClipboard::hasInternal() const
539 {
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.
545 #ifndef Q_OS_MAC
546         return true;
547 #else
548         return false;
549 #endif
550 }
551
552
553 void GuiClipboard::setFindBuffer(docstring const & text)
554 {
555         LYXERR(Debug::CLIPBOARD, "new findbuffer: " << text);
556         Clipboard::setFindBuffer(text);
557         qApp->clipboard()->setText(toqstr(text), QClipboard::FindBuffer);
558 }
559
560
561 void GuiClipboard::on_findChanged()
562 {
563         Clipboard::setFindBuffer(from_utf8(fromqstr(
564                 qApp->clipboard()->text(QClipboard::FindBuffer))));
565 }
566
567
568 void GuiClipboard::on_dataChanged()
569 {
570         update();
571 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
572         // Retry on Windows (#10109)
573         if (cache_.formats().count() == 0) {
574                 QTimer::singleShot(100, this, SLOT(update()));
575         }
576 #endif
577 }
578
579 void GuiClipboard::update()
580 {
581         //Note: we do not really need to run cache_.update() unless the
582         //data has been changed *and* the GuiClipboard has been queried.
583         //However if run cache_.update() the moment a process grabs the
584         //clipboard, the process holding the clipboard presumably won't
585         //yet be frozen, and so we won't need to wait 5 seconds for Qt
586         //to time-out waiting for the clipboard.
587         cache_.update();
588         QStringList l = cache_.formats();
589         LYXERR(Debug::CLIPBOARD, "Qt Clipboard changed. We found the following mime types:");
590         for (int i = 0; i < l.count(); i++)
591                 LYXERR(Debug::CLIPBOARD, l.value(i));
592
593         plaintext_clipboard_empty_ = qApp->clipboard()->
594                 text(QClipboard::Clipboard).isEmpty();
595
596         has_text_contents_ = hasTextContents();
597         has_graphics_contents_ = hasGraphicsContents();
598 }
599
600
601 bool GuiClipboard::empty() const
602 {
603         // We need to check both the plaintext and the LyX version of the
604         // clipboard. The plaintext version is empty if the LyX version
605         // contains only one inset, and the LyX version is empty if the
606         // clipboard does not come from LyX.
607         if (!plaintext_clipboard_empty_)
608                 return false;
609         return !has_text_contents_ && !has_graphics_contents_;
610 }
611
612 } // namespace frontend
613 } // namespace lyx
614
615 #include "moc_GuiClipboard.cpp"