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>
53 using namespace lyx::support;
60 static QMimeData const * read_clipboard()
62 LYXERR(Debug::ACTION, "Getting Clipboard");
63 QMimeData const * source =
64 qApp->clipboard()->mimeData(QClipboard::Clipboard);
66 LYXERR0("0 bytes (no QMimeData)");
67 return new QMimeData();
69 // It appears that doing IO between getting a mimeData object
70 // and using it can cause a crash (maybe Qt used IO
71 // as an excuse to free() it? Anyway let's not introduce
72 // any new IO here, so e.g. leave the following line commented.
73 // lyxerr << "Got Clipboard (" << (long) source << ")\n" ;
78 void CacheMimeData::update()
80 time_t const start_time = current_time();
81 LYXERR(Debug::ACTION, "Creating CacheMimeData object");
82 cached_formats_ = read_clipboard()->formats();
84 // Qt times out after 5 seconds if it does not recieve a response.
85 if (current_time() - start_time > 3) {
86 LYXERR0("No timely response from clipboard, perhaps process "
87 << "holding clipboard is frozen?");
92 QByteArray CacheMimeData::data(QString const & mimeType) const
94 return read_clipboard()->data(mimeType);
98 QString const lyxMimeType(){ return "application/x-lyx"; }
99 QString const pdfMimeType(){ return "application/pdf"; }
100 QString const emfMimeType(){ return "image/x-emf"; }
101 QString const wmfMimeType(){ return "image/x-wmf"; }
104 GuiClipboard::GuiClipboard()
106 connect(qApp->clipboard(), SIGNAL(dataChanged()),
107 this, SLOT(on_dataChanged()));
108 // initialize clipboard status.
113 string const GuiClipboard::getAsLyX() const
115 LYXERR(Debug::ACTION, "GuiClipboard::getAsLyX(): `");
116 // We don't convert encodings here since the encoding of the
117 // clipboard contents is specified in the data itself
118 if (cache_.hasFormat(lyxMimeType())) {
119 // data from ourself or some other LyX instance
120 QByteArray const ar = cache_.data(lyxMimeType());
121 string const s(ar.data(), ar.count());
122 LYXERR(Debug::ACTION, s << "'");
125 LYXERR(Debug::ACTION, "'");
130 FileName GuiClipboard::getPastedGraphicsFileName(Cursor const & cur,
131 Clipboard::GraphicsType & type) const
133 // create file dialog filter according to the existing types in the clipboard
134 vector<Clipboard::GraphicsType> types;
135 if (hasGraphicsContents(Clipboard::EmfGraphicsType))
136 types.push_back(Clipboard::EmfGraphicsType);
137 if (hasGraphicsContents(Clipboard::WmfGraphicsType))
138 types.push_back(Clipboard::WmfGraphicsType);
139 if (hasGraphicsContents(Clipboard::LinkBackGraphicsType))
140 types.push_back(Clipboard::LinkBackGraphicsType);
141 if (hasGraphicsContents(Clipboard::PdfGraphicsType))
142 types.push_back(Clipboard::PdfGraphicsType);
143 if (hasGraphicsContents(Clipboard::PngGraphicsType))
144 types.push_back(Clipboard::PngGraphicsType);
145 if (hasGraphicsContents(Clipboard::JpegGraphicsType))
146 types.push_back(Clipboard::JpegGraphicsType);
148 LASSERT(!types.empty(), /**/);
150 // select prefered type if AnyGraphicsType was passed
151 if (type == Clipboard::AnyGraphicsType)
152 type = types.front();
155 map<Clipboard::GraphicsType, string> extensions;
156 map<Clipboard::GraphicsType, docstring> typeNames;
158 extensions[Clipboard::EmfGraphicsType] = "emf";
159 extensions[Clipboard::WmfGraphicsType] = "wmf";
160 extensions[Clipboard::LinkBackGraphicsType] = "linkback";
161 extensions[Clipboard::PdfGraphicsType] = "pdf";
162 extensions[Clipboard::PngGraphicsType] = "png";
163 extensions[Clipboard::JpegGraphicsType] = "jpeg";
165 typeNames[Clipboard::EmfGraphicsType] = _("Enhanced Metafile");
166 typeNames[Clipboard::WmfGraphicsType] = _("Windows Metafile");
167 typeNames[Clipboard::LinkBackGraphicsType] = _("LinkBack PDF");
168 typeNames[Clipboard::PdfGraphicsType] = _("PDF");
169 typeNames[Clipboard::PngGraphicsType] = _("PNG");
170 typeNames[Clipboard::JpegGraphicsType] = _("JPEG");
172 // find unused filename with primary extension
173 string document_path = cur.buffer()->fileName().onlyPath().absFileName();
174 unsigned newfile_number = 0;
178 filename = FileName(addName(document_path,
180 + convert<string>(newfile_number) + "."
181 + extensions[type]));
182 } while (filename.isReadableFile());
185 // create file type filter, putting the prefered on to the front
187 for (size_t i = 0; i != types.size(); ++i) {
188 docstring s = bformat(_("%1$s Files"), typeNames[types[i]])
189 + " (*." + from_ascii(extensions[types[i]]) + ")";
190 if (types[i] == type)
191 filter.prepend(toqstr(s));
193 filter.append(toqstr(s));
195 filter = fileFilters(filter.join(";;"));
197 // show save dialog for the graphic
198 FileDialog dlg(qt_("Choose a filename to save the pasted graphic as"));
199 FileDialog::Result result =
200 dlg.save(toqstr(filename.onlyPath().absFileName()), filter,
201 toqstr(filename.onlyFileName()));
203 if (result.first == FileDialog::Later)
206 string newFilename = fromqstr(result.second);
207 if (newFilename.empty()) {
208 cur.bv().message(_("Canceled."));
211 filename.set(newFilename);
213 // check the extension (the user could have changed it)
214 if (!suffixIs(ascii_lowercase(filename.absFileName()),
215 "." + extensions[type])) {
216 // the user changed the extension. Check if the type is available
218 for (i = 1; i != types.size(); ++i) {
219 if (suffixIs(ascii_lowercase(filename.absFileName()),
220 "." + extensions[types[i]])) {
226 // invalid extension found, or none at all. In the latter
227 // case set the default extensions.
228 if (i == types.size()
229 && filename.onlyFileName().find('.') == string::npos) {
230 filename.changeExtension("." + extensions[type]);
234 // check whether the file exists and warn the user
235 if (!filename.exists())
237 int ret = frontend::Alert::prompt(
238 _("Overwrite external file?"),
239 bformat(_("File %1$s already exists, do you want to overwrite it?"),
240 from_utf8(filename.absFileName())), 1, 1, _("&Overwrite"), _("&Cancel"));
242 // overwrite, hence break the dialog loop
245 // not overwrite, hence show the dialog again (i.e. loop)
252 FileName GuiClipboard::getAsGraphics(Cursor const & cur, GraphicsType type) const
254 // get the filename from the user
255 FileName filename = getPastedGraphicsFileName(cur, type);
256 if (filename.empty())
259 // handle image cases first
260 if (type == PngGraphicsType || type == JpegGraphicsType) {
261 // get image from QImage from clipboard
262 QImage image = qApp->clipboard()->image();
263 if (image.isNull()) {
264 LYXERR(Debug::ACTION, "No image in clipboard");
268 // convert into graphics format
271 buffer.open(QIODevice::WriteOnly);
272 if (type == PngGraphicsType)
273 image.save(toqstr(filename.absFileName()), "PNG");
274 else if (type == JpegGraphicsType)
275 image.save(toqstr(filename.absFileName()), "JPEG");
277 LASSERT(false, /**/);
285 case PdfGraphicsType: mime = pdfMimeType(); break;
286 case LinkBackGraphicsType: mime = pdfMimeType(); break;
287 case EmfGraphicsType: mime = emfMimeType(); break;
288 case WmfGraphicsType: mime = wmfMimeType(); break;
289 default: LASSERT(false, /**/);
293 if (!cache_.hasFormat(mime))
295 // data from ourself or some other LyX instance
296 QByteArray const ar = cache_.data(mime);
297 LYXERR(Debug::ACTION, "Getting from clipboard: mime = " << mime.data()
298 << "length = " << ar.count());
300 QFile f(toqstr(filename.absFileName()));
301 if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
302 LYXERR(Debug::ACTION, "Error opening file "
303 << filename.absFileName() << " for writing");
307 // write the (LinkBack) PDF data
309 if (type == LinkBackGraphicsType) {
311 void const * linkBackData;
312 unsigned linkBackLen;
313 getLinkBackData(&linkBackData, &linkBackLen);
314 f.write((char *)linkBackData, linkBackLen);
315 quint32 pdfLen = ar.size();
317 ds << pdfLen; // big endian by default
319 // only non-Mac this should never happen
320 LASSERT(false, /**/);
329 docstring const GuiClipboard::getAsText() const
331 // text data from other applications
332 QString const str = qApp->clipboard()->text(QClipboard::Clipboard)
333 .normalized(QString::NormalizationForm_C);
334 LYXERR(Debug::ACTION, "GuiClipboard::getAsText(): `" << str << "'");
338 return internalLineEnding(str);
342 void GuiClipboard::put(string const & lyx, docstring const & text)
344 LYXERR(Debug::ACTION, "GuiClipboard::put(`" << lyx << "' `"
345 << to_utf8(text) << "')");
346 // We don't convert the encoding of lyx since the encoding of the
347 // clipboard contents is specified in the data itself
348 QMimeData * data = new QMimeData;
350 QByteArray const qlyx(lyx.c_str(), lyx.size());
351 data->setData(lyxMimeType(), qlyx);
353 // Don't test for text.empty() since we want to be able to clear the
355 QString const qtext = toqstr(text);
356 data->setText(qtext);
357 qApp->clipboard()->setMimeData(data, QClipboard::Clipboard);
361 bool GuiClipboard::hasLyXContents() const
363 return cache_.hasFormat(lyxMimeType());
367 bool GuiClipboard::hasTextContents() const
369 return cache_.hasText();
373 bool GuiClipboard::hasGraphicsContents(Clipboard::GraphicsType type) const
375 if (type == AnyGraphicsType) {
376 return hasGraphicsContents(PdfGraphicsType)
377 || hasGraphicsContents(PngGraphicsType)
378 || hasGraphicsContents(JpegGraphicsType)
379 || hasGraphicsContents(EmfGraphicsType)
380 || hasGraphicsContents(WmfGraphicsType)
381 || hasGraphicsContents(LinkBackGraphicsType);
384 // handle image cases first
385 if (type == PngGraphicsType || type == JpegGraphicsType)
386 return cache_.hasImage();
388 // handle LinkBack for Mac
389 if (type == LinkBackGraphicsType)
391 return isLinkBackDataInPasteboard();
397 QStringList const & formats = cache_.formats();
398 LYXERR(Debug::ACTION, "We found " << formats.size() << " formats");
399 for (int i = 0; i < formats.size(); ++i)
400 LYXERR(Debug::ACTION, "Found format " << formats[i]);
402 // compute mime for type
405 case EmfGraphicsType: mime = emfMimeType(); break;
406 case WmfGraphicsType: mime = wmfMimeType(); break;
407 case PdfGraphicsType: mime = pdfMimeType(); break;
408 default: LASSERT(false, /**/);
411 return cache_.hasFormat(mime);
415 bool GuiClipboard::isInternal() const
417 // ownsClipboard() is also true for stuff coming from dialogs, e.g.
418 // the preamble dialog
419 // FIXME: This does only work on X11, since ownsClipboard() is
420 // hardwired to return false on Windows and OS X.
421 return qApp->clipboard()->ownsClipboard() && hasLyXContents();
425 bool GuiClipboard::hasInternal() const
427 // Windows and Mac OS X does not have the concept of ownership;
428 // the clipboard is a fully global resource so all applications
429 // are notified of changes.
430 #if (defined(Q_WS_X11))
438 void GuiClipboard::on_dataChanged()
440 //Note: we do not really need to run cache_.update() unless the
441 //data has been changed *and* the GuiClipboard has been queried.
442 //However if run cache_.update() the moment a process grabs the
443 //clipboard, the process holding the clipboard presumably won't
444 //yet be frozen, and so we won't need to wait 5 seconds for Qt
445 //to time-out waiting for the clipboard.
447 QStringList l = cache_.formats();
448 LYXERR(Debug::ACTION, "Qt Clipboard changed. We found the following mime types:");
449 for (int i = 0; i < l.count(); i++)
450 LYXERR(Debug::ACTION, l.value(i));
452 text_clipboard_empty_ = qApp->clipboard()->
453 text(QClipboard::Clipboard).isEmpty();
455 has_lyx_contents_ = hasLyXContents();
456 has_graphics_contents_ = hasGraphicsContents();
460 bool GuiClipboard::empty() const
462 // We need to check both the plaintext and the LyX version of the
463 // clipboard. The plaintext version is empty if the LyX version
464 // contains only one inset, and the LyX version is empty if the
465 // clipboard does not come from LyX.
466 if (!text_clipboard_empty_)
468 return !has_lyx_contents_ && !has_graphics_contents_;
471 } // namespace frontend
474 #include "moc_GuiClipboard.cpp"