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>
52 using namespace lyx::support;
59 static QMimeData const * read_clipboard()
61 LYXERR(Debug::ACTION, "Getting Clipboard");
62 QMimeData const * source =
63 qApp->clipboard()->mimeData(QClipboard::Clipboard);
65 LYXERR0("0 bytes (no QMimeData)");
66 return new QMimeData();
68 // It appears that doing IO between getting a mimeData object
69 // and using it can cause a crash (maybe Qt used IO
70 // as an excuse to free() it? Anyway let's not introduce
71 // any new IO here, so e.g. leave the following line commented.
72 // lyxerr << "Got Clipboard (" << (long) source << ")\n" ;
77 void CacheMimeData::update()
79 time_t const start_time = current_time();
80 LYXERR(Debug::ACTION, "Creating CacheMimeData object");
81 cached_formats_ = read_clipboard()->formats();
83 // Qt times out after 5 seconds if it does not recieve a response.
84 if (current_time() - start_time > 3) {
85 LYXERR0("No timely response from clipboard, perhaps process "
86 << "holding clipboard is frozen?");
91 QByteArray CacheMimeData::data(QString const & mimeType) const
93 return read_clipboard()->data(mimeType);
97 QString const lyxMimeType(){ return "application/x-lyx"; }
98 QString const pdfMimeType(){ return "application/pdf"; }
99 QString const emfMimeType(){ return "image/x-emf"; }
100 QString const wmfMimeType(){ return "image/x-wmf"; }
103 GuiClipboard::GuiClipboard()
105 connect(qApp->clipboard(), SIGNAL(dataChanged()),
106 this, SLOT(on_dataChanged()));
107 // initialize clipboard status.
112 string const GuiClipboard::getAsLyX() const
114 LYXERR(Debug::ACTION, "GuiClipboard::getAsLyX(): `");
115 // We don't convert encodings here since the encoding of the
116 // clipboard contents is specified in the data itself
117 if (cache_.hasFormat(lyxMimeType())) {
118 // data from ourself or some other LyX instance
119 QByteArray const ar = cache_.data(lyxMimeType());
120 string const s(ar.data(), ar.count());
121 LYXERR(Debug::ACTION, s << "'");
124 LYXERR(Debug::ACTION, "'");
129 FileName GuiClipboard::getPastedGraphicsFileName(Cursor const & cur,
130 Clipboard::GraphicsType & type) const
132 // create file dialog filter according to the existing types in the clipboard
133 vector<Clipboard::GraphicsType> types;
134 if (hasGraphicsContents(Clipboard::EmfGraphicsType))
135 types.push_back(Clipboard::EmfGraphicsType);
136 if (hasGraphicsContents(Clipboard::WmfGraphicsType))
137 types.push_back(Clipboard::WmfGraphicsType);
138 if (hasGraphicsContents(Clipboard::LinkBackGraphicsType))
139 types.push_back(Clipboard::LinkBackGraphicsType);
140 if (hasGraphicsContents(Clipboard::PdfGraphicsType))
141 types.push_back(Clipboard::PdfGraphicsType);
142 if (hasGraphicsContents(Clipboard::PngGraphicsType))
143 types.push_back(Clipboard::PngGraphicsType);
144 if (hasGraphicsContents(Clipboard::JpegGraphicsType))
145 types.push_back(Clipboard::JpegGraphicsType);
147 LASSERT(!types.empty(), /**/);
149 // select prefered type if AnyGraphicsType was passed
150 if (type == Clipboard::AnyGraphicsType)
151 type = types.front();
154 map<Clipboard::GraphicsType, string> extensions;
155 map<Clipboard::GraphicsType, docstring> typeNames;
157 extensions[Clipboard::EmfGraphicsType] = "emf";
158 extensions[Clipboard::WmfGraphicsType] = "wmf";
159 extensions[Clipboard::LinkBackGraphicsType] = "linkback";
160 extensions[Clipboard::PdfGraphicsType] = "pdf";
161 extensions[Clipboard::PngGraphicsType] = "png";
162 extensions[Clipboard::JpegGraphicsType] = "jpeg";
164 typeNames[Clipboard::EmfGraphicsType] = _("Enhanced Metafile");
165 typeNames[Clipboard::WmfGraphicsType] = _("Windows Metafile");
166 typeNames[Clipboard::LinkBackGraphicsType] = _("LinkBack PDF");
167 typeNames[Clipboard::PdfGraphicsType] = _("PDF");
168 typeNames[Clipboard::PngGraphicsType] = _("PNG");
169 typeNames[Clipboard::JpegGraphicsType] = _("JPEG");
171 // find unused filename with primary extension
172 string document_path = cur.buffer()->fileName().onlyPath().absFileName();
173 unsigned newfile_number = 0;
177 filename = FileName(addName(document_path,
179 + convert<string>(newfile_number) + "."
180 + extensions[type]));
181 } while (filename.isReadableFile());
184 // create file type filter, putting the prefered on to the front
186 for (size_t i = 0; i != types.size(); ++i) {
187 docstring s = bformat(_("%1$s Files"), typeNames[types[i]])
188 + " (*." + from_ascii(extensions[types[i]]) + ")";
189 if (types[i] == type)
190 filter.prepend(toqstr(s));
192 filter.append(toqstr(s));
194 filter = fileFilters(filter.join(";;"));
196 // show save dialog for the graphic
197 FileDialog dlg(qt_("Choose a filename to save the pasted graphic as"));
198 FileDialog::Result result =
199 dlg.save(toqstr(filename.onlyPath().absFileName()), filter,
200 toqstr(filename.onlyFileName()));
202 if (result.first == FileDialog::Later)
205 string newFilename = fromqstr(result.second);
206 if (newFilename.empty()) {
207 cur.bv().message(_("Canceled."));
210 filename.set(newFilename);
212 // check the extension (the user could have changed it)
213 if (!suffixIs(ascii_lowercase(filename.absFileName()),
214 "." + extensions[type])) {
215 // the user changed the extension. Check if the type is available
217 for (i = 1; i != types.size(); ++i) {
218 if (suffixIs(ascii_lowercase(filename.absFileName()),
219 "." + extensions[types[i]])) {
225 // invalid extension found, or none at all. In the latter
226 // case set the default extensions.
227 if (i == types.size()
228 && filename.onlyFileName().find('.') == string::npos) {
229 filename.changeExtension("." + extensions[type]);
233 // check whether the file exists and warn the user
234 if (!filename.exists())
236 int ret = frontend::Alert::prompt(
237 _("Overwrite external file?"),
238 bformat(_("File %1$s already exists, do you want to overwrite it?"),
239 from_utf8(filename.absFileName())), 1, 1, _("&Overwrite"), _("&Cancel"));
241 // overwrite, hence break the dialog loop
244 // not overwrite, hence show the dialog again (i.e. loop)
251 FileName GuiClipboard::getAsGraphics(Cursor const & cur, GraphicsType type) const
253 // get the filename from the user
254 FileName filename = getPastedGraphicsFileName(cur, type);
255 if (filename.empty())
258 // handle image cases first
259 if (type == PngGraphicsType || type == JpegGraphicsType) {
260 // get image from QImage from clipboard
261 QImage image = qApp->clipboard()->image();
262 if (image.isNull()) {
263 LYXERR(Debug::ACTION, "No image in clipboard");
267 // convert into graphics format
270 buffer.open(QIODevice::WriteOnly);
271 if (type == PngGraphicsType)
272 image.save(toqstr(filename.absFileName()), "PNG");
273 else if (type == JpegGraphicsType)
274 image.save(toqstr(filename.absFileName()), "JPEG");
276 LASSERT(false, /**/);
284 case PdfGraphicsType: mime = pdfMimeType(); break;
285 case LinkBackGraphicsType: mime = pdfMimeType(); break;
286 case EmfGraphicsType: mime = emfMimeType(); break;
287 case WmfGraphicsType: mime = wmfMimeType(); break;
288 default: LASSERT(false, /**/);
292 if (!cache_.hasFormat(mime))
294 // data from ourself or some other LyX instance
295 QByteArray const ar = cache_.data(mime);
296 LYXERR(Debug::ACTION, "Getting from clipboard: mime = " << mime.data()
297 << "length = " << ar.count());
299 QFile f(toqstr(filename.absFileName()));
300 if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
301 LYXERR(Debug::ACTION, "Error opening file "
302 << filename.absFileName() << " for writing");
306 // write the (LinkBack) PDF data
308 if (type == LinkBackGraphicsType) {
310 void const * linkBackData;
311 unsigned linkBackLen;
312 getLinkBackData(&linkBackData, &linkBackLen);
313 f.write((char *)linkBackData, linkBackLen);
314 quint32 pdfLen = ar.size();
316 ds << pdfLen; // big endian by default
318 // only non-Mac this should never happen
319 LASSERT(false, /**/);
328 docstring const GuiClipboard::getAsText() const
330 // text data from other applications
331 QString const str = qApp->clipboard()->text(QClipboard::Clipboard)
332 .normalized(QString::NormalizationForm_C);
333 LYXERR(Debug::ACTION, "GuiClipboard::getAsText(): `" << str << "'");
337 return internalLineEnding(str);
341 void GuiClipboard::put(string const & lyx, docstring const & text)
343 LYXERR(Debug::ACTION, "GuiClipboard::put(`" << lyx << "' `"
344 << to_utf8(text) << "')");
345 // We don't convert the encoding of lyx since the encoding of the
346 // clipboard contents is specified in the data itself
347 QMimeData * data = new QMimeData;
349 QByteArray const qlyx(lyx.c_str(), lyx.size());
350 data->setData(lyxMimeType(), qlyx);
352 // Don't test for text.empty() since we want to be able to clear the
354 QString const qtext = toqstr(text);
355 data->setText(qtext);
356 qApp->clipboard()->setMimeData(data, QClipboard::Clipboard);
360 bool GuiClipboard::hasLyXContents() const
362 return cache_.hasFormat(lyxMimeType());
366 bool GuiClipboard::hasTextContents() const
368 return cache_.hasText();
372 bool GuiClipboard::hasGraphicsContents(Clipboard::GraphicsType type) const
374 if (type == AnyGraphicsType) {
375 return hasGraphicsContents(PdfGraphicsType)
376 || hasGraphicsContents(PngGraphicsType)
377 || hasGraphicsContents(JpegGraphicsType)
378 || hasGraphicsContents(EmfGraphicsType)
379 || hasGraphicsContents(WmfGraphicsType)
380 || hasGraphicsContents(LinkBackGraphicsType);
383 // handle image cases first
384 if (type == PngGraphicsType || type == JpegGraphicsType)
385 return cache_.hasImage();
387 // handle LinkBack for Mac
388 if (type == LinkBackGraphicsType)
390 return isLinkBackDataInPasteboard();
396 QStringList const & formats = cache_.formats();
397 LYXERR(Debug::ACTION, "We found " << formats.size() << " formats");
398 for (int i = 0; i < formats.size(); ++i)
399 LYXERR(Debug::ACTION, "Found format " << formats[i]);
401 // compute mime for type
404 case EmfGraphicsType: mime = emfMimeType(); break;
405 case WmfGraphicsType: mime = wmfMimeType(); break;
406 case PdfGraphicsType: mime = pdfMimeType(); break;
407 default: LASSERT(false, /**/);
410 return cache_.hasFormat(mime);
414 bool GuiClipboard::isInternal() const
416 // ownsClipboard() is also true for stuff coming from dialogs, e.g.
417 // the preamble dialog
418 // FIXME: This does only work on X11, since ownsClipboard() is
419 // hardwired to return false on Windows and OS X.
420 return qApp->clipboard()->ownsClipboard() && hasLyXContents();
424 bool GuiClipboard::hasInternal() const
426 // Windows and Mac OS X does not have the concept of ownership;
427 // the clipboard is a fully global resource so all applications
428 // are notified of changes.
429 #if (defined(Q_WS_X11))
437 void GuiClipboard::on_dataChanged()
439 //Note: we do not really need to run cache_.update() unless the
440 //data has been changed *and* the GuiClipboard has been queried.
441 //However if run cache_.update() the moment a process grabs the
442 //clipboard, the process holding the clipboard presumably won't
443 //yet be frozen, and so we won't need to wait 5 seconds for Qt
444 //to time-out waiting for the clipboard.
446 QStringList l = cache_.formats();
447 LYXERR(Debug::ACTION, "Qt Clipboard changed. We found the following mime types:");
448 for (int i = 0; i < l.count(); i++)
449 LYXERR(Debug::ACTION, l.value(i));
451 text_clipboard_empty_ = qApp->clipboard()->
452 text(QClipboard::Clipboard).isEmpty();
454 has_lyx_contents_ = hasLyXContents();
455 has_graphics_contents_ = hasGraphicsContents();
459 bool GuiClipboard::empty() const
461 // We need to check both the plaintext and the LyX version of the
462 // clipboard. The plaintext version is empty if the LyX version
463 // contains only one inset, and the LyX version is empty if the
464 // clipboard does not come from LyX.
465 if (!text_clipboard_empty_)
467 return !has_lyx_contents_ && !has_graphics_contents_;
470 } // namespace frontend
473 #include "moc_GuiClipboard.cpp"