2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * 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 "GuiApplication.h"
17 #include "ToolTipFormatter.h"
18 #include "ColorCache.h"
20 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferParams.h"
36 #include "BufferView.h"
39 #include "Converter.h"
40 #include "CutAndPaste.h"
41 #include "ErrorList.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.h"
45 #include "GuiWorkArea.h"
49 #include "LaTeXPackages.h"
52 #include "LyXAction.h"
54 #include "Paragraph.h"
57 #include "SpellChecker.h"
58 #include "Thesaurus.h"
61 #include "insets/InsetText.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/FileName.h"
67 #include "support/filetools.h"
68 #include "support/ForkedCalls.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/lstrings.h"
72 #include "support/lyxalgo.h" // sorted
73 #include "support/Messages.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/TempFile.h"
77 #include "support/textutils.h"
80 #include "support/AppleScript.h"
81 #include "support/linkback/LinkBackProxy.h"
88 #include <QDesktopWidget>
91 #include <QFileOpenEvent>
93 #include <QFontDatabase>
96 #include <QImageReader>
99 #include <QLibraryInfo>
106 #include <QSessionManager>
108 #include <QSocketNotifier>
109 #include <QSortFilterProxyModel>
110 #include <QStandardItemModel>
112 #include <QTranslator>
113 #include <QThreadPool>
117 #include <X11/Xatom.h>
118 #include <X11/Xlib.h>
122 #elif defined(QPA_XCB)
124 #ifdef HAVE_QT5_X11_EXTRAS
125 #include <QtX11Extras/QX11Info>
129 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
130 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
131 #if (QT_VERSION < 0x050000)
132 #include <QWindowsMime>
133 #define QWINDOWSMIME QWindowsMime
136 #define QWINDOWSMIME QWinMime
146 #include <QMacPasteboardMime>
149 #include <boost/crc.hpp>
156 using namespace lyx::support;
159 static void initializeResources()
161 static bool initialized = false;
163 Q_INIT_RESOURCE(Resources);
171 frontend::Application * createApplication(int & argc, char * argv[])
173 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
174 // prune -geometry argument(s) by shifting
175 // the following ones 2 places down.
176 for (int i = 0 ; i < argc ; ++i) {
177 if (strcmp(argv[i], "-geometry") == 0) {
178 int const remove = (i+1) < argc ? 2 : 1;
180 for (int j = i; j < argc; ++j)
181 argv[j] = argv[j + remove];
187 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
188 // On Windows, allow bringing the LyX window to top
189 AllowSetForegroundWindow(ASFW_ANY);
192 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
193 // I'd rather do that in the constructor, but I do not think that
194 // the palette is accessible there.
195 guiApp->colorCache().setPalette(guiApp->palette());
204 if (lyxrc.gui_language == "auto") {
205 theLocale = QLocale::system();
206 code = fromqstr(theLocale.name());
208 Language const * l = languages.getLanguage(lyxrc.gui_language);
209 code = l ? l->code() : "C";
210 theLocale = QLocale(toqstr(code));
212 // Qt tries to outsmart us and transforms en_US to C.
213 Messages::guiLanguage((code == "C") ? "en_US" : code);
214 QLocale::setDefault(theLocale);
215 setlocale(LC_NUMERIC, "C");
222 /// Return the list of loadable formats.
223 vector<string> loadableImageFormats()
227 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
229 LYXERR(Debug::GRAPHICS,
230 "\nThe image loader can load the following directly:\n");
232 if (qt_formats.empty())
233 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
235 bool jpeg_found = false;
236 bool jpg_found = false;
237 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
239 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
241 string ext = ascii_lowercase((const char *) *it);
249 else if (ext == "jpg") {
254 else if (lyxrc.use_converter_cache &&
255 (ext == "svg" || ext == "svgz") &&
256 theConverters().isReachable("svg", "png"))
257 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
258 // the SVG as in the output. However we require that the converter
259 // cache is enabled since this is expensive. We also require that
260 // an explicit svg->png converter is defined, since the default
261 // converter could produce bad quality as well. This assumes that
262 // png can always be loaded.
271 ////////////////////////////////////////////////////////////////////////
273 // Icon loading support code
275 ////////////////////////////////////////////////////////////////////////
285 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
287 return lhs.key < rhs.key;
293 CompareKey(QString const & name) : name_(name) {}
294 bool operator()(ImgMap const & other) const { return other.key == name_; }
300 // this must be sorted alphabetically
301 // Upper case comes before lower case
302 // Please don't change the formatting, this list is parsed by
303 // development/tools/generate_symbols_images.py.
304 ImgMap sorted_img_map[] = {
305 { "Arrownot", "arrownot2"},
306 { "Arrowvert", "arrowvert2"},
307 { "Bowtie", "bowtie2" },
309 { "Bumpeq", "bumpeq2" },
310 { "CIRCLE", "circle3" },
312 { "CheckedBox", "checkedbox2" },
313 { "Circle", "circle2" },
314 { "Colonapprox", "colonapprox2" },
315 { "Coloneq", "coloneq2" },
316 { "Coloneqq", "coloneqq2" },
317 { "Colonsim", "colonsim2" },
319 { "DOWNarrow", "downarrow3" },
320 { "Delta", "delta2" },
321 { "Diamond", "diamond2" },
322 { "Doteq", "doteq2" },
323 { "Downarrow", "downarrow2" },
324 { "Eqcolon", "eqcolon2" },
325 { "Eqqcolon", "eqqcolon2" },
326 { "Gamma", "gamma2" },
328 { "LEFTCIRCLE", "leftcircle3" },
329 { "LEFTarrow", "leftarrow3" },
330 { "LEFTcircle", "leftcircle4" },
332 { "Lambda", "lambda2" },
334 { "Leftarrow", "leftarrow2" },
335 { "Leftcircle", "leftcircle2" },
336 { "Leftrightarrow", "leftrightarrow2" },
337 { "Longarrownot", "longarrownot2"},
338 { "Longleftarrow", "longleftarrow2" },
339 { "Longleftrightarrow", "longleftrightarrow2" },
340 { "Longmapsfrom", "longmapsfrom2"},
341 { "Longmapsto", "longmapsto2"},
342 { "Longrightarrow", "longrightarrow2" },
343 { "Mapsfrom", "mapsfrom2"},
344 { "Mapsfromchar", "mapsfromchar2"},
345 { "Mapsto", "mapsto2"},
346 { "Mapstochar", "mapstochar2"},
347 { "Omega", "omega2" },
352 { "RIGHTCIRCLE", "rightcircle3" },
353 { "RIGHTarrow", "rightarrow3" },
354 { "RIGHTcircle", "rightcircle4" },
356 { "Rightarrow", "rightarrow2" },
357 { "Rightcircle", "rightcircle2" },
358 { "Sigma", "sigma2" },
359 { "Square", "square2" },
360 { "Subset", "subset2" },
361 { "Supset", "supset2" },
362 { "Theta", "theta2" },
363 { "Thorn", "thorn2" },
364 { "UParrow", "uparrow3" },
365 { "Uparrow", "uparrow2" },
366 { "Updownarrow", "updownarrow2" },
367 { "Upsilon", "upsilon2" },
368 { "Vdash", "vdash3" },
373 { "lVert", "vert2" },
375 { "nLeftarrow", "nleftarrow2" },
376 { "nLeftrightarrow", "nleftrightarrow2" },
377 { "nRightarrow", "nrightarrow2" },
378 { "nVDash", "nvdash3" },
379 { "nVdash", "nvdash4" },
380 { "nvDash", "nvdash2" },
381 { "rVert", "vert2" },
383 { "textrm \\AA", "textrm_AA"},
384 { "textrm \\O", "textrm_O"},
385 { "vDash", "vdash2" },
386 { "varDelta", "vardelta2" },
387 { "varGamma", "vargamma2" },
388 { "varLambda", "varlambda2" },
389 { "varOmega", "varomega2" },
390 { "varPhi", "varphi2" },
391 { "varPi", "varpi2" },
392 { "varPsi", "varpsi2" },
393 { "varSigma", "varsigma2" },
394 { "varTheta", "vartheta2" },
395 { "varUpsilon", "varupsilon2" },
396 { "varXi", "varxi2" }
400 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
402 // This list specifies which system's theme icon is related to which lyx
403 // command. It was based on:
404 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
405 // this must be sorted alphabetically
406 // Upper case comes before lower case
407 ImgMap sorted_theme_icon_map[] = {
408 { "bookmark-goto 0", "go-jump" },
409 { "buffer-new", "document-new" },
410 { "buffer-write", "document-save" },
411 { "buffer-write-as", "document-save-as" },
412 { "buffer-zoom-in", "zoom-in" },
413 { "buffer-zoom-out", "zoom-out" },
414 { "copy", "edit-copy" },
415 { "cut", "edit-cut" },
416 { "depth-decrement", "format-indent-less" },
417 { "depth-increment", "format-indent-more" },
418 { "dialog-show spellchecker", "tools-check-spelling" },
419 { "dialog-show-new-inset graphics", "insert-image" },
420 { "dialog-toggle findreplaceadv", "edit-find-replace" },
421 { "file-open", "document-open" },
422 { "font-bold", "format-text-bold" },
423 { "font-ital", "format-text-italic" },
424 { "font-strikeout", "format-text-strikethrough" },
425 { "font-underline", "format-text-underline" },
426 { "lyx-quit", "application-exit" },
427 { "paste", "edit-paste" },
428 { "redo", "edit-redo" },
429 { "undo", "edit-undo" },
430 { "window-close", "window-close" },
431 { "window-new", "window-new" }
434 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
437 QString findImg(QString const & name)
439 ImgMap const * const begin = sorted_img_map;
440 ImgMap const * const end = begin + nr_sorted_img_map;
441 LATTEST(sorted(begin, end));
443 ImgMap const * const it = find_if(begin, end, CompareKey(name));
447 img_name = it->value;
450 img_name.replace('_', "underscore");
451 img_name.replace(' ', '_');
453 // This way we can have "math-delim { }" on the toolbar.
454 img_name.replace('(', "lparen");
455 img_name.replace(')', "rparen");
456 img_name.replace('[', "lbracket");
457 img_name.replace(']', "rbracket");
458 img_name.replace('{', "lbrace");
459 img_name.replace('}', "rbrace");
460 img_name.replace('|', "bars");
461 img_name.replace(',', "thinspace");
462 img_name.replace(':', "mediumspace");
463 img_name.replace(';', "thickspace");
464 img_name.replace('!', "negthinspace");
467 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
468 << "Looking for math icon called \"" << img_name << '"');
475 QString themeIconName(QString const & action)
477 ImgMap const * const begin = sorted_theme_icon_map;
478 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
479 LASSERT(sorted(begin, end), /**/);
481 ImgMap const * const it = find_if(begin, end, CompareKey(action));
489 QString iconName(FuncRequest const & f, bool unknown)
491 initializeResources();
495 switch (f.action()) {
496 case LFUN_MATH_INSERT:
497 if (!f.argument().empty()) {
499 name1 = findImg(toqstr(f.argument()).mid(1));
502 case LFUN_MATH_DELIM:
503 case LFUN_MATH_BIGDELIM:
505 name1 = findImg(toqstr(f.argument()));
509 name1 = toqstr(f.argument());
511 case LFUN_COMMAND_ALTERNATIVES: {
512 // use the first of the alternative commands
514 docstring dummy = split(f.argument(), firstcom, ';');
515 name1 = toqstr(firstcom);
516 name1.replace(' ', '_');
520 name2 = toqstr(lyxaction.getActionName(f.action()));
523 if (!f.argument().empty()) {
524 name1 = name2 + ' ' + toqstr(f.argument());
525 name1.replace(' ', '_');
526 name1.replace('\\', "backslash");
530 QStringList imagedirs;
531 imagedirs << "images/" << "images/ipa/";
532 search_mode mode = theGuiApp()->imageSearchMode();
533 for (int i = 0; i < imagedirs.size(); ++i) {
534 QString imagedir = imagedirs.at(i) + path;
535 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
537 return toqstr(fname.absFileName());
539 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
541 return toqstr(fname.absFileName());
544 path = ":/images/" + path;
547 LYXERR0("Directory " << path << " not found in resource!");
550 if (res.exists(name1 + ".svgz"))
551 return path + name1 + ".svgz";
552 else if (res.exists(name1 + ".png"))
553 return path + name1 + ".png";
555 if (res.exists(name2 + ".svgz"))
556 return path + name2 + ".svgz";
557 else if (res.exists(name2 + ".png"))
558 return path + name2 + ".png";
560 LYXERR(Debug::GUI, "Cannot find icon with filename "
561 << "\"" << name1 << ".{svgz,png}\""
563 << "\"" << name2 << ".{svgz,png}\""
565 << lyxaction.getActionName(f.action())
566 << '(' << to_utf8(f.argument()) << ")\"");
569 QString imagedir = "images/";
570 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
572 return toqstr(fname.absFileName());
573 return QString(":/images/unknown.svgz");
580 bool getPixmap(QPixmap & pixmap, QString const & path)
582 return pixmap.load(path);
586 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
588 QString imagedir = path;
589 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
590 QString fpath = toqstr(fname.absFileName());
591 QPixmap pixmap = QPixmap();
593 if (getPixmap(pixmap, fpath)) {
597 QStringList exts = ext.split(",");
598 fpath = ":/" + path + name + ".";
599 for (int i = 0; i < exts.size(); ++i) {
600 if (getPixmap(pixmap, fpath + exts.at(i))) {
605 bool const list = ext.contains(",");
606 LYXERR0("Cannot load pixmap \""
607 << path << name << "." << (list ? "{" : "") << ext
608 << (list ? "}" : "") << "\", please verify resource system!");
614 QIcon getIcon(FuncRequest const & f, bool unknown)
616 #if (QT_VERSION >= 0x040600)
617 if (lyxrc.use_system_theme_icons) {
618 // use the icons from system theme that are available
619 QString action = toqstr(lyxaction.getActionName(f.action()));
620 if (!f.argument().empty())
621 action += " " + toqstr(f.argument());
622 QString const theme_icon = themeIconName(action);
623 if (QIcon::hasThemeIcon(theme_icon)) {
624 QIcon const thmicn = QIcon::fromTheme(theme_icon);
625 if (!thmicn.isNull())
631 QString icon = iconName(f, unknown);
635 //LYXERR(Debug::GUI, "Found icon: " << icon);
636 QPixmap pixmap = QPixmap();
637 if (!getPixmap(pixmap,icon)) {
638 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
642 return QIcon(pixmap);
646 ////////////////////////////////////////////////////////////////////////
648 // LyX server support code.
650 ////////////////////////////////////////////////////////////////////////
652 class SocketNotifier : public QSocketNotifier
655 /// connect a connection notification from the LyXServerSocket
656 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
657 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
661 /// The callback function
662 Application::SocketCallback func_;
666 class GuiTranslator : public QTranslator
669 GuiTranslator(QObject * parent = nullptr)
670 : QTranslator(parent)
673 virtual QString translate(const char * /* context */,
674 const char *sourceText,
675 #if QT_VERSION >= 0x050000
676 const char * /* disambiguation */ = 0, int /* n */ = -1) const
678 const char * /*comment*/ = 0) const
681 // Here we declare the strings that need to be translated from Qt own GUI
682 // This is needed to include these strings to po files
686 _("Restore Defaults");
689 // Already in po: "Cancel", "&Cancel"
690 _("Apply"); // Already in po: "&Apply"
691 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
694 docstring s = getGuiMessages().getIfFound(sourceText);
695 // This test should eventually be removed when translations are updated
697 LYXERR(Debug::LOCALE, "Missing translation for `"
698 << string(sourceText) << "'");
704 ////////////////////////////////////////////////////////////////////////
706 // Mac specific stuff goes here...
708 ////////////////////////////////////////////////////////////////////////
711 // QMacPasteboardMimeGraphics can only be compiled on Mac.
713 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
716 QMacPasteboardMimeGraphics()
717 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
720 QString convertorName() { return "Graphics"; }
722 QString flavorFor(QString const & mime)
724 LYXERR(Debug::ACTION, "flavorFor " << mime);
725 if (mime == pdfMimeType())
726 return QLatin1String("com.adobe.pdf");
730 QString mimeFor(QString flav)
732 LYXERR(Debug::ACTION, "mimeFor " << flav);
733 if (flav == QLatin1String("com.adobe.pdf"))
734 return pdfMimeType();
738 bool canConvert(QString const & mime, QString flav)
740 return mimeFor(flav) == mime;
743 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
747 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
751 QList<QByteArray> convertFromMime(QString const & /*mime*/,
752 QVariant data, QString /*flav*/)
754 QList<QByteArray> ret;
755 ret.append(data.toByteArray());
761 ///////////////////////////////////////////////////////////////
763 // You can find more platform specific stuff at the end of this file...
765 ///////////////////////////////////////////////////////////////
767 ////////////////////////////////////////////////////////////////////////
768 // Windows specific stuff goes here...
770 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
771 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
772 // QWindowsMimeMetafile can only be compiled on Windows.
774 static FORMATETC cfFromMime(QString const & mimetype)
777 if (mimetype == emfMimeType()) {
778 formatetc.cfFormat = CF_ENHMETAFILE;
779 formatetc.tymed = TYMED_ENHMF;
780 } else if (mimetype == wmfMimeType()) {
781 formatetc.cfFormat = CF_METAFILEPICT;
782 formatetc.tymed = TYMED_MFPICT;
785 formatetc.dwAspect = DVASPECT_CONTENT;
786 formatetc.lindex = -1;
791 class QWindowsMimeMetafile : public QWINDOWSMIME {
793 QWindowsMimeMetafile() {}
795 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
796 QMimeData const * /*mimedata*/) const
801 bool canConvertToMime(QString const & mimetype,
802 IDataObject * pDataObj) const
804 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
806 FORMATETC formatetc = cfFromMime(mimetype);
807 return pDataObj->QueryGetData(&formatetc) == S_OK;
810 bool convertFromMime(FORMATETC const & /*formatetc*/,
811 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
816 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
817 QVariant::Type /*preferredType*/) const
820 if (!canConvertToMime(mimetype, pDataObj))
823 FORMATETC formatetc = cfFromMime(mimetype);
825 if (pDataObj->GetData(&formatetc, &s) != S_OK)
829 if (s.tymed == TYMED_ENHMF) {
830 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
831 data.resize(dataSize);
832 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
833 (LPBYTE)data.data());
834 } else if (s.tymed == TYMED_MFPICT) {
835 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
836 data.resize(dataSize);
837 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
838 (LPBYTE)data.data());
841 ReleaseStgMedium(&s);
847 QVector<FORMATETC> formatsForMime(QString const & mimetype,
848 QMimeData const * /*mimedata*/) const
850 QVector<FORMATETC> formats;
851 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
852 formats += cfFromMime(mimetype);
856 QString mimeForFormat(FORMATETC const & formatetc) const
858 switch (formatetc.cfFormat) {
860 return emfMimeType();
861 case CF_METAFILEPICT:
862 return wmfMimeType();
872 /// Allows to check whether ESC was pressed during a long operation
873 class KeyChecker : public QObject {
878 KeyChecker() : pressed_(false), started_(false) {}
881 QCoreApplication::instance()->installEventFilter(this);
886 QCoreApplication::instance()->removeEventFilter(this);
890 QCoreApplication::processEvents();
893 bool started() const {
896 bool eventFilter(QObject *obj, QEvent *event) {
897 LYXERR(Debug::ACTION, "Event Type: " << event->type());
898 switch (event->type()) {
902 case QEvent::UpdateRequest:
903 case QEvent::CursorChange:
904 case QEvent::ActionChanged:
905 case QEvent::EnabledChange:
906 case QEvent::SockAct:
909 case QEvent::ToolTipChange:
910 case QEvent::LayoutRequest:
911 case QEvent::MetaCall:
912 return QObject::eventFilter(obj, event);
914 // FIXME Blocking all these events is a bad idea.
915 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
916 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
924 ////////////////////////////////////////////////////////////////////////
925 // GuiApplication::Private definition and implementation.
926 ////////////////////////////////////////////////////////////////////////
928 struct GuiApplication::Private
930 Private(): language_model_(0), meta_fake_bit(NoModifier),
933 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
934 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
935 /// WMF Mime handler for Windows clipboard.
936 wmf_mime_ = new QWindowsMimeMetafile;
939 initKeySequences(&theTopLevelKeymap());
942 void initKeySequences(KeyMap * kb)
944 keyseq = KeySequence(kb, kb);
945 cancel_meta_seq = KeySequence(kb, kb);
949 QSortFilterProxyModel * language_model_;
951 GuiClipboard clipboard_;
953 GuiSelection selection_;
955 FontLoader font_loader_;
957 ColorCache color_cache_;
958 /// the built-in Qt translation mechanism
959 QTranslator qt_trans_;
960 /// LyX gettext-based translation for Qt elements
961 GuiTranslator gui_trans_;
963 QHash<int, SocketNotifier *> socket_notifiers_;
967 /// The global instance
970 /// this timer is used for any regular events one wants to
971 /// perform. at present it is used to check if forked processes
973 QTimer general_timer_;
975 /// delayed FuncRequests
976 std::queue<FuncRequest> func_request_queue_;
981 KeySequence cancel_meta_seq;
983 KeyModifier meta_fake_bit;
985 /// The result of last dispatch action
986 DispatchResult dispatch_result_;
988 /// Multiple views container.
990 * Warning: This must not be a smart pointer as the destruction of the
991 * object is handled by Qt when the view is closed
992 * \sa Qt::WA_DeleteOnClose attribute.
994 QHash<int, GuiView *> views_;
996 /// Only used on mac.
997 QMenuBar * global_menubar_;
1000 /// Linkback mime handler for MacOSX.
1001 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1004 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1005 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1006 /// WMF Mime handler for Windows clipboard.
1007 QWindowsMimeMetafile * wmf_mime_;
1011 /// Allows to check whether ESC was pressed during a long operation
1012 KeyChecker key_checker_;
1016 GuiApplication * guiApp;
1018 GuiApplication::~GuiApplication()
1021 closeAllLinkBackLinks();
1027 GuiApplication::GuiApplication(int & argc, char ** argv)
1028 : QApplication(argc, argv), current_view_(0),
1029 d(new GuiApplication::Private)
1031 QString app_name = "LyX";
1032 QCoreApplication::setOrganizationName(app_name);
1033 QCoreApplication::setOrganizationDomain("lyx.org");
1034 QCoreApplication::setApplicationName(lyx_package);
1035 #if QT_VERSION >= 0x050000
1036 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1039 qsrand(QDateTime::currentDateTime().toTime_t());
1041 // Install LyX translator for missing Qt translations
1042 installTranslator(&d->gui_trans_);
1043 // Install Qt native translator for GUI elements.
1044 installTranslator(&d->qt_trans_);
1047 // Enable reception of XCB events.
1048 installNativeEventFilter(this);
1051 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1052 // lyxrc setting for this in order to let the application stay resident.
1053 // But then we need some kind of dock icon, at least on Windows.
1055 if (lyxrc.quit_on_last_window_closed)
1056 setQuitOnLastWindowClosed(false);
1059 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1060 // seems to be the default case for applications like LyX.
1061 setQuitOnLastWindowClosed(false);
1066 #if defined(Q_WS_X11) || defined(QPA_XCB)
1067 // doubleClickInterval() is 400 ms on X11 which is just too long.
1068 // On Windows and Mac OS X, the operating system's value is used.
1069 // On Microsoft Windows, calling this function sets the double
1070 // click interval for all applications. So we don't!
1071 QApplication::setDoubleClickInterval(300);
1074 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1076 // needs to be done before reading lyxrc
1078 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1082 // Initialize RC Fonts
1083 if (lyxrc.roman_font_name.empty())
1084 lyxrc.roman_font_name = fromqstr(romanFontName());
1086 if (lyxrc.sans_font_name.empty())
1087 lyxrc.sans_font_name = fromqstr(sansFontName());
1089 if (lyxrc.typewriter_font_name.empty())
1090 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1092 #if (QT_VERSION >= 0x050000)
1093 // Qt4 does this in event(), see below.
1094 // Track change of keyboard
1095 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1098 d->general_timer_.setInterval(500);
1099 connect(&d->general_timer_, SIGNAL(timeout()),
1100 this, SLOT(handleRegularEvents()));
1101 d->general_timer_.start();
1103 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1104 // This is clearly not enough in a time where we use threads for
1105 // document preview and/or export. 20 should be OK.
1106 QThreadPool::globalInstance()->setMaxThreadCount(20);
1108 // make sure tooltips are formatted
1109 installEventFilter(new ToolTipFormatter(this));
1113 GuiApplication * theGuiApp()
1115 return dynamic_cast<GuiApplication *>(theApp());
1119 double GuiApplication::pixelRatio() const
1121 #if QT_VERSION >= 0x050000
1122 return qt_scale_factor * devicePixelRatio();
1129 void GuiApplication::clearSession()
1136 docstring Application::iconName(FuncRequest const & f, bool unknown)
1138 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1142 docstring Application::mathIcon(docstring const & c)
1144 return qstring_to_ucs4(findImg(toqstr(c)));
1148 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1152 BufferView * bv = 0;
1153 BufferView * doc_bv = 0;
1155 if (cmd.action() == LFUN_NOACTION) {
1156 status.message(from_utf8(N_("Nothing to do")));
1157 status.setEnabled(false);
1160 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1161 status.setUnknown(true);
1162 status.message(from_utf8(N_("Unknown action")));
1163 status.setEnabled(false);
1166 // Does the GuiApplication know something?
1167 else if (getStatus(cmd, status)) { }
1169 // If we do not have a GuiView, then other functions are disabled
1170 else if (!current_view_)
1171 status.setEnabled(false);
1173 // Does the GuiView know something?
1174 else if (current_view_->getStatus(cmd, status)) { }
1176 // In LyX/Mac, when a dialog is open, the menus of the
1177 // application can still be accessed without giving focus to
1178 // the main window. In this case, we want to disable the menu
1179 // entries that are buffer or view-related.
1180 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1182 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1183 status.setEnabled(false);
1186 // If we do not have a BufferView, then other functions are disabled
1187 else if (!(bv = current_view_->currentBufferView()))
1188 status.setEnabled(false);
1190 // Does the current BufferView know something?
1191 else if (bv->getStatus(cmd, status)) { }
1193 // Does the current Buffer know something?
1194 else if (bv->buffer().getStatus(cmd, status)) { }
1196 // If we do not have a document BufferView, different from the
1197 // current BufferView, then other functions are disabled
1198 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1199 status.setEnabled(false);
1201 // Does the document Buffer know something?
1202 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1205 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1206 status.message(from_utf8(N_("Command not handled")));
1207 status.setEnabled(false);
1210 // the default error message if we disable the command
1211 if (!status.enabled() && status.message().empty())
1212 status.message(from_utf8(N_("Command disabled")));
1218 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1220 // I would really like to avoid having this switch and rather try to
1221 // encode this in the function itself.
1222 // -- And I'd rather let an inset decide which LFUNs it is willing
1223 // to handle (Andre')
1225 switch (cmd.action()) {
1227 // This could be used for the no-GUI version. The GUI version is handled in
1228 // GuiView::getStatus(). See above.
1230 case LFUN_BUFFER_WRITE:
1231 case LFUN_BUFFER_WRITE_AS:
1232 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1233 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1234 enable = b && (b->isUnnamed() || !b->isClean());
1239 case LFUN_BOOKMARK_GOTO: {
1240 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1241 enable = theSession().bookmarks().isValid(num);
1245 case LFUN_BOOKMARK_CLEAR:
1246 enable = theSession().bookmarks().hasValid();
1249 // this one is difficult to get right. As a half-baked
1250 // solution, we consider only the first action of the sequence
1251 case LFUN_COMMAND_SEQUENCE: {
1252 // argument contains ';'-terminated commands
1253 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1254 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1255 func.setOrigin(cmd.origin());
1256 flag = getStatus(func);
1260 // we want to check if at least one of these is enabled
1261 case LFUN_COMMAND_ALTERNATIVES: {
1262 // argument contains ';'-terminated commands
1263 string arg = to_utf8(cmd.argument());
1264 while (!arg.empty()) {
1266 arg = split(arg, first, ';');
1267 FuncRequest func(lyxaction.lookupFunc(first));
1268 func.setOrigin(cmd.origin());
1269 flag = getStatus(func);
1270 // if this one is enabled, the whole thing is
1279 string name = to_utf8(cmd.argument());
1280 if (theTopLevelCmdDef().lock(name, func)) {
1281 func.setOrigin(cmd.origin());
1282 flag = getStatus(func);
1283 theTopLevelCmdDef().release(name);
1285 // catch recursion or unknown command
1286 // definition. all operations until the
1287 // recursion or unknown command definition
1288 // occurs are performed, so set the state to
1296 string const dir = cmd.getArg(0);
1297 string const lfun = cmd.getLongArg(1);
1298 BufferView const * bv =
1299 current_view_ ? current_view_->currentBufferView() : nullptr;
1300 bool rtl = bv ? bv->cursor().innerParagraph().isRTL(bv->buffer().params())
1301 : layoutDirection() == Qt::RightToLeft;
1302 if (((rtl && dir != "rtl") || (!rtl && dir != "ltr"))) {
1303 flag.setUnknown(true);
1304 flag.setEnabled(false);
1306 FuncRequest func(lyxaction.lookupFunc(lfun));
1307 func.setOrigin(cmd.origin());
1308 flag = getStatus(func);
1313 case LFUN_IF_RELATIVES: {
1314 string const lfun = to_utf8(cmd.argument());
1315 BufferView const * bv =
1316 current_view_ ? current_view_->currentBufferView() : nullptr;
1317 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1321 FuncRequest func(lyxaction.lookupFunc(lfun));
1322 func.setOrigin(cmd.origin());
1323 flag = getStatus(func);
1327 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1329 case LFUN_PREFERENCES_SAVE:
1330 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1331 case LFUN_DEBUG_LEVEL_SET:
1332 // these are handled in our dispatch()
1335 case LFUN_WINDOW_CLOSE:
1336 enable = d->views_.size() > 0;
1339 case LFUN_BUFFER_NEW:
1340 case LFUN_BUFFER_NEW_TEMPLATE:
1341 case LFUN_FILE_OPEN:
1342 case LFUN_HELP_OPEN:
1343 case LFUN_SCREEN_FONT_UPDATE:
1344 case LFUN_SET_COLOR:
1345 case LFUN_WINDOW_NEW:
1347 case LFUN_LYXRC_APPLY:
1348 case LFUN_COMMAND_PREFIX:
1350 case LFUN_META_PREFIX:
1351 case LFUN_RECONFIGURE:
1352 case LFUN_SERVER_GET_FILENAME:
1353 case LFUN_SERVER_NOTIFY:
1357 case LFUN_BUFFER_FORALL: {
1358 if (theBufferList().empty()) {
1359 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1360 flag.setEnabled(false);
1364 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1365 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1366 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1367 flag.setEnabled(false);
1372 case LFUN_DIALOG_SHOW: {
1373 string const name = cmd.getArg(0);
1374 return name == "aboutlyx"
1375 || name == "lyxfiles"
1377 || name == "texinfo"
1378 || name == "progress"
1379 || name == "compare";
1387 flag.setEnabled(false);
1391 /// make a post-dispatch status message
1392 static docstring makeDispatchMessage(docstring const & msg,
1393 FuncRequest const & cmd)
1395 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1396 || cmd.origin() == FuncRequest::TOOLBAR
1397 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1399 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1400 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1404 docstring dispatch_msg = msg;
1405 if (!dispatch_msg.empty())
1406 dispatch_msg += ' ';
1408 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1410 bool argsadded = false;
1412 if (!cmd.argument().empty()) {
1413 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1414 comname += ' ' + cmd.argument();
1418 docstring const shortcuts = theTopLevelKeymap().
1419 printBindings(cmd, KeySequence::ForGui);
1421 if (!shortcuts.empty())
1422 comname += ": " + shortcuts;
1423 else if (!argsadded && !cmd.argument().empty())
1424 comname += ' ' + cmd.argument();
1426 if (!comname.empty()) {
1427 comname = rtrim(comname);
1428 dispatch_msg += '(' + rtrim(comname) + ')';
1430 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1431 return dispatch_msg;
1435 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1439 Buffer * buffer = 0;
1440 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1441 //setCurrentView(cmd.view_origin); //does not work
1443 dr.setMessage(_("Wrong focus!"));
1444 d->dispatch_result_ = dr;
1445 return d->dispatch_result_;
1447 if (current_view_ && current_view_->currentBufferView()) {
1448 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1449 buffer = ¤t_view_->currentBufferView()->buffer();
1452 dr.screenUpdate(Update::FitCursor);
1454 // This handles undo groups automagically
1455 UndoGroupHelper ugh(buffer);
1457 // redraw the screen at the end (first of the two drawing steps).
1458 // This is done unless explicitly requested otherwise.
1459 // This code is kept inside the undo group because updateBuffer
1460 // can create undo actions (see #11292)
1461 updateCurrentView(cmd, dr);
1464 d->dispatch_result_ = dr;
1465 return d->dispatch_result_;
1469 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1474 BufferView * bv = current_view_->currentBufferView();
1476 if (dr.needBufferUpdate()) {
1477 bv->cursor().clearBufferUpdate();
1478 bv->buffer().updateBuffer();
1480 // BufferView::update() updates the ViewMetricsInfo and
1481 // also initializes the position cache for all insets in
1482 // (at least partially) visible top-level paragraphs.
1483 // We will redraw the screen only if needed.
1484 bv->processUpdateFlags(dr.screenUpdate());
1486 // Do we have a selection?
1487 theSelection().haveSelection(bv->cursor().selection());
1490 current_view_->restartCaret();
1492 if (dr.needMessageUpdate()) {
1493 // Some messages may already be translated, so we cannot use _()
1494 current_view_->message(makeDispatchMessage(
1495 translateIfPossible(dr.message()), cmd));
1500 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1501 bool switchToBuffer)
1503 if (!theSession().bookmarks().isValid(idx))
1505 BookmarksSection::Bookmark const & bm =
1506 theSession().bookmarks().bookmark(idx);
1507 LASSERT(!bm.filename.empty(), return);
1508 string const file = bm.filename.absFileName();
1509 // if the file is not opened, open it.
1510 if (!theBufferList().exists(bm.filename)) {
1512 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1516 // open may fail, so we need to test it again
1517 if (!theBufferList().exists(bm.filename))
1520 // bm can be changed when saving
1521 BookmarksSection::Bookmark tmp = bm;
1523 // Special case idx == 0 used for back-from-back jump navigation
1525 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1527 // if the current buffer is not that one, switch to it.
1528 BufferView * doc_bv = current_view_ ?
1529 current_view_->documentBufferView() : 0;
1530 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1531 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1532 if (switchToBuffer) {
1533 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1536 doc_bv = current_view_->documentBufferView();
1541 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1542 if (!doc_bv || !doc_bv->moveToPosition(
1543 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1546 Cursor & cur = doc_bv->cursor();
1547 if (old && cur != *old)
1548 notifyCursorLeavesOrEnters(*old, cur);
1554 // Cursor jump succeeded!
1555 pit_type new_pit = cur.pit();
1556 pos_type new_pos = cur.pos();
1557 int new_id = cur.paragraph().id();
1559 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1560 // see http://www.lyx.org/trac/ticket/3092
1561 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1562 || bm.top_id != new_id) {
1563 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1564 new_pit, new_pos, new_id);
1568 // This function runs "configure" and then rereads lyx.defaults to
1569 // reconfigure the automatic settings.
1570 void GuiApplication::reconfigure(string const & option)
1572 // emit message signal.
1574 current_view_->message(_("Running configure..."));
1576 // Run configure in user lyx directory
1577 string const lock_file = package().getConfigureLockName();
1578 int fd = fileLock(lock_file.c_str());
1579 int const ret = package().reconfigureUserLyXDir(option);
1580 // emit message signal.
1582 current_view_->message(_("Reloading configuration..."));
1583 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1584 // Re-read packages.lst
1585 LaTeXPackages::getAvailable();
1586 fileUnlock(fd, lock_file.c_str());
1589 Alert::information(_("System reconfiguration failed"),
1590 _("The system reconfiguration has failed.\n"
1591 "Default textclass is used but LyX may\n"
1592 "not be able to work properly.\n"
1593 "Please reconfigure again if needed."));
1595 Alert::information(_("System reconfigured"),
1596 _("The system has been reconfigured.\n"
1597 "You need to restart LyX to make use of any\n"
1598 "updated document class specifications."));
1601 void GuiApplication::validateCurrentView()
1603 if (!d->views_.empty() && !current_view_) {
1604 // currently at least one view exists but no view has the focus.
1605 // choose the last view to make it current.
1606 // a view without any open document is preferred.
1607 GuiView * candidate = 0;
1608 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1609 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1610 for (; it != end; ++it) {
1612 if (!candidate->documentBufferView())
1615 setCurrentView(candidate);
1619 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1621 string const argument = to_utf8(cmd.argument());
1622 FuncCode const action = cmd.action();
1624 LYXERR(Debug::ACTION, "cmd: " << cmd);
1626 // we have not done anything wrong yet.
1629 FuncStatus const flag = getStatus(cmd);
1630 if (!flag.enabled()) {
1631 // We cannot use this function here
1632 LYXERR(Debug::ACTION, "action "
1633 << lyxaction.getActionName(action)
1634 << " [" << action << "] is disabled at this location");
1635 dr.setMessage(flag.message());
1637 dr.dispatched(false);
1638 dr.screenUpdate(Update::None);
1639 dr.clearBufferUpdate();
1643 if (cmd.origin() == FuncRequest::LYXSERVER) {
1644 if (current_view_ && current_view_->currentBufferView())
1645 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1646 // we will also need to redraw the screen at the end
1647 dr.screenUpdate(Update::FitCursor);
1650 // Assumes that the action will be dispatched.
1651 dr.dispatched(true);
1653 switch (cmd.action()) {
1655 case LFUN_WINDOW_NEW:
1656 createView(toqstr(cmd.argument()));
1659 case LFUN_WINDOW_CLOSE:
1660 // update bookmark pit of the current buffer before window close
1661 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1662 gotoBookmark(i+1, false, false);
1663 // clear the last opened list, because
1664 // maybe this will end the session
1665 theSession().lastOpened().clear();
1666 // check for valid current_view_
1667 validateCurrentView();
1669 current_view_->closeScheduled();
1673 // quitting is triggered by the gui code
1674 // (leaving the event loop).
1676 current_view_->message(from_utf8(N_("Exiting.")));
1677 if (closeAllViews())
1681 case LFUN_SCREEN_FONT_UPDATE: {
1682 // handle the screen font changes.
1683 /* FIXME: this only updates the current document, whereas all
1684 * documents should see their metrics updated.
1686 d->font_loader_.update();
1687 dr.screenUpdate(Update::Force | Update::FitCursor);
1691 case LFUN_BUFFER_NEW:
1692 validateCurrentView();
1694 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1695 createView(QString(), false); // keep hidden
1696 current_view_->newDocument(to_utf8(cmd.argument()));
1697 current_view_->show();
1698 setActiveWindow(current_view_);
1700 current_view_->newDocument(to_utf8(cmd.argument()));
1704 case LFUN_BUFFER_NEW_TEMPLATE: {
1705 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1706 string const temp = cmd.getArg(1);
1707 validateCurrentView();
1709 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1711 current_view_->newDocument(file, temp, true);
1712 if (!current_view_->documentBufferView())
1713 current_view_->close();
1715 current_view_->newDocument(file, temp, true);
1720 case LFUN_FILE_OPEN: {
1721 // FIXME: normally the code below is not needed, since getStatus makes sure that
1722 // current_view_ is not null.
1723 validateCurrentView();
1724 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1725 string const fname = to_utf8(cmd.argument());
1726 bool const is_open = FileName::isAbsolute(fname)
1727 && theBufferList().getBuffer(FileName(fname));
1729 || (!lyxrc.open_buffers_in_tabs
1730 && current_view_->documentBufferView() != 0
1732 // We want the ui session to be saved per document and not per
1733 // window number. The filename crc is a good enough identifier.
1734 boost::crc_32_type crc;
1735 crc = for_each(fname.begin(), fname.end(), crc);
1736 createView(crc.checksum());
1737 current_view_->openDocument(fname);
1738 if (!current_view_->documentBufferView())
1739 current_view_->close();
1740 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1741 current_view_->raise();
1742 current_view_->activateWindow();
1743 current_view_->showNormal();
1746 current_view_->openDocument(fname);
1747 if (cmd.origin() == FuncRequest::LYXSERVER) {
1748 current_view_->raise();
1749 current_view_->activateWindow();
1750 current_view_->showNormal();
1756 case LFUN_HELP_OPEN: {
1757 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1758 if (current_view_ == 0)
1760 string const arg = to_utf8(cmd.argument());
1762 current_view_->message(_("Missing argument"));
1765 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1767 fname = i18nLibFileSearch("examples", arg, "lyx");
1769 if (fname.empty()) {
1770 lyxerr << "LyX: unable to find documentation file `"
1771 << arg << "'. Bad installation?" << endl;
1774 current_view_->message(bformat(_("Opening help file %1$s..."),
1775 makeDisplayPath(fname.absFileName())));
1776 Buffer * buf = current_view_->loadDocument(fname, false);
1778 buf->setReadonly(!current_view_->develMode());
1782 case LFUN_SET_COLOR: {
1783 string const lyx_name = cmd.getArg(0);
1784 string const x11_name = cmd.getArg(1);
1785 if (lyx_name.empty() || x11_name.empty()) {
1787 current_view_->message(
1788 _("Syntax: set-color <lyx_name> <x11_name>"));
1793 // FIXME: The graphics cache no longer has a changeDisplay method.
1794 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1795 bool const graphicsbg_changed =
1796 lyx_name == graphicsbg && x11_name != graphicsbg;
1797 if (graphicsbg_changed)
1798 graphics::GCache::get().changeDisplay(true);
1801 if (!lcolor.setColor(lyx_name, x11_name)) {
1803 current_view_->message(
1804 bformat(_("Set-color \"%1$s\" failed "
1805 "- color is undefined or "
1806 "may not be redefined"),
1807 from_utf8(lyx_name)));
1810 // Make sure we don't keep old colors in cache.
1811 d->color_cache_.clear();
1812 // Update the current view
1813 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1817 case LFUN_LYXRC_APPLY: {
1818 // reset active key sequences, since the bindings
1819 // are updated (bug 6064)
1821 LyXRC const lyxrc_orig = lyxrc;
1823 istringstream ss(to_utf8(cmd.argument()));
1824 bool const success = lyxrc.read(ss);
1827 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1828 << "Unable to read lyxrc data"
1833 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1835 // If the request comes from the minibuffer, then we can't reset
1836 // the GUI, since that would destory the minibuffer itself and
1837 // cause a crash, since we are currently in one of the methods of
1838 // GuiCommandBuffer. See bug #8540.
1839 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1842 // FIXME Unfortunately, that leaves a bug here, since we cannot
1843 // reset the GUI in this case. If the changes to lyxrc affected the
1844 // UI, then, nothing would happen. This seems fairly unlikely, but
1845 // it definitely is a bug.
1847 dr.forceBufferUpdate();
1851 case LFUN_COMMAND_PREFIX:
1852 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1857 d->meta_fake_bit = NoModifier;
1858 GuiView * gv = currentView();
1859 if (gv && gv->currentBufferView())
1860 // cancel any selection
1861 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1862 dr.setMessage(from_ascii(N_("Cancel")));
1865 case LFUN_META_PREFIX:
1866 d->meta_fake_bit = AltModifier;
1867 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1870 // --- Menus -----------------------------------------------
1871 case LFUN_RECONFIGURE:
1872 // argument is any additional parameter to the configure.py command
1873 reconfigure(to_utf8(cmd.argument()));
1876 // --- lyxserver commands ----------------------------
1877 case LFUN_SERVER_GET_FILENAME: {
1878 if (current_view_ && current_view_->documentBufferView()) {
1879 docstring const fname = from_utf8(
1880 current_view_->documentBufferView()->buffer().absFileName());
1881 dr.setMessage(fname);
1882 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1884 dr.setMessage(docstring());
1885 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1890 case LFUN_SERVER_NOTIFY: {
1891 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1892 dr.setMessage(dispatch_buffer);
1893 theServer().notifyClient(to_utf8(dispatch_buffer));
1897 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1898 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1901 // --- syntax commands ----------------------------
1905 string rest = split(argument, countstr, ' ');
1906 int const count = convert<int>(countstr);
1907 // an arbitrary number to limit number of iterations
1908 int const max_iter = 10000;
1909 if (count > max_iter) {
1910 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1913 for (int i = 0; i < count; ++i) {
1914 FuncRequest lfun = lyxaction.lookupFunc(rest);
1915 lfun.allowAsync(false);
1922 case LFUN_COMMAND_SEQUENCE: {
1923 // argument contains ';'-terminated commands
1924 string arg = argument;
1925 // FIXME: this LFUN should also work without any view.
1926 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1927 ? &(current_view_->documentBufferView()->buffer()) : 0;
1928 // This handles undo groups automagically
1929 UndoGroupHelper ugh(buffer);
1930 while (!arg.empty()) {
1932 arg = split(arg, first, ';');
1933 FuncRequest func(lyxaction.lookupFunc(first));
1934 func.allowAsync(false);
1935 func.setOrigin(cmd.origin());
1941 case LFUN_BUFFER_FORALL: {
1942 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1943 funcToRun.allowAsync(false);
1945 map<Buffer *, GuiView *> views_lVisible;
1946 map<GuiView *, Buffer *> activeBuffers;
1948 QList<GuiView *> allViews = d->views_.values();
1950 // this for does not modify any buffer. It just collects info on local
1951 // visibility of buffers and on which buffer is active in each view.
1952 Buffer * const last = theBufferList().last();
1953 for(GuiView * view : allViews) {
1954 // all of the buffers might be locally hidden. That is, there is no
1956 if (!view || !view->currentBufferView())
1957 activeBuffers[view] = 0;
1959 activeBuffers[view] = &view->currentBufferView()->buffer();
1961 // find out if each is locally visible or locally hidden.
1962 // we don't use a for loop as the buffer list cycles.
1963 Buffer * b = theBufferList().first();
1965 bool const locallyVisible = view && view->workArea(*b);
1966 if (locallyVisible) {
1967 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1968 // only need to overwrite/add if we don't already know a buffer is globally
1969 // visible or we do know but we would prefer to dispatch LFUN from the
1970 // current view because of cursor position issues.
1971 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1972 views_lVisible[b] = view;
1976 b = theBufferList().next(b);
1980 GuiView * const homeView = currentView();
1981 Buffer * b = theBufferList().first();
1982 Buffer * nextBuf = 0;
1983 int numProcessed = 0;
1986 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1988 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1990 // first change to a view where b is locally visible, preferably current_view_.
1991 GuiView * const vLv = views_lVisible[b];
1993 lyx::dispatch(funcToRun);
2001 // put things back to how they were (if possible).
2002 for (GuiView * view : allViews) {
2003 Buffer * originalBuf = activeBuffers[view];
2004 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2005 if (theBufferList().isLoaded(originalBuf))
2006 view->setBuffer(originalBuf);
2008 homeView->setFocus();
2010 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2014 case LFUN_COMMAND_ALTERNATIVES: {
2015 // argument contains ';'-terminated commands
2016 string arg = argument;
2017 while (!arg.empty()) {
2019 arg = split(arg, first, ';');
2020 FuncRequest func(lyxaction.lookupFunc(first));
2021 func.setOrigin(cmd.origin());
2022 FuncStatus const stat = getStatus(func);
2023 if (stat.enabled()) {
2033 if (theTopLevelCmdDef().lock(argument, func)) {
2034 func.setOrigin(cmd.origin());
2036 theTopLevelCmdDef().release(argument);
2038 if (func.action() == LFUN_UNKNOWN_ACTION) {
2039 // unknown command definition
2040 lyxerr << "Warning: unknown command definition `"
2044 // recursion detected
2045 lyxerr << "Warning: Recursion in the command definition `"
2046 << argument << "' detected"
2054 string const lfun = cmd.getLongArg(1);
2055 FuncRequest func(lyxaction.lookupFunc(cmd.getLongArg(1)));
2056 func.setOrigin(cmd.origin());
2057 FuncStatus const stat = getStatus(func);
2058 if (stat.enabled()) {
2065 case LFUN_IF_RELATIVES: {
2066 string const lfun = to_utf8(cmd.argument());
2067 FuncRequest func(lyxaction.lookupFunc(lfun));
2068 func.setOrigin(cmd.origin());
2069 FuncStatus const stat = getStatus(func);
2070 if (stat.enabled()) {
2077 case LFUN_PREFERENCES_SAVE:
2078 lyxrc.write(support::makeAbsPath("preferences",
2079 package().user_support().absFileName()), false);
2082 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2083 string const fname = addName(addPath(package().user_support().absFileName(),
2084 "templates/"), "defaults.lyx");
2085 Buffer defaults(fname);
2087 istringstream ss(argument);
2092 // We need to make sure that, after we recreat the DocumentClass,
2093 // which we do in readHeader, we apply it to the document itself.
2094 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2095 int const unknown_tokens = defaults.readHeader(lex);
2096 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2098 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2099 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2101 if (unknown_tokens != 0) {
2102 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2103 << unknown_tokens << " unknown token"
2104 << (unknown_tokens == 1 ? "" : "s")
2108 if (defaults.writeFile(FileName(defaults.absFileName())))
2109 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2110 makeDisplayPath(fname)));
2113 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2118 case LFUN_BOOKMARK_GOTO:
2119 // go to bookmark, open unopened file and switch to buffer if necessary
2120 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2121 dr.screenUpdate(Update::Force | Update::FitCursor);
2124 case LFUN_BOOKMARK_CLEAR:
2125 theSession().bookmarks().clear();
2128 case LFUN_DEBUG_LEVEL_SET:
2129 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2132 case LFUN_DIALOG_SHOW: {
2133 string const name = cmd.getArg(0);
2135 if ( name == "aboutlyx"
2137 || name == "texinfo"
2138 || name == "progress"
2139 || name == "compare")
2141 // work around: on Mac OS the application
2142 // is not terminated when closing the last view.
2143 // Create a new one to be able to dispatch the
2144 // LFUN_DIALOG_SHOW to this view.
2145 if (current_view_ == 0)
2151 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2154 current_view_->dispatch(cmd, dr);
2158 if (cmd.origin() == FuncRequest::LYXSERVER)
2159 updateCurrentView(cmd, dr);
2163 docstring GuiApplication::viewStatusMessage()
2165 // When meta-fake key is pressed, show the key sequence so far + "M-".
2166 if (d->meta_fake_bit != NoModifier)
2167 return d->keyseq.print(KeySequence::ForGui) + "M-";
2169 // Else, when a non-complete key sequence is pressed,
2170 // show the available options.
2171 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2172 return d->keyseq.printOptions(true);
2178 string GuiApplication::inputLanguageCode() const
2180 #if (QT_VERSION < 0x050000)
2181 QLocale loc = keyboardInputLocale();
2183 QLocale loc = inputMethod()->locale();
2185 //LYXERR0("input lang = " << fromqstr(loc.name()));
2186 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2190 void GuiApplication::onLocaleChanged()
2192 //LYXERR0("Change language to " << inputLanguage()->lang());
2193 if (currentView() && currentView()->currentBufferView())
2194 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2198 void GuiApplication::handleKeyFunc(FuncCode action)
2202 if (d->keyseq.length())
2204 GuiView * gv = currentView();
2205 LASSERT(gv && gv->currentBufferView(), return);
2206 BufferView * bv = gv->currentBufferView();
2207 bv->getIntl().getTransManager().deadkey(
2208 c, get_accent(action).accent, bv->cursor().innerText(),
2210 // Need to clear, in case the minibuffer calls these
2213 // copied verbatim from do_accent_char
2214 bv->cursor().resetAnchor();
2218 //Keep this in sync with GuiApplication::processKeySym below
2219 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2220 KeyModifier state) const
2222 // Do nothing if we have nothing
2223 if (!keysym.isOK() || keysym.isModifier())
2225 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2227 FuncRequest func = seq.addkey(keysym, state);
2228 // When not cancel or meta-fake, do the normal lookup.
2229 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2231 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2233 // Maybe user can only reach the key via holding down shift.
2234 // Let's see. But only if shift is the only modifier
2235 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2236 // If addkey looked up a command and did not find further commands then
2237 // seq has been reset at this point
2238 func = seq.addkey(keysym, NoModifier);
2240 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2241 << seq.print(KeySequence::Portable) << ']');
2242 return func.action() != LFUN_UNKNOWN_ACTION;
2246 //Keep this in sync with GuiApplication::queryKeySym above
2247 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2249 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2251 // Do nothing if we have nothing (JMarc)
2252 if (!keysym.isOK() || keysym.isModifier()) {
2254 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2256 current_view_->restartCaret();
2260 char_type encoded_last_key = keysym.getUCSEncoded();
2262 // Do a one-deep top-level lookup for
2263 // cancel and meta-fake keys. RVDK_PATCH_5
2264 d->cancel_meta_seq.reset();
2266 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2267 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2269 // When not cancel or meta-fake, do the normal lookup.
2270 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2271 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2272 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2273 // remove Caps Lock and Mod2 as a modifiers
2274 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2275 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2278 // Dont remove this unless you know what you are doing.
2279 d->meta_fake_bit = NoModifier;
2281 // Can this happen now ?
2282 if (func.action() == LFUN_NOACTION)
2283 func = FuncRequest(LFUN_COMMAND_PREFIX);
2285 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2286 << d->keyseq.print(KeySequence::Portable) << ']');
2288 // already here we know if it any point in going further
2289 // why not return already here if action == -1 and
2290 // num_bytes == 0? (Lgb)
2292 if (d->keyseq.length() > 1 && current_view_)
2293 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2296 // Maybe user can only reach the key via holding down shift.
2297 // Let's see. But only if shift is the only modifier
2298 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2299 LYXERR(Debug::KEY, "Trying without shift");
2300 // If addkey looked up a command and did not find further commands then
2301 // seq has been reset at this point
2302 func = d->keyseq.addkey(keysym, NoModifier);
2303 LYXERR(Debug::KEY, "Action now " << func.action());
2306 if (func.action() == LFUN_UNKNOWN_ACTION) {
2307 // We didn't match any of the key sequences.
2308 // See if it's normal insertable text not already
2309 // covered by a binding
2310 if (keysym.isText() && d->keyseq.length() == 1) {
2311 // Non-printable characters (such as ASCII control characters)
2312 // must not be inserted (#5704)
2313 if (!isPrintable(encoded_last_key)) {
2314 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2316 current_view_->restartCaret();
2319 // The following modifier check is not needed on Mac.
2320 // The keysym is either not text or it is different
2321 // from the non-modifier keysym. See #9875 for the
2322 // broken alt-modifier effect of having this code active.
2323 #if !defined(Q_OS_MAC)
2324 // If a non-Shift Modifier is used we have a non-bound key sequence
2325 // (such as Alt+j = j). This should be omitted (#5575).
2326 // On Windows, AltModifier and ControlModifier are both
2327 // set when AltGr is pressed. Therefore, in order to not
2328 // break AltGr-bound symbols (see #5575 for details),
2329 // unbound Ctrl+Alt key sequences are allowed.
2330 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2331 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2332 && !(state & AltModifier && state & ControlModifier)
2336 if (current_view_) {
2337 current_view_->message(_("Unknown function."));
2338 current_view_->restartCaret();
2343 // Since all checks above were passed, we now really have text that
2344 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2345 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2347 LYXERR(Debug::KEY, "isText() is true, inserting.");
2348 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2350 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2351 if (current_view_) {
2352 current_view_->message(_("Unknown function."));
2353 current_view_->restartCaret();
2359 if (func.action() == LFUN_SELF_INSERT) {
2360 if (encoded_last_key != 0) {
2361 docstring const arg(1, encoded_last_key);
2362 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2363 FuncRequest::KEYBOARD));
2364 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2367 processFuncRequest(func);
2371 void GuiApplication::processFuncRequest(FuncRequest const & func)
2373 lyx::dispatch(func);
2377 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2379 addToFuncRequestQueue(func);
2380 processFuncRequestQueueAsync();
2384 void GuiApplication::processFuncRequestQueue()
2386 while (!d->func_request_queue_.empty()) {
2387 // take the item from the stack _before_ processing the
2388 // request in order to avoid race conditions from nested
2389 // or parallel requests (see #10406)
2390 FuncRequest const fr(d->func_request_queue_.front());
2391 d->func_request_queue_.pop();
2392 processFuncRequest(fr);
2397 void GuiApplication::processFuncRequestQueueAsync()
2399 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2403 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2405 d->func_request_queue_.push(func);
2409 void GuiApplication::resetGui()
2411 // Set the language defined by the user.
2415 if (!readUIFile(toqstr(lyxrc.ui_file)))
2416 // Gives some error box here.
2419 if (d->global_menubar_)
2420 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2422 QHash<int, GuiView *>::iterator it;
2423 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2426 gv->setLayoutDirection(layoutDirection());
2430 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2434 void GuiApplication::createView(int view_id)
2436 createView(QString(), true, view_id);
2440 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2443 // release the keyboard which might have been grabed by the global
2444 // menubar on Mac to catch shortcuts even without any GuiView.
2445 if (d->global_menubar_)
2446 d->global_menubar_->releaseKeyboard();
2450 while (d->views_.find(id) != d->views_.end())
2453 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2454 GuiView * view = new GuiView(id);
2455 // `view' is the new current_view_. Tell coverity that is is not 0.
2456 LATTEST(current_view_);
2458 d->views_[id] = view;
2462 setActiveWindow(view);
2465 if (!geometry_arg.isEmpty()) {
2466 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2470 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2471 re.indexIn(geometry_arg);
2472 w = re.cap(1).toInt();
2473 h = re.cap(2).toInt();
2474 x = re.cap(3).toInt();
2475 y = re.cap(4).toInt();
2476 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2477 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2478 // Set initial geometry such that we can get the frame size.
2479 view->setGeometry(x, y, w, h);
2480 int framewidth = view->geometry().x() - view->x();
2481 int titleheight = view->geometry().y() - view->y();
2482 // Negative displacements must be interpreted as distances
2483 // from the right or bottom screen borders.
2484 if (sx == '-' || sy == '-') {
2485 QRect rec = QApplication::desktop()->screenGeometry();
2487 x += rec.width() - w - framewidth;
2489 y += rec.height() - h - titleheight;
2490 view->setGeometry(x, y, w, h);
2492 // Make sure that the left and top frame borders are visible.
2493 if (view->x() < 0 || view->y() < 0) {
2498 view->setGeometry(x, y, w, h);
2506 bool GuiApplication::unhide(Buffer * buf)
2510 currentView()->setBuffer(buf, false);
2515 Clipboard & GuiApplication::clipboard()
2517 return d->clipboard_;
2521 Selection & GuiApplication::selection()
2523 return d->selection_;
2527 FontLoader & GuiApplication::fontLoader()
2529 return d->font_loader_;
2533 Toolbars const & GuiApplication::toolbars() const
2535 return d->toolbars_;
2539 Toolbars & GuiApplication::toolbars()
2541 return d->toolbars_;
2545 Menus const & GuiApplication::menus() const
2551 Menus & GuiApplication::menus()
2557 QList<int> GuiApplication::viewIds() const
2559 return d->views_.keys();
2563 ColorCache & GuiApplication::colorCache()
2565 return d->color_cache_;
2569 int GuiApplication::exec()
2571 // asynchronously handle batch commands. This event will be in
2572 // the event queue in front of other asynchronous events. Hence,
2573 // we can assume in the latter that the gui is setup already.
2574 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2576 return QApplication::exec();
2580 void GuiApplication::exit(int status)
2582 QApplication::exit(status);
2586 void GuiApplication::setGuiLanguage()
2590 // install translation file for Qt built-in dialogs
2591 QString const language_name = QString("qt_") + theLocale.name();
2592 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2593 // Short-named translator can be loaded from a long name, but not the
2594 // opposite. Therefore, long name should be used without truncation.
2595 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2596 if (!d->qt_trans_.load(language_name,
2597 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2598 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2601 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2605 switch (theLocale.language()) {
2606 case QLocale::Arabic :
2607 case QLocale::Hebrew :
2608 case QLocale::Persian :
2609 case QLocale::Urdu :
2610 setLayoutDirection(Qt::RightToLeft);
2613 setLayoutDirection(Qt::LeftToRight);
2618 void GuiApplication::execBatchCommands()
2623 if (!readUIFile(toqstr(lyxrc.ui_file)))
2624 // Gives some error box here.
2628 #if QT_VERSION > 0x040600
2629 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2631 #if QT_VERSION > 0x050100
2632 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2634 // Create the global default menubar which is shown for the dialogs
2635 // and if no GuiView is visible.
2636 // This must be done after the session was recovered to know the "last files".
2637 d->global_menubar_ = new QMenuBar(0);
2638 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2641 lyx::execBatchCommands();
2645 QAbstractItemModel * GuiApplication::languageModel()
2647 if (d->language_model_)
2648 return d->language_model_;
2650 QStandardItemModel * lang_model = new QStandardItemModel(this);
2651 lang_model->insertColumns(0, 3);
2652 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2653 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2654 Languages::const_iterator it = lyx::languages.begin();
2655 Languages::const_iterator end = lyx::languages.end();
2656 for (; it != end; ++it) {
2657 int current_row = lang_model->rowCount();
2658 lang_model->insertRows(current_row, 1);
2659 QModelIndex pl_item = lang_model->index(current_row, 0);
2660 QModelIndex sp_item = lang_model->index(current_row, 1);
2661 QModelIndex th_item = lang_model->index(current_row, 2);
2662 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2663 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2664 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2665 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2666 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2667 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2668 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2669 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2670 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2671 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2673 d->language_model_ = new QSortFilterProxyModel(this);
2674 d->language_model_->setSourceModel(lang_model);
2675 d->language_model_->setSortLocaleAware(true);
2676 return d->language_model_;
2680 void GuiApplication::restoreGuiSession()
2682 if (!lyxrc.load_session)
2685 Session & session = theSession();
2686 LastOpenedSection::LastOpened const & lastopened =
2687 session.lastOpened().getfiles();
2689 validateCurrentView();
2691 FileName active_file;
2692 // do not add to the lastfile list since these files are restored from
2693 // last session, and should be already there (regular files), or should
2694 // not be added at all (help files).
2695 for (size_t i = 0; i < lastopened.size(); ++i) {
2696 FileName const & file_name = lastopened[i].file_name;
2697 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2698 && current_view_->documentBufferView() != 0)) {
2699 boost::crc_32_type crc;
2700 string const & fname = file_name.absFileName();
2701 crc = for_each(fname.begin(), fname.end(), crc);
2702 createView(crc.checksum());
2704 current_view_->loadDocument(file_name, false);
2706 if (lastopened[i].active)
2707 active_file = file_name;
2710 // Restore last active buffer
2711 Buffer * buffer = theBufferList().getBuffer(active_file);
2712 if (buffer && current_view_)
2713 current_view_->setBuffer(buffer);
2715 // clear this list to save a few bytes of RAM
2716 session.lastOpened().clear();
2720 QString const GuiApplication::romanFontName()
2723 font.setStyleHint(QFont::Serif);
2724 font.setFamily("serif");
2726 return QFontInfo(font).family();
2730 QString const GuiApplication::sansFontName()
2733 font.setStyleHint(QFont::SansSerif);
2734 font.setFamily("sans");
2736 return QFontInfo(font).family();
2740 QString const GuiApplication::typewriterFontName()
2742 return QFontInfo(typewriterSystemFont()).family();
2747 // We cannot use QFont::fixedPitch() because it doesn't
2748 // return the fact but only if it is requested.
2749 static bool isFixedPitch(const QFont & font) {
2750 const QFontInfo fi(font);
2751 return fi.fixedPitch();
2756 QFont const GuiApplication::typewriterSystemFont()
2758 #if QT_VERSION >= 0x050200
2759 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2761 QFont font("monospace");
2763 if (!isFixedPitch(font)) {
2764 // try to enforce a real monospaced font
2765 font.setStyleHint(QFont::Monospace);
2766 if (!isFixedPitch(font)) {
2767 font.setStyleHint(QFont::TypeWriter);
2768 if (!isFixedPitch(font)) font.setFamily("courier");
2772 // On a Mac the result is too small and it's not practical to
2773 // rely on Qtconfig utility to change the system settings of Qt.
2774 font.setPointSize(12);
2780 void GuiApplication::handleRegularEvents()
2782 ForkedCallsController::handleCompletedProcesses();
2786 bool GuiApplication::event(QEvent * e)
2789 case QEvent::FileOpen: {
2790 // Open a file; this happens only on Mac OS X for now.
2792 // We do this asynchronously because on startup the batch
2793 // commands are not executed here yet and the gui is not ready
2795 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2796 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2797 processFuncRequestAsync(fr);
2801 #if (QT_VERSION < 0x050000)
2802 // Qt5 uses a signal for that, see above.
2803 case QEvent::KeyboardLayoutChange:
2804 //LYXERR0("keyboard change");
2805 if (currentView() && currentView()->currentBufferView())
2806 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2811 return QApplication::event(e);
2816 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2819 return QApplication::notify(receiver, event);
2821 catch (ExceptionMessage const & e) {
2823 case ErrorException:
2825 setQuitOnLastWindowClosed(false);
2827 Alert::error(e.title_, e.details_);
2829 // Properly crash in debug mode in order to get a useful backtrace.
2832 // In release mode, try to exit gracefully.
2834 // FIXME: GCC 7 thinks we can fall through here. Can we?
2836 case BufferException: {
2837 if (!current_view_ || !current_view_->documentBufferView())
2839 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2840 docstring details = e.details_ + '\n';
2841 details += buf->emergencyWrite();
2842 theBufferList().release(buf);
2843 details += "\n" + _("The current document was closed.");
2844 Alert::error(e.title_, details);
2847 case WarningException:
2848 Alert::warning(e.title_, e.details_);
2852 catch (exception const & e) {
2853 docstring s = _("LyX has caught an exception, it will now "
2854 "attempt to save all unsaved documents and exit."
2856 s += from_ascii(e.what());
2857 Alert::error(_("Software exception Detected"), s);
2861 docstring s = _("LyX has caught some really weird exception, it will "
2862 "now attempt to save all unsaved documents and exit.");
2863 Alert::error(_("Software exception Detected"), s);
2871 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2873 QColor const & qcol = d->color_cache_.get(col);
2874 if (!qcol.isValid()) {
2880 rgbcol.r = qcol.red();
2881 rgbcol.g = qcol.green();
2882 rgbcol.b = qcol.blue();
2887 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2889 QColor const qcol(lcolor.getX11Name(col).c_str());
2890 if (!qcol.isValid()) {
2896 rgbcol.r = qcol.red();
2897 rgbcol.g = qcol.green();
2898 rgbcol.b = qcol.blue();
2903 string const GuiApplication::hexName(ColorCode col)
2905 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2909 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2911 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2912 d->socket_notifiers_[fd] = sn;
2913 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2917 void GuiApplication::socketDataReceived(int fd)
2919 d->socket_notifiers_[fd]->func_();
2923 void GuiApplication::unregisterSocketCallback(int fd)
2925 d->socket_notifiers_.take(fd)->setEnabled(false);
2929 void GuiApplication::commitData(QSessionManager & sm)
2931 /** The implementation is required to avoid an application exit
2932 ** when session state save is triggered by session manager.
2933 ** The default implementation sends a close event to all
2934 ** visible top level widgets when session managment allows
2936 ** We are changing that to check the state of each buffer in all
2937 ** views and ask the users what to do if buffers are dirty.
2938 ** Furthermore, we save the session state.
2939 ** We do NOT close the views here since the user still can cancel
2940 ** the logout process (see #9277); also, this would hide LyX from
2941 ** an OSes own session handling (application restoration).
2943 #ifdef QT_NO_SESSIONMANAGER
2945 #warning Qt is compiled without session manager
2947 #pragma message("warning: Qt is compiled without session manager")
2951 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2959 void GuiApplication::unregisterView(GuiView * gv)
2961 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2962 d->views_.remove(gv->id());
2963 if (current_view_ == gv)
2969 bool GuiApplication::closeAllViews()
2971 if (d->views_.empty())
2974 // When a view/window was closed before without quitting LyX, there
2975 // are already entries in the lastOpened list.
2976 theSession().lastOpened().clear();
2978 QList<GuiView *> const views = d->views_.values();
2979 for (GuiView * view : views) {
2980 if (!view->closeScheduled())
2989 bool GuiApplication::prepareAllViewsForLogout()
2991 if (d->views_.empty())
2994 QList<GuiView *> const views = d->views_.values();
2995 for (GuiView * view : views) {
2996 if (!view->prepareAllBuffersForLogout())
3004 GuiView & GuiApplication::view(int id) const
3006 LAPPERR(d->views_.contains(id));
3007 return *d->views_.value(id);
3011 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3013 QList<GuiView *> const views = d->views_.values();
3014 for (GuiView * view : views)
3015 view->hideDialog(name, inset);
3019 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3021 Buffer const * buf = 0;
3022 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3023 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3024 if (Buffer const * ptr = (*it)->updateInset(inset))
3031 bool GuiApplication::searchMenu(FuncRequest const & func,
3032 docstring_list & names) const
3034 BufferView * bv = 0;
3036 bv = current_view_->currentBufferView();
3037 return d->menus_.searchMenu(func, names, bv);
3041 bool GuiApplication::hasBufferView() const
3043 return (current_view_ && current_view_->currentBufferView());
3047 // Ensure that a file is read only once (prevents include loops)
3048 static QStringList uifiles;
3049 // store which ui files define Toolbars
3050 static QStringList toolbar_uifiles;
3053 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
3064 LexerKeyword uitags[] = {
3065 { "format", ui_format },
3066 { "include", ui_include },
3067 { "menuset", ui_menuset },
3068 { "toolbars", ui_toolbars },
3069 { "toolbarset", ui_toolbarset }
3073 lex.setFile(ui_path);
3075 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3079 if (lyxerr.debugging(Debug::PARSER))
3080 lex.printTable(lyxerr);
3083 // format before introduction of format tag
3084 unsigned int format = 0;
3085 while (lex.isOK()) {
3086 int const status = lex.lex();
3088 // we have to do this check here, outside the switch,
3089 // because otherwise we would start reading include files,
3090 // e.g., if the first tag we hit was an include tag.
3091 if (status == ui_format)
3093 format = lex.getInteger();
3097 // this will trigger unless the first tag we hit is a format
3098 // tag, with the right format.
3099 if (format != LFUN_FORMAT)
3100 return FormatMismatch;
3103 case Lexer::LEX_FEOF:
3108 QString const file = toqstr(lex.getString());
3109 bool const success = readUIFile(file, true);
3111 LYXERR0("Failed to read included file: " << fromqstr(file));
3118 d->menus_.read(lex);
3122 d->toolbars_.readToolbars(lex);
3126 d->toolbars_.readToolbarSettings(lex);
3127 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3131 if (!rtrim(lex.getString()).empty())
3132 lex.printError("LyX::ReadUIFile: "
3133 "Unknown menu tag: `$$Token'");
3135 LYXERR0("Error with status: " << status);
3141 return (error ? ReadError : ReadOK);
3145 bool GuiApplication::readUIFile(QString const & name, bool include)
3147 LYXERR(Debug::INIT, "About to read " << name << "...");
3151 ui_path = libFileSearch("ui", name, "inc");
3152 if (ui_path.empty())
3153 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3155 ui_path = libFileSearch("ui", name, "ui");
3158 if (ui_path.empty()) {
3159 static const QString defaultUIFile = "default";
3160 LYXERR(Debug::INIT, "Could not find " << name);
3162 Alert::warning(_("Could not find UI definition file"),
3163 bformat(_("Error while reading the included file\n%1$s\n"
3164 "Please check your installation."), qstring_to_ucs4(name)));
3167 if (name == defaultUIFile) {
3168 LYXERR(Debug::INIT, "Could not find default UI file!!");
3169 Alert::warning(_("Could not find default UI file"),
3170 _("LyX could not find the default UI file!\n"
3171 "Please check your installation."));
3174 Alert::warning(_("Could not find UI definition file"),
3175 bformat(_("Error while reading the configuration file\n%1$s\n"
3176 "Falling back to default.\n"
3177 "Please look under Tools>Preferences>User Interface and\n"
3178 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3179 return readUIFile(defaultUIFile, false);
3182 QString const uifile = toqstr(ui_path.absFileName());
3183 if (uifiles.contains(uifile)) {
3185 // We are reading again the top uifile so reset the safeguard:
3188 d->toolbars_.reset();
3190 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3191 << "Is this an include loop?");
3195 uifiles.push_back(uifile);
3197 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3199 ReturnValues retval = readUIFile(ui_path);
3201 if (retval == FormatMismatch) {
3202 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3203 TempFile tmp("convertXXXXXX.ui");
3204 FileName const tempfile = tmp.name();
3205 bool const success = prefs2prefs(ui_path, tempfile, true);
3207 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3208 " to format " << LFUN_FORMAT << ".");
3210 retval = readUIFile(tempfile);
3214 if (retval != ReadOK) {
3215 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3223 settings.beginGroup("ui_files");
3224 bool touched = false;
3225 for (int i = 0; i != uifiles.size(); ++i) {
3226 QFileInfo fi(uifiles[i]);
3227 QDateTime const date_value = fi.lastModified();
3228 QString const name_key = QString::number(i);
3229 // if an ui file which defines Toolbars has changed,
3230 // we have to reset the settings
3231 if (toolbar_uifiles.contains(uifiles[i])
3232 && (!settings.contains(name_key)
3233 || settings.value(name_key).toString() != uifiles[i]
3234 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3236 settings.setValue(name_key, uifiles[i]);
3237 settings.setValue(name_key + "/date", date_value);
3240 settings.endGroup();
3242 settings.remove("views");
3248 void GuiApplication::onLastWindowClosed()
3250 if (d->global_menubar_)
3251 d->global_menubar_->grabKeyboard();
3255 void GuiApplication::startLongOperation() {
3256 d->key_checker_.start();
3260 bool GuiApplication::longOperationCancelled() {
3261 return d->key_checker_.pressed();
3265 void GuiApplication::stopLongOperation() {
3266 d->key_checker_.stop();
3270 bool GuiApplication::longOperationStarted() {
3271 return d->key_checker_.started();
3275 ////////////////////////////////////////////////////////////////////////
3277 // X11 specific stuff goes here...
3280 bool GuiApplication::x11EventFilter(XEvent * xev)
3285 switch (xev->type) {
3286 case SelectionRequest: {
3287 if (xev->xselectionrequest.selection != XA_PRIMARY)
3289 LYXERR(Debug::SELECTION, "X requested selection.");
3290 BufferView * bv = current_view_->currentBufferView();
3292 docstring const sel = bv->requestSelection();
3294 d->selection_.put(sel);
3295 // Refresh the selection request timestamp.
3296 // We have to do this by ourselves as Qt seems
3297 // not doing that, maybe because of our
3298 // "persistent selection" implementation
3299 // (see comments in GuiSelection.cpp).
3300 XSelectionEvent nev;
3301 nev.type = SelectionNotify;
3302 nev.display = xev->xselectionrequest.display;
3303 nev.requestor = xev->xselectionrequest.requestor;
3304 nev.selection = xev->xselectionrequest.selection;
3305 nev.target = xev->xselectionrequest.target;
3306 nev.property = 0L; // None
3307 nev.time = CurrentTime;
3308 XSendEvent(QX11Info::display(),
3309 nev.requestor, False, 0,
3310 reinterpret_cast<XEvent *>(&nev));
3316 case SelectionClear: {
3317 if (xev->xselectionclear.selection != XA_PRIMARY)
3319 LYXERR(Debug::SELECTION, "Lost selection.");
3320 BufferView * bv = current_view_->currentBufferView();
3322 bv->clearSelection();
3328 #elif defined(QPA_XCB)
3329 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3330 void * message, long *)
3332 if (!current_view_ || eventType != "xcb_generic_event_t")
3335 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3337 switch (ev->response_type) {
3338 case XCB_SELECTION_REQUEST: {
3339 xcb_selection_request_event_t * srev =
3340 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3341 if (srev->selection != XCB_ATOM_PRIMARY)
3343 LYXERR(Debug::SELECTION, "X requested selection.");
3344 BufferView * bv = current_view_->currentBufferView();
3346 docstring const sel = bv->requestSelection();
3348 d->selection_.put(sel);
3349 #ifdef HAVE_QT5_X11_EXTRAS
3350 // Refresh the selection request timestamp.
3351 // We have to do this by ourselves as Qt seems
3352 // not doing that, maybe because of our
3353 // "persistent selection" implementation
3354 // (see comments in GuiSelection.cpp).
3355 // It is expected that every X11 event is
3356 // 32 bytes long, even if not all 32 bytes are
3358 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3359 struct alignas(32) padded_event
3360 : xcb_selection_notify_event_t {};
3361 padded_event nev = {};
3362 nev.response_type = XCB_SELECTION_NOTIFY;
3363 nev.requestor = srev->requestor;
3364 nev.selection = srev->selection;
3365 nev.target = srev->target;
3366 nev.property = XCB_NONE;
3367 nev.time = XCB_CURRENT_TIME;
3368 xcb_connection_t * con = QX11Info::connection();
3369 xcb_send_event(con, 0, srev->requestor,
3370 XCB_EVENT_MASK_NO_EVENT,
3371 reinterpret_cast<char const *>(&nev));
3379 case XCB_SELECTION_CLEAR: {
3380 xcb_selection_clear_event_t * scev =
3381 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3382 if (scev->selection != XCB_ATOM_PRIMARY)
3384 LYXERR(Debug::SELECTION, "Lost selection.");
3385 BufferView * bv = current_view_->currentBufferView();
3387 bv->clearSelection();
3395 } // namespace frontend
3398 void hideDialogs(std::string const & name, Inset * inset)
3401 frontend::guiApp->hideDialogs(name, inset);
3405 ////////////////////////////////////////////////////////////////////
3409 ////////////////////////////////////////////////////////////////////
3411 frontend::FontLoader & theFontLoader()
3413 LAPPERR(frontend::guiApp);
3414 return frontend::guiApp->fontLoader();
3418 frontend::FontMetrics const & theFontMetrics(Font const & f)
3420 return theFontMetrics(f.fontInfo());
3424 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3426 LAPPERR(frontend::guiApp);
3427 return frontend::guiApp->fontLoader().metrics(f);
3431 ////////////////////////////////////////////////////////////////////
3435 ////////////////////////////////////////////////////////////////////
3437 frontend::Clipboard & theClipboard()
3439 LAPPERR(frontend::guiApp);
3440 return frontend::guiApp->clipboard();
3444 frontend::Selection & theSelection()
3446 LAPPERR(frontend::guiApp);
3447 return frontend::guiApp->selection();
3453 #include "moc_GuiApplication.cpp"