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/textutils.h"
74 #include "support/Messages.h"
75 #include "support/os.h"
76 #include "support/Package.h"
77 #include "support/TempFile.h"
80 #include "support/AppleScript.h"
81 #include "support/linkback/LinkBackProxy.h"
89 #include <QDesktopWidget>
92 #include <QFileOpenEvent>
94 #include <QFontDatabase>
97 #include <QImageReader>
100 #include <QLibraryInfo>
107 #include <QSessionManager>
109 #include <QSocketNotifier>
110 #include <QSortFilterProxyModel>
111 #include <QStandardItemModel>
113 #include <QTranslator>
114 #include <QThreadPool>
118 #include <X11/Xatom.h>
119 #include <X11/Xlib.h>
123 #elif defined(QPA_XCB)
125 #ifdef HAVE_QT5_X11_EXTRAS
126 #include <QtX11Extras/QX11Info>
130 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
131 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
132 #if (QT_VERSION < 0x050000)
133 #include <QWindowsMime>
134 #define QWINDOWSMIME QWindowsMime
137 #define QWINDOWSMIME QWinMime
147 #include <QMacPasteboardMime>
150 #include <boost/crc.hpp>
157 using namespace lyx::support;
162 frontend::Application * createApplication(int & argc, char * argv[])
164 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
165 // prune -geometry argument(s) by shifting
166 // the following ones 2 places down.
167 for (int i = 0 ; i < argc ; ++i) {
168 if (strcmp(argv[i], "-geometry") == 0) {
169 int const remove = (i+1) < argc ? 2 : 1;
171 for (int j = i; j < argc; ++j)
172 argv[j] = argv[j + remove];
178 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
179 // On Windows, allow bringing the LyX window to top
180 AllowSetForegroundWindow(ASFW_ANY);
183 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
184 // I'd rather do that in the constructor, but I do not think that
185 // the palette is accessible there.
186 guiApp->colorCache().setPalette(guiApp->palette());
195 if (lyxrc.gui_language == "auto") {
196 theLocale = QLocale::system();
197 code = fromqstr(theLocale.name());
199 Language const * l = languages.getLanguage(lyxrc.gui_language);
200 code = l ? l->code() : "C";
201 theLocale = QLocale(toqstr(code));
203 // Qt tries to outsmart us and transforms en_US to C.
204 Messages::guiLanguage((code == "C") ? "en_US" : code);
205 QLocale::setDefault(theLocale);
206 setlocale(LC_NUMERIC, "C");
213 /// Return the list of loadable formats.
214 vector<string> loadableImageFormats()
218 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
220 LYXERR(Debug::GRAPHICS,
221 "\nThe image loader can load the following directly:\n");
223 if (qt_formats.empty())
224 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
226 bool jpeg_found = false;
227 bool jpg_found = false;
228 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
230 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
232 string ext = ascii_lowercase((const char *) *it);
240 else if (ext == "jpg") {
245 else if (lyxrc.use_converter_cache &&
246 (ext == "svg" || ext == "svgz") &&
247 theConverters().isReachable("svg", "png"))
248 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
249 // the SVG as in the output. However we require that the converter
250 // cache is enabled since this is expensive. We also require that
251 // an explicit svg->png converter is defined, since the default
252 // converter could produce bad quality as well. This assumes that
253 // png can always be loaded.
262 ////////////////////////////////////////////////////////////////////////
264 // Icon loading support code
266 ////////////////////////////////////////////////////////////////////////
276 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
278 return lhs.key < rhs.key;
284 CompareKey(QString const & name) : name_(name) {}
285 bool operator()(ImgMap const & other) const { return other.key == name_; }
291 // this must be sorted alphabetically
292 // Upper case comes before lower case
293 // Please don't change the formatting, this list is parsed by
294 // development/tools/generate_symbols_images.py.
295 ImgMap sorted_img_map[] = {
296 { "Arrownot", "arrownot2"},
297 { "Arrowvert", "arrowvert2"},
298 { "Bowtie", "bowtie2" },
300 { "Bumpeq", "bumpeq2" },
301 { "CIRCLE", "circle3" },
303 { "CheckedBox", "checkedbox2" },
304 { "Circle", "circle2" },
305 { "Colonapprox", "colonapprox2" },
306 { "Coloneq", "coloneq2" },
307 { "Coloneqq", "coloneqq2" },
308 { "Colonsim", "colonsim2" },
310 { "DOWNarrow", "downarrow3" },
311 { "Delta", "delta2" },
312 { "Diamond", "diamond2" },
313 { "Doteq", "doteq2" },
314 { "Downarrow", "downarrow2" },
315 { "Eqcolon", "eqcolon2" },
316 { "Eqqcolon", "eqqcolon2" },
317 { "Gamma", "gamma2" },
319 { "LEFTCIRCLE", "leftcircle3" },
320 { "LEFTarrow", "leftarrow3" },
321 { "LEFTcircle", "leftcircle4" },
323 { "Lambda", "lambda2" },
325 { "Leftarrow", "leftarrow2" },
326 { "Leftcircle", "leftcircle2" },
327 { "Leftrightarrow", "leftrightarrow2" },
328 { "Longarrownot", "longarrownot2"},
329 { "Longleftarrow", "longleftarrow2" },
330 { "Longleftrightarrow", "longleftrightarrow2" },
331 { "Longmapsfrom", "longmapsfrom2"},
332 { "Longmapsto", "longmapsto2"},
333 { "Longrightarrow", "longrightarrow2" },
334 { "Mapsfrom", "mapsfrom2"},
335 { "Mapsfromchar", "mapsfromchar2"},
336 { "Mapsto", "mapsto2"},
337 { "Mapstochar", "mapstochar2"},
338 { "Omega", "omega2" },
343 { "RIGHTCIRCLE", "rightcircle3" },
344 { "RIGHTarrow", "rightarrow3" },
345 { "RIGHTcircle", "rightcircle4" },
347 { "Rightarrow", "rightarrow2" },
348 { "Rightcircle", "rightcircle2" },
349 { "Sigma", "sigma2" },
350 { "Square", "square2" },
351 { "Subset", "subset2" },
352 { "Supset", "supset2" },
353 { "Theta", "theta2" },
354 { "Thorn", "thorn2" },
355 { "UParrow", "uparrow3" },
356 { "Uparrow", "uparrow2" },
357 { "Updownarrow", "updownarrow2" },
358 { "Upsilon", "upsilon2" },
359 { "Vdash", "vdash3" },
364 { "lVert", "vert2" },
366 { "nLeftarrow", "nleftarrow2" },
367 { "nLeftrightarrow", "nleftrightarrow2" },
368 { "nRightarrow", "nrightarrow2" },
369 { "nVDash", "nvdash3" },
370 { "nVdash", "nvdash4" },
371 { "nvDash", "nvdash2" },
372 { "rVert", "vert2" },
374 { "textrm \\AA", "textrm_AA"},
375 { "textrm \\O", "textrm_O"},
376 { "vDash", "vdash2" },
377 { "varDelta", "vardelta2" },
378 { "varGamma", "vargamma2" },
379 { "varLambda", "varlambda2" },
380 { "varOmega", "varomega2" },
381 { "varPhi", "varphi2" },
382 { "varPi", "varpi2" },
383 { "varPsi", "varpsi2" },
384 { "varSigma", "varsigma2" },
385 { "varTheta", "vartheta2" },
386 { "varUpsilon", "varupsilon2" },
387 { "varXi", "varxi2" }
391 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
393 // This list specifies which system's theme icon is related to which lyx
394 // command. It was based on:
395 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
396 // this must be sorted alphabetically
397 // Upper case comes before lower case
398 ImgMap sorted_theme_icon_map[] = {
399 { "bookmark-goto 0", "go-jump" },
400 { "buffer-new", "document-new" },
401 { "buffer-write", "document-save" },
402 { "buffer-write-as", "document-save-as" },
403 { "buffer-zoom-in", "zoom-in" },
404 { "buffer-zoom-out", "zoom-out" },
405 { "copy", "edit-copy" },
406 { "cut", "edit-cut" },
407 { "depth-decrement", "format-indent-less" },
408 { "depth-increment", "format-indent-more" },
409 { "dialog-show spellchecker", "tools-check-spelling" },
410 { "dialog-show-new-inset graphics", "insert-image" },
411 { "dialog-toggle findreplaceadv", "edit-find-replace" },
412 { "file-open", "document-open" },
413 { "font-bold", "format-text-bold" },
414 { "font-ital", "format-text-italic" },
415 { "font-strikeout", "format-text-strikethrough" },
416 { "font-underline", "format-text-underline" },
417 { "lyx-quit", "application-exit" },
418 { "paste", "edit-paste" },
419 { "redo", "edit-redo" },
420 { "undo", "edit-undo" },
421 { "window-close", "window-close" },
422 { "window-new", "window-new" }
425 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
428 QString findImg(QString const & name)
430 ImgMap const * const begin = sorted_img_map;
431 ImgMap const * const end = begin + nr_sorted_img_map;
432 LATTEST(sorted(begin, end));
434 ImgMap const * const it = find_if(begin, end, CompareKey(name));
438 img_name = it->value;
441 img_name.replace('_', "underscore");
442 img_name.replace(' ', '_');
444 // This way we can have "math-delim { }" on the toolbar.
445 img_name.replace('(', "lparen");
446 img_name.replace(')', "rparen");
447 img_name.replace('[', "lbracket");
448 img_name.replace(']', "rbracket");
449 img_name.replace('{', "lbrace");
450 img_name.replace('}', "rbrace");
451 img_name.replace('|', "bars");
452 img_name.replace(',', "thinspace");
453 img_name.replace(':', "mediumspace");
454 img_name.replace(';', "thickspace");
455 img_name.replace('!', "negthinspace");
458 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
459 << "Looking for math icon called \"" << img_name << '"');
466 QString themeIconName(QString const & action)
468 ImgMap const * const begin = sorted_theme_icon_map;
469 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
470 LASSERT(sorted(begin, end), /**/);
472 ImgMap const * const it = find_if(begin, end, CompareKey(action));
480 // the returned bool is true if the icon needs to be flipped
481 pair<QString,bool> iconName(FuncRequest const & f, bool unknown, bool rtl)
484 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
486 if (!f.argument().empty()) {
487 // if there are arguments, first search an icon which name is the full thing
488 QString name = lfunname + ' ' + toqstr(f.argument());
489 name.replace(' ', '_');
490 name.replace(';', '_');
491 name.replace('\\', "backslash");
494 // then special default icon for some lfuns
495 switch (f.action()) {
496 case LFUN_MATH_INSERT:
497 names << "math/" + findImg(toqstr(f.argument()).mid(1));
499 case LFUN_MATH_DELIM:
500 case LFUN_MATH_BIGDELIM:
501 names << "math/" + findImg(toqstr(f.argument()));
504 names << "commands/" + toqstr(f.argument());
506 case LFUN_COMMAND_ALTERNATIVES: {
507 // use the first of the alternative commands
509 docstring dummy = split(f.argument(), firstcom, ';');
510 QString name1 = toqstr(firstcom);
511 name1.replace(' ', '_');
512 name1.replace(';', '_');
513 name1.replace('\\', "backslash");
522 // next thing to try is function name alone
525 // and finally maybe the unknown icon
529 search_mode const mode = theGuiApp()->imageSearchMode();
530 // The folders where icons are searched for
531 QStringList imagedirs;
532 imagedirs << "images/" << "images/ipa/";
533 // This is used to search for rtl version of icons which have the +rrtl suffix.
534 QStringList suffixes;
537 suffixes << QString();
539 for (QString const & imagedir : imagedirs)
540 for (QString const & name : names)
541 for (QString const & suffix : suffixes) {
542 QString id = imagedir;
543 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
545 return make_pair(toqstr(fname.absFileName()),
546 rtl && suffix.isEmpty());
549 LYXERR(Debug::GUI, "Cannot find icon for command \""
550 << lyxaction.getActionName(f.action())
551 << '(' << to_utf8(f.argument()) << ")\"");
553 return make_pair(QString(), false);
557 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
559 QString imagedir = path;
560 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
561 QString fpath = toqstr(fname.absFileName());
562 QPixmap pixmap = QPixmap();
564 if (pixmap.load(fpath))
567 bool const list = ext.contains(",");
568 LYXERR(Debug::GUI, "Cannot load pixmap \""
569 << path << "/" << name << "." << (list ? "{" : "") << ext
570 << (list ? "}" : "") << "\".");
576 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
578 #if (QT_VERSION >= 0x040600)
579 if (lyxrc.use_system_theme_icons) {
580 // use the icons from system theme that are available
581 QString action = toqstr(lyxaction.getActionName(f.action()));
582 if (!f.argument().empty())
583 action += " " + toqstr(f.argument());
584 QString const theme_icon = themeIconName(action);
585 if (QIcon::hasThemeIcon(theme_icon)) {
586 QIcon const thmicn = QIcon::fromTheme(theme_icon);
587 if (!thmicn.isNull())
595 tie(icon, flip) = iconName(f, unknown, rtl);
599 //LYXERR(Debug::GUI, "Found icon: " << icon);
600 QPixmap pixmap = QPixmap();
601 if (!pixmap.load(icon)) {
602 LYXERR0("Cannot load icon " << icon << ".");
607 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
609 return QIcon(pixmap);
613 ////////////////////////////////////////////////////////////////////////
615 // LyX server support code.
617 ////////////////////////////////////////////////////////////////////////
619 class SocketNotifier : public QSocketNotifier
622 /// connect a connection notification from the LyXServerSocket
623 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
624 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
628 /// The callback function
629 Application::SocketCallback func_;
633 class GuiTranslator : public QTranslator
636 GuiTranslator(QObject * parent = nullptr)
637 : QTranslator(parent)
640 virtual QString translate(const char * /* context */,
641 const char *sourceText,
642 #if QT_VERSION >= 0x050000
643 const char * /* disambiguation */ = 0, int /* n */ = -1) const
645 const char * /*comment*/ = 0) const
648 // Here we declare the strings that need to be translated from Qt own GUI
649 // This is needed to include these strings to po files
653 _("Restore Defaults");
656 // Already in po: "Cancel", "&Cancel"
657 _("Apply"); // Already in po: "&Apply"
658 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
661 docstring s = getGuiMessages().getIfFound(sourceText);
662 // This test should eventually be removed when translations are updated
664 LYXERR(Debug::LOCALE, "Missing translation for `"
665 << string(sourceText) << "'");
671 ////////////////////////////////////////////////////////////////////////
673 // Mac specific stuff goes here...
675 ////////////////////////////////////////////////////////////////////////
678 // QMacPasteboardMimeGraphics can only be compiled on Mac.
680 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
683 QMacPasteboardMimeGraphics()
684 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
687 QString convertorName() { return "Graphics"; }
689 QString flavorFor(QString const & mime)
691 LYXERR(Debug::ACTION, "flavorFor " << mime);
692 if (mime == pdfMimeType())
693 return QLatin1String("com.adobe.pdf");
697 QString mimeFor(QString flav)
699 LYXERR(Debug::ACTION, "mimeFor " << flav);
700 if (flav == QLatin1String("com.adobe.pdf"))
701 return pdfMimeType();
705 bool canConvert(QString const & mime, QString flav)
707 return mimeFor(flav) == mime;
710 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
714 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
718 QList<QByteArray> convertFromMime(QString const & /*mime*/,
719 QVariant data, QString /*flav*/)
721 QList<QByteArray> ret;
722 ret.append(data.toByteArray());
728 ///////////////////////////////////////////////////////////////
730 // You can find more platform specific stuff at the end of this file...
732 ///////////////////////////////////////////////////////////////
734 ////////////////////////////////////////////////////////////////////////
735 // Windows specific stuff goes here...
737 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
738 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
739 // QWindowsMimeMetafile can only be compiled on Windows.
741 static FORMATETC cfFromMime(QString const & mimetype)
744 if (mimetype == emfMimeType()) {
745 formatetc.cfFormat = CF_ENHMETAFILE;
746 formatetc.tymed = TYMED_ENHMF;
747 } else if (mimetype == wmfMimeType()) {
748 formatetc.cfFormat = CF_METAFILEPICT;
749 formatetc.tymed = TYMED_MFPICT;
752 formatetc.dwAspect = DVASPECT_CONTENT;
753 formatetc.lindex = -1;
758 class QWindowsMimeMetafile : public QWINDOWSMIME {
760 QWindowsMimeMetafile() {}
762 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
763 QMimeData const * /*mimedata*/) const
768 bool canConvertToMime(QString const & mimetype,
769 IDataObject * pDataObj) const
771 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
773 FORMATETC formatetc = cfFromMime(mimetype);
774 return pDataObj->QueryGetData(&formatetc) == S_OK;
777 bool convertFromMime(FORMATETC const & /*formatetc*/,
778 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
783 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
784 QVariant::Type /*preferredType*/) const
787 if (!canConvertToMime(mimetype, pDataObj))
790 FORMATETC formatetc = cfFromMime(mimetype);
792 if (pDataObj->GetData(&formatetc, &s) != S_OK)
796 if (s.tymed == TYMED_ENHMF) {
797 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
798 data.resize(dataSize);
799 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
800 (LPBYTE)data.data());
801 } else if (s.tymed == TYMED_MFPICT) {
802 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
803 data.resize(dataSize);
804 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
805 (LPBYTE)data.data());
808 ReleaseStgMedium(&s);
814 QVector<FORMATETC> formatsForMime(QString const & mimetype,
815 QMimeData const * /*mimedata*/) const
817 QVector<FORMATETC> formats;
818 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
819 formats += cfFromMime(mimetype);
823 QString mimeForFormat(FORMATETC const & formatetc) const
825 switch (formatetc.cfFormat) {
827 return emfMimeType();
828 case CF_METAFILEPICT:
829 return wmfMimeType();
839 /// Allows to check whether ESC was pressed during a long operation
840 class KeyChecker : public QObject {
845 KeyChecker() : pressed_(false), started_(false) {}
848 QCoreApplication::instance()->installEventFilter(this);
853 QCoreApplication::instance()->removeEventFilter(this);
857 QCoreApplication::processEvents();
860 bool started() const {
863 bool eventFilter(QObject *obj, QEvent *event) {
864 LYXERR(Debug::ACTION, "Event Type: " << event->type());
865 switch (event->type()) {
869 case QEvent::UpdateRequest:
870 case QEvent::CursorChange:
871 case QEvent::ActionChanged:
872 case QEvent::EnabledChange:
873 case QEvent::SockAct:
876 case QEvent::ToolTipChange:
877 case QEvent::LayoutRequest:
878 case QEvent::MetaCall:
879 return QObject::eventFilter(obj, event);
881 // FIXME Blocking all these events is a bad idea.
882 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
883 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
891 ////////////////////////////////////////////////////////////////////////
892 // GuiApplication::Private definition and implementation.
893 ////////////////////////////////////////////////////////////////////////
895 struct GuiApplication::Private
897 Private(): language_model_(0), meta_fake_bit(NoModifier),
900 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
901 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
902 /// WMF Mime handler for Windows clipboard.
903 wmf_mime_ = new QWindowsMimeMetafile;
906 initKeySequences(&theTopLevelKeymap());
909 void initKeySequences(KeyMap * kb)
911 keyseq = KeySequence(kb, kb);
912 cancel_meta_seq = KeySequence(kb, kb);
916 QSortFilterProxyModel * language_model_;
918 GuiClipboard clipboard_;
920 GuiSelection selection_;
922 FontLoader font_loader_;
924 ColorCache color_cache_;
925 /// the built-in Qt translation mechanism
926 QTranslator qt_trans_;
927 /// LyX gettext-based translation for Qt elements
928 GuiTranslator gui_trans_;
930 QHash<int, SocketNotifier *> socket_notifiers_;
934 /// The global instance
937 /// this timer is used for any regular events one wants to
938 /// perform. at present it is used to check if forked processes
940 QTimer general_timer_;
942 /// delayed FuncRequests
943 std::queue<FuncRequest> func_request_queue_;
948 KeySequence cancel_meta_seq;
950 KeyModifier meta_fake_bit;
952 /// The result of last dispatch action
953 DispatchResult dispatch_result_;
955 /// Multiple views container.
957 * Warning: This must not be a smart pointer as the destruction of the
958 * object is handled by Qt when the view is closed
959 * \sa Qt::WA_DeleteOnClose attribute.
961 QHash<int, GuiView *> views_;
963 /// Only used on mac.
964 QMenuBar * global_menubar_;
967 /// Linkback mime handler for MacOSX.
968 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
971 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
972 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
973 /// WMF Mime handler for Windows clipboard.
974 QWindowsMimeMetafile * wmf_mime_;
978 /// Allows to check whether ESC was pressed during a long operation
979 KeyChecker key_checker_;
983 GuiApplication * guiApp;
985 GuiApplication::~GuiApplication()
988 closeAllLinkBackLinks();
994 GuiApplication::GuiApplication(int & argc, char ** argv)
995 : QApplication(argc, argv), current_view_(0),
996 d(new GuiApplication::Private)
998 QString app_name = "LyX";
999 QCoreApplication::setOrganizationName(app_name);
1000 QCoreApplication::setOrganizationDomain("lyx.org");
1001 QCoreApplication::setApplicationName(lyx_package);
1002 #if QT_VERSION >= 0x050000
1003 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1006 qsrand(QDateTime::currentDateTime().toTime_t());
1008 // Install LyX translator for missing Qt translations
1009 installTranslator(&d->gui_trans_);
1010 // Install Qt native translator for GUI elements.
1011 installTranslator(&d->qt_trans_);
1014 // Enable reception of XCB events.
1015 installNativeEventFilter(this);
1018 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1019 // lyxrc setting for this in order to let the application stay resident.
1020 // But then we need some kind of dock icon, at least on Windows.
1022 if (lyxrc.quit_on_last_window_closed)
1023 setQuitOnLastWindowClosed(false);
1026 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1027 // seems to be the default case for applications like LyX.
1028 setQuitOnLastWindowClosed(false);
1033 #if defined(Q_WS_X11) || defined(QPA_XCB)
1034 // doubleClickInterval() is 400 ms on X11 which is just too long.
1035 // On Windows and Mac OS X, the operating system's value is used.
1036 // On Microsoft Windows, calling this function sets the double
1037 // click interval for all applications. So we don't!
1038 QApplication::setDoubleClickInterval(300);
1041 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1043 // needs to be done before reading lyxrc
1045 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1049 // Initialize RC Fonts
1050 if (lyxrc.roman_font_name.empty())
1051 lyxrc.roman_font_name = fromqstr(romanFontName());
1053 if (lyxrc.sans_font_name.empty())
1054 lyxrc.sans_font_name = fromqstr(sansFontName());
1056 if (lyxrc.typewriter_font_name.empty())
1057 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1059 #if (QT_VERSION >= 0x050000)
1060 // Qt4 does this in event(), see below.
1061 // Track change of keyboard
1062 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1065 d->general_timer_.setInterval(500);
1066 connect(&d->general_timer_, SIGNAL(timeout()),
1067 this, SLOT(handleRegularEvents()));
1068 d->general_timer_.start();
1070 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1071 // This is clearly not enough in a time where we use threads for
1072 // document preview and/or export. 20 should be OK.
1073 QThreadPool::globalInstance()->setMaxThreadCount(20);
1075 // make sure tooltips are formatted
1076 installEventFilter(new ToolTipFormatter(this));
1080 GuiApplication * theGuiApp()
1082 return dynamic_cast<GuiApplication *>(theApp());
1086 double GuiApplication::pixelRatio() const
1088 #if QT_VERSION >= 0x050000
1089 return qt_scale_factor * devicePixelRatio();
1096 void GuiApplication::clearSession()
1103 docstring Application::iconName(FuncRequest const & f, bool unknown)
1105 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown, false).first);
1109 docstring Application::mathIcon(docstring const & c)
1111 return qstring_to_ucs4(findImg(toqstr(c)));
1115 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1119 BufferView * bv = 0;
1120 BufferView * doc_bv = 0;
1122 if (cmd.action() == LFUN_NOACTION) {
1123 status.message(from_utf8(N_("Nothing to do")));
1124 status.setEnabled(false);
1127 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1128 status.setUnknown(true);
1129 status.message(from_utf8(N_("Unknown action")));
1130 status.setEnabled(false);
1133 // Does the GuiApplication know something?
1134 else if (getStatus(cmd, status)) { }
1136 // If we do not have a GuiView, then other functions are disabled
1137 else if (!current_view_)
1138 status.setEnabled(false);
1140 // Does the GuiView know something?
1141 else if (current_view_->getStatus(cmd, status)) { }
1143 // In LyX/Mac, when a dialog is open, the menus of the
1144 // application can still be accessed without giving focus to
1145 // the main window. In this case, we want to disable the menu
1146 // entries that are buffer or view-related.
1147 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1149 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1150 status.setEnabled(false);
1153 // If we do not have a BufferView, then other functions are disabled
1154 else if (!(bv = current_view_->currentBufferView()))
1155 status.setEnabled(false);
1157 // Does the current BufferView know something?
1158 else if (bv->getStatus(cmd, status)) { }
1160 // Does the current Buffer know something?
1161 else if (bv->buffer().getStatus(cmd, status)) { }
1163 // If we do not have a document BufferView, different from the
1164 // current BufferView, then other functions are disabled
1165 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1166 status.setEnabled(false);
1168 // Does the document Buffer know something?
1169 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1172 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1173 status.message(from_utf8(N_("Command not handled")));
1174 status.setEnabled(false);
1177 // the default error message if we disable the command
1178 if (!status.enabled() && status.message().empty())
1179 status.message(from_utf8(N_("Command disabled")));
1185 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1187 // I would really like to avoid having this switch and rather try to
1188 // encode this in the function itself.
1189 // -- And I'd rather let an inset decide which LFUNs it is willing
1190 // to handle (Andre')
1192 switch (cmd.action()) {
1194 // This could be used for the no-GUI version. The GUI version is handled in
1195 // GuiView::getStatus(). See above.
1197 case LFUN_BUFFER_WRITE:
1198 case LFUN_BUFFER_WRITE_AS:
1199 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1200 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1201 enable = b && (b->isUnnamed() || !b->isClean());
1206 case LFUN_BOOKMARK_GOTO: {
1207 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1208 enable = theSession().bookmarks().isValid(num);
1212 case LFUN_BOOKMARK_CLEAR:
1213 enable = theSession().bookmarks().hasValid();
1216 // this one is difficult to get right. As a half-baked
1217 // solution, we consider only the first action of the sequence
1218 case LFUN_COMMAND_SEQUENCE: {
1219 // argument contains ';'-terminated commands
1220 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1221 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1222 func.setOrigin(cmd.origin());
1223 flag = getStatus(func);
1227 // we want to check if at least one of these is enabled
1228 case LFUN_COMMAND_ALTERNATIVES: {
1229 // argument contains ';'-terminated commands
1230 string arg = to_utf8(cmd.argument());
1231 while (!arg.empty()) {
1233 arg = split(arg, first, ';');
1234 FuncRequest func(lyxaction.lookupFunc(first));
1235 func.setOrigin(cmd.origin());
1236 flag = getStatus(func);
1237 // if this one is enabled, the whole thing is
1246 string name = to_utf8(cmd.argument());
1247 if (theTopLevelCmdDef().lock(name, func)) {
1248 func.setOrigin(cmd.origin());
1249 flag = getStatus(func);
1250 theTopLevelCmdDef().release(name);
1252 // catch recursion or unknown command
1253 // definition. all operations until the
1254 // recursion or unknown command definition
1255 // occurs are performed, so set the state to
1262 case LFUN_IF_RELATIVES: {
1263 string const lfun = to_utf8(cmd.argument());
1264 BufferView const * bv =
1265 current_view_ ? current_view_->currentBufferView() : nullptr;
1266 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1270 FuncRequest func(lyxaction.lookupFunc(lfun));
1271 func.setOrigin(cmd.origin());
1272 flag = getStatus(func);
1276 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1278 case LFUN_PREFERENCES_SAVE:
1279 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1280 case LFUN_DEBUG_LEVEL_SET:
1281 // these are handled in our dispatch()
1284 case LFUN_WINDOW_CLOSE:
1285 enable = d->views_.size() > 0;
1288 case LFUN_BUFFER_NEW:
1289 case LFUN_BUFFER_NEW_TEMPLATE:
1290 case LFUN_FILE_OPEN:
1291 case LFUN_HELP_OPEN:
1292 case LFUN_SCREEN_FONT_UPDATE:
1293 case LFUN_SET_COLOR:
1294 case LFUN_WINDOW_NEW:
1296 case LFUN_LYXRC_APPLY:
1297 case LFUN_COMMAND_PREFIX:
1299 case LFUN_META_PREFIX:
1300 case LFUN_RECONFIGURE:
1301 case LFUN_SERVER_GET_FILENAME:
1302 case LFUN_SERVER_NOTIFY:
1306 case LFUN_BUFFER_FORALL: {
1307 if (theBufferList().empty()) {
1308 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1309 flag.setEnabled(false);
1313 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1314 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1315 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1316 flag.setEnabled(false);
1321 case LFUN_DIALOG_SHOW: {
1322 string const name = cmd.getArg(0);
1323 return name == "aboutlyx"
1324 || name == "lyxfiles"
1326 || name == "texinfo"
1327 || name == "progress"
1328 || name == "compare";
1336 flag.setEnabled(false);
1340 /// make a post-dispatch status message
1341 static docstring makeDispatchMessage(docstring const & msg,
1342 FuncRequest const & cmd)
1344 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1345 || cmd.origin() == FuncRequest::TOOLBAR
1346 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1348 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1349 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1353 docstring dispatch_msg = msg;
1354 if (!dispatch_msg.empty())
1355 dispatch_msg += ' ';
1357 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1359 bool argsadded = false;
1361 if (!cmd.argument().empty()) {
1362 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1363 comname += ' ' + cmd.argument();
1367 docstring const shortcuts = theTopLevelKeymap().
1368 printBindings(cmd, KeySequence::ForGui);
1370 if (!shortcuts.empty())
1371 comname += ": " + shortcuts;
1372 else if (!argsadded && !cmd.argument().empty())
1373 comname += ' ' + cmd.argument();
1375 if (!comname.empty()) {
1376 comname = rtrim(comname);
1377 dispatch_msg += '(' + rtrim(comname) + ')';
1379 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1380 return dispatch_msg;
1384 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1388 Buffer * buffer = 0;
1389 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1390 //setCurrentView(cmd.view_origin); //does not work
1392 dr.setMessage(_("Wrong focus!"));
1393 d->dispatch_result_ = dr;
1394 return d->dispatch_result_;
1396 if (current_view_ && current_view_->currentBufferView()) {
1397 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1398 buffer = ¤t_view_->currentBufferView()->buffer();
1401 dr.screenUpdate(Update::FitCursor);
1403 // This handles undo groups automagically
1404 UndoGroupHelper ugh(buffer);
1406 // redraw the screen at the end (first of the two drawing steps).
1407 // This is done unless explicitly requested otherwise.
1408 // This code is kept inside the undo group because updateBuffer
1409 // can create undo actions (see #11292)
1410 updateCurrentView(cmd, dr);
1413 d->dispatch_result_ = dr;
1414 return d->dispatch_result_;
1418 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1423 BufferView * bv = current_view_->currentBufferView();
1425 if (dr.needBufferUpdate()) {
1426 bv->cursor().clearBufferUpdate();
1427 bv->buffer().updateBuffer();
1429 // BufferView::update() updates the ViewMetricsInfo and
1430 // also initializes the position cache for all insets in
1431 // (at least partially) visible top-level paragraphs.
1432 // We will redraw the screen only if needed.
1433 bv->processUpdateFlags(dr.screenUpdate());
1435 // Do we have a selection?
1436 theSelection().haveSelection(bv->cursor().selection());
1439 current_view_->restartCaret();
1441 if (dr.needMessageUpdate()) {
1442 // Some messages may already be translated, so we cannot use _()
1443 current_view_->message(makeDispatchMessage(
1444 translateIfPossible(dr.message()), cmd));
1449 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1450 bool switchToBuffer)
1452 if (!theSession().bookmarks().isValid(idx))
1454 BookmarksSection::Bookmark const & bm =
1455 theSession().bookmarks().bookmark(idx);
1456 LASSERT(!bm.filename.empty(), return);
1457 string const file = bm.filename.absFileName();
1458 // if the file is not opened, open it.
1459 if (!theBufferList().exists(bm.filename)) {
1461 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1465 // open may fail, so we need to test it again
1466 if (!theBufferList().exists(bm.filename))
1469 // bm can be changed when saving
1470 BookmarksSection::Bookmark tmp = bm;
1472 // Special case idx == 0 used for back-from-back jump navigation
1474 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1476 // if the current buffer is not that one, switch to it.
1477 BufferView * doc_bv = current_view_ ?
1478 current_view_->documentBufferView() : 0;
1479 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1480 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1481 if (switchToBuffer) {
1482 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1485 doc_bv = current_view_->documentBufferView();
1490 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1491 if (!doc_bv || !doc_bv->moveToPosition(
1492 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1495 Cursor & cur = doc_bv->cursor();
1496 if (old && cur != *old)
1497 notifyCursorLeavesOrEnters(*old, cur);
1503 // Cursor jump succeeded!
1504 pit_type new_pit = cur.pit();
1505 pos_type new_pos = cur.pos();
1506 int new_id = cur.paragraph().id();
1508 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1509 // see http://www.lyx.org/trac/ticket/3092
1510 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1511 || bm.top_id != new_id) {
1512 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1513 new_pit, new_pos, new_id);
1517 // This function runs "configure" and then rereads lyx.defaults to
1518 // reconfigure the automatic settings.
1519 void GuiApplication::reconfigure(string const & option)
1521 // emit message signal.
1523 current_view_->message(_("Running configure..."));
1525 // Run configure in user lyx directory
1526 string const lock_file = package().getConfigureLockName();
1527 int fd = fileLock(lock_file.c_str());
1528 int const ret = package().reconfigureUserLyXDir(option);
1529 // emit message signal.
1531 current_view_->message(_("Reloading configuration..."));
1532 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1533 // Re-read packages.lst
1534 LaTeXPackages::getAvailable();
1535 fileUnlock(fd, lock_file.c_str());
1538 Alert::information(_("System reconfiguration failed"),
1539 _("The system reconfiguration has failed.\n"
1540 "Default textclass is used but LyX may\n"
1541 "not be able to work properly.\n"
1542 "Please reconfigure again if needed."));
1544 Alert::information(_("System reconfigured"),
1545 _("The system has been reconfigured.\n"
1546 "You need to restart LyX to make use of any\n"
1547 "updated document class specifications."));
1550 void GuiApplication::validateCurrentView()
1552 if (!d->views_.empty() && !current_view_) {
1553 // currently at least one view exists but no view has the focus.
1554 // choose the last view to make it current.
1555 // a view without any open document is preferred.
1556 GuiView * candidate = 0;
1557 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1558 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1559 for (; it != end; ++it) {
1561 if (!candidate->documentBufferView())
1564 setCurrentView(candidate);
1568 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1570 string const argument = to_utf8(cmd.argument());
1571 FuncCode const action = cmd.action();
1573 LYXERR(Debug::ACTION, "cmd: " << cmd);
1575 // we have not done anything wrong yet.
1578 FuncStatus const flag = getStatus(cmd);
1579 if (!flag.enabled()) {
1580 // We cannot use this function here
1581 LYXERR(Debug::ACTION, "action "
1582 << lyxaction.getActionName(action)
1583 << " [" << action << "] is disabled at this location");
1584 dr.setMessage(flag.message());
1586 dr.dispatched(false);
1587 dr.screenUpdate(Update::None);
1588 dr.clearBufferUpdate();
1592 if (cmd.origin() == FuncRequest::LYXSERVER) {
1593 if (current_view_ && current_view_->currentBufferView())
1594 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1595 // we will also need to redraw the screen at the end
1596 dr.screenUpdate(Update::FitCursor);
1599 // Assumes that the action will be dispatched.
1600 dr.dispatched(true);
1602 switch (cmd.action()) {
1604 case LFUN_WINDOW_NEW:
1605 createView(toqstr(cmd.argument()));
1608 case LFUN_WINDOW_CLOSE:
1609 // update bookmark pit of the current buffer before window close
1610 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1611 gotoBookmark(i+1, false, false);
1612 // clear the last opened list, because
1613 // maybe this will end the session
1614 theSession().lastOpened().clear();
1615 // check for valid current_view_
1616 validateCurrentView();
1618 current_view_->closeScheduled();
1622 // quitting is triggered by the gui code
1623 // (leaving the event loop).
1625 current_view_->message(from_utf8(N_("Exiting.")));
1626 if (closeAllViews())
1630 case LFUN_SCREEN_FONT_UPDATE: {
1631 // handle the screen font changes.
1632 /* FIXME: this only updates the current document, whereas all
1633 * documents should see their metrics updated.
1635 d->font_loader_.update();
1636 dr.screenUpdate(Update::Force | Update::FitCursor);
1640 case LFUN_BUFFER_NEW:
1641 validateCurrentView();
1643 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1644 createView(QString(), false); // keep hidden
1645 current_view_->newDocument(to_utf8(cmd.argument()));
1646 current_view_->show();
1647 setActiveWindow(current_view_);
1649 current_view_->newDocument(to_utf8(cmd.argument()));
1653 case LFUN_BUFFER_NEW_TEMPLATE: {
1654 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1655 string const temp = cmd.getArg(1);
1656 validateCurrentView();
1658 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1660 current_view_->newDocument(file, temp, true);
1661 if (!current_view_->documentBufferView())
1662 current_view_->close();
1664 current_view_->newDocument(file, temp, true);
1669 case LFUN_FILE_OPEN: {
1670 // FIXME: normally the code below is not needed, since getStatus makes sure that
1671 // current_view_ is not null.
1672 validateCurrentView();
1673 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1674 string const fname = to_utf8(cmd.argument());
1675 bool const is_open = FileName::isAbsolute(fname)
1676 && theBufferList().getBuffer(FileName(fname));
1678 || (!lyxrc.open_buffers_in_tabs
1679 && current_view_->documentBufferView() != 0
1681 // We want the ui session to be saved per document and not per
1682 // window number. The filename crc is a good enough identifier.
1683 boost::crc_32_type crc;
1684 crc = for_each(fname.begin(), fname.end(), crc);
1685 createView(crc.checksum());
1686 current_view_->openDocument(fname);
1687 if (!current_view_->documentBufferView())
1688 current_view_->close();
1689 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1690 current_view_->raise();
1691 current_view_->activateWindow();
1692 current_view_->showNormal();
1695 current_view_->openDocument(fname);
1696 if (cmd.origin() == FuncRequest::LYXSERVER) {
1697 current_view_->raise();
1698 current_view_->activateWindow();
1699 current_view_->showNormal();
1705 case LFUN_HELP_OPEN: {
1706 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1707 if (current_view_ == 0)
1709 string const arg = to_utf8(cmd.argument());
1711 current_view_->message(_("Missing argument"));
1714 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1716 fname = i18nLibFileSearch("examples", arg, "lyx");
1718 if (fname.empty()) {
1719 lyxerr << "LyX: unable to find documentation file `"
1720 << arg << "'. Bad installation?" << endl;
1723 current_view_->message(bformat(_("Opening help file %1$s..."),
1724 makeDisplayPath(fname.absFileName())));
1725 Buffer * buf = current_view_->loadDocument(fname, false);
1727 buf->setReadonly(!current_view_->develMode());
1731 case LFUN_SET_COLOR: {
1732 string const lyx_name = cmd.getArg(0);
1733 string const x11_name = cmd.getArg(1);
1734 if (lyx_name.empty() || x11_name.empty()) {
1736 current_view_->message(
1737 _("Syntax: set-color <lyx_name> <x11_name>"));
1742 // FIXME: The graphics cache no longer has a changeDisplay method.
1743 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1744 bool const graphicsbg_changed =
1745 lyx_name == graphicsbg && x11_name != graphicsbg;
1746 if (graphicsbg_changed)
1747 graphics::GCache::get().changeDisplay(true);
1750 if (!lcolor.setColor(lyx_name, x11_name)) {
1752 current_view_->message(
1753 bformat(_("Set-color \"%1$s\" failed "
1754 "- color is undefined or "
1755 "may not be redefined"),
1756 from_utf8(lyx_name)));
1759 // Make sure we don't keep old colors in cache.
1760 d->color_cache_.clear();
1761 // Update the current view
1762 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1766 case LFUN_LYXRC_APPLY: {
1767 // reset active key sequences, since the bindings
1768 // are updated (bug 6064)
1770 LyXRC const lyxrc_orig = lyxrc;
1772 istringstream ss(to_utf8(cmd.argument()));
1773 bool const success = lyxrc.read(ss);
1776 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1777 << "Unable to read lyxrc data"
1782 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1784 // If the request comes from the minibuffer, then we can't reset
1785 // the GUI, since that would destroy the minibuffer itself and
1786 // cause a crash, since we are currently in one of the methods of
1787 // GuiCommandBuffer. See bug #8540.
1788 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1791 // FIXME Unfortunately, that leaves a bug here, since we cannot
1792 // reset the GUI in this case. If the changes to lyxrc affected the
1793 // UI, then, nothing would happen. This seems fairly unlikely, but
1794 // it definitely is a bug.
1796 dr.forceBufferUpdate();
1800 case LFUN_COMMAND_PREFIX:
1801 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1806 d->meta_fake_bit = NoModifier;
1807 GuiView * gv = currentView();
1808 if (gv && gv->currentBufferView())
1809 // cancel any selection
1810 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1811 dr.setMessage(from_ascii(N_("Cancel")));
1814 case LFUN_META_PREFIX:
1815 d->meta_fake_bit = AltModifier;
1816 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1819 // --- Menus -----------------------------------------------
1820 case LFUN_RECONFIGURE:
1821 // argument is any additional parameter to the configure.py command
1822 reconfigure(to_utf8(cmd.argument()));
1825 // --- lyxserver commands ----------------------------
1826 case LFUN_SERVER_GET_FILENAME: {
1827 if (current_view_ && current_view_->documentBufferView()) {
1828 docstring const fname = from_utf8(
1829 current_view_->documentBufferView()->buffer().absFileName());
1830 dr.setMessage(fname);
1831 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1833 dr.setMessage(docstring());
1834 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1839 case LFUN_SERVER_NOTIFY: {
1840 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1841 dr.setMessage(dispatch_buffer);
1842 theServer().notifyClient(to_utf8(dispatch_buffer));
1846 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1847 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1853 string rest = split(argument, countstr, ' ');
1854 int const count = convert<int>(countstr);
1855 // an arbitrary number to limit number of iterations
1856 int const max_iter = 10000;
1857 if (count > max_iter) {
1858 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1861 for (int i = 0; i < count; ++i) {
1862 FuncRequest lfun = lyxaction.lookupFunc(rest);
1863 lfun.allowAsync(false);
1870 case LFUN_COMMAND_SEQUENCE: {
1871 // argument contains ';'-terminated commands
1872 string arg = argument;
1873 // FIXME: this LFUN should also work without any view.
1874 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1875 ? &(current_view_->documentBufferView()->buffer()) : 0;
1876 // This handles undo groups automagically
1877 UndoGroupHelper ugh(buffer);
1878 while (!arg.empty()) {
1880 arg = split(arg, first, ';');
1881 FuncRequest func(lyxaction.lookupFunc(first));
1882 func.allowAsync(false);
1883 func.setOrigin(cmd.origin());
1889 case LFUN_BUFFER_FORALL: {
1890 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1891 funcToRun.allowAsync(false);
1893 map<Buffer *, GuiView *> views_lVisible;
1894 map<GuiView *, Buffer *> activeBuffers;
1896 QList<GuiView *> allViews = d->views_.values();
1898 // this for does not modify any buffer. It just collects info on local
1899 // visibility of buffers and on which buffer is active in each view.
1900 Buffer * const last = theBufferList().last();
1901 for(GuiView * view : allViews) {
1902 // all of the buffers might be locally hidden. That is, there is no
1904 if (!view || !view->currentBufferView())
1905 activeBuffers[view] = 0;
1907 activeBuffers[view] = &view->currentBufferView()->buffer();
1909 // find out if each is locally visible or locally hidden.
1910 // we don't use a for loop as the buffer list cycles.
1911 Buffer * b = theBufferList().first();
1913 bool const locallyVisible = view && view->workArea(*b);
1914 if (locallyVisible) {
1915 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1916 // only need to overwrite/add if we don't already know a buffer is globally
1917 // visible or we do know but we would prefer to dispatch LFUN from the
1918 // current view because of cursor position issues.
1919 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1920 views_lVisible[b] = view;
1924 b = theBufferList().next(b);
1928 GuiView * const homeView = currentView();
1929 Buffer * b = theBufferList().first();
1930 Buffer * nextBuf = 0;
1931 int numProcessed = 0;
1934 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1936 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1938 // first change to a view where b is locally visible, preferably current_view_.
1939 GuiView * const vLv = views_lVisible[b];
1941 lyx::dispatch(funcToRun);
1949 // put things back to how they were (if possible).
1950 for (GuiView * view : allViews) {
1951 Buffer * originalBuf = activeBuffers[view];
1952 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1953 if (theBufferList().isLoaded(originalBuf))
1954 view->setBuffer(originalBuf);
1956 homeView->setFocus();
1958 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1962 case LFUN_COMMAND_ALTERNATIVES: {
1963 // argument contains ';'-terminated commands
1964 string arg = argument;
1965 while (!arg.empty()) {
1967 arg = split(arg, first, ';');
1968 FuncRequest func(lyxaction.lookupFunc(first));
1969 func.setOrigin(cmd.origin());
1970 FuncStatus const stat = getStatus(func);
1971 if (stat.enabled()) {
1981 if (theTopLevelCmdDef().lock(argument, func)) {
1982 func.setOrigin(cmd.origin());
1984 theTopLevelCmdDef().release(argument);
1986 if (func.action() == LFUN_UNKNOWN_ACTION) {
1987 // unknown command definition
1988 lyxerr << "Warning: unknown command definition `"
1992 // recursion detected
1993 lyxerr << "Warning: Recursion in the command definition `"
1994 << argument << "' detected"
2001 case LFUN_IF_RELATIVES: {
2002 string const lfun = to_utf8(cmd.argument());
2003 FuncRequest func(lyxaction.lookupFunc(lfun));
2004 func.setOrigin(cmd.origin());
2005 FuncStatus const stat = getStatus(func);
2006 if (stat.enabled()) {
2013 case LFUN_PREFERENCES_SAVE:
2014 lyxrc.write(support::makeAbsPath("preferences",
2015 package().user_support().absFileName()), false);
2018 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2019 string const fname = addName(addPath(package().user_support().absFileName(),
2020 "templates/"), "defaults.lyx");
2021 Buffer defaults(fname);
2023 istringstream ss(argument);
2028 // We need to make sure that, after we recreat the DocumentClass,
2029 // which we do in readHeader, we apply it to the document itself.
2030 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2031 int const unknown_tokens = defaults.readHeader(lex);
2032 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2034 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2035 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2037 if (unknown_tokens != 0) {
2038 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2039 << unknown_tokens << " unknown token"
2040 << (unknown_tokens == 1 ? "" : "s")
2044 if (defaults.writeFile(FileName(defaults.absFileName())))
2045 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2046 makeDisplayPath(fname)));
2049 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2054 case LFUN_BOOKMARK_GOTO:
2055 // go to bookmark, open unopened file and switch to buffer if necessary
2056 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2057 dr.screenUpdate(Update::Force | Update::FitCursor);
2060 case LFUN_BOOKMARK_CLEAR:
2061 theSession().bookmarks().clear();
2064 case LFUN_DEBUG_LEVEL_SET:
2065 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2068 case LFUN_DIALOG_SHOW: {
2069 string const name = cmd.getArg(0);
2071 if ( name == "aboutlyx"
2073 || name == "texinfo"
2074 || name == "progress"
2075 || name == "compare")
2077 // work around: on Mac OS the application
2078 // is not terminated when closing the last view.
2079 // Create a new one to be able to dispatch the
2080 // LFUN_DIALOG_SHOW to this view.
2081 if (current_view_ == 0)
2087 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2090 current_view_->dispatch(cmd, dr);
2094 if (cmd.origin() == FuncRequest::LYXSERVER)
2095 updateCurrentView(cmd, dr);
2099 docstring GuiApplication::viewStatusMessage()
2101 // When meta-fake key is pressed, show the key sequence so far + "M-".
2102 if (d->meta_fake_bit != NoModifier)
2103 return d->keyseq.print(KeySequence::ForGui) + "M-";
2105 // Else, when a non-complete key sequence is pressed,
2106 // show the available options.
2107 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2108 return d->keyseq.printOptions(true);
2114 string GuiApplication::inputLanguageCode() const
2116 #if (QT_VERSION < 0x050000)
2117 QLocale loc = keyboardInputLocale();
2119 QLocale loc = inputMethod()->locale();
2121 //LYXERR0("input lang = " << fromqstr(loc.name()));
2122 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2126 void GuiApplication::onLocaleChanged()
2128 //LYXERR0("Change language to " << inputLanguage()->lang());
2129 if (currentView() && currentView()->currentBufferView())
2130 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2134 void GuiApplication::handleKeyFunc(FuncCode action)
2138 if (d->keyseq.length())
2140 GuiView * gv = currentView();
2141 LASSERT(gv && gv->currentBufferView(), return);
2142 BufferView * bv = gv->currentBufferView();
2143 bv->getIntl().getTransManager().deadkey(
2144 c, get_accent(action).accent, bv->cursor().innerText(),
2146 // Need to clear, in case the minibuffer calls these
2149 // copied verbatim from do_accent_char
2150 bv->cursor().resetAnchor();
2154 //Keep this in sync with GuiApplication::processKeySym below
2155 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2156 KeyModifier state) const
2158 // Do nothing if we have nothing
2159 if (!keysym.isOK() || keysym.isModifier())
2161 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2163 FuncRequest func = seq.addkey(keysym, state);
2164 // When not cancel or meta-fake, do the normal lookup.
2165 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2167 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2169 // Maybe user can only reach the key via holding down shift.
2170 // Let's see. But only if shift is the only modifier
2171 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2172 // If addkey looked up a command and did not find further commands then
2173 // seq has been reset at this point
2174 func = seq.addkey(keysym, NoModifier);
2176 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2177 << seq.print(KeySequence::Portable) << ']');
2178 return func.action() != LFUN_UNKNOWN_ACTION;
2182 //Keep this in sync with GuiApplication::queryKeySym above
2183 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2185 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2187 // Do nothing if we have nothing (JMarc)
2188 if (!keysym.isOK() || keysym.isModifier()) {
2190 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2192 current_view_->restartCaret();
2196 char_type encoded_last_key = keysym.getUCSEncoded();
2198 // Do a one-deep top-level lookup for
2199 // cancel and meta-fake keys. RVDK_PATCH_5
2200 d->cancel_meta_seq.reset();
2202 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2203 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2205 // When not cancel or meta-fake, do the normal lookup.
2206 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2207 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2208 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2209 // remove Caps Lock and Mod2 as a modifiers
2210 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2211 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2214 // Don't remove this unless you know what you are doing.
2215 d->meta_fake_bit = NoModifier;
2217 // Can this happen now ?
2218 if (func.action() == LFUN_NOACTION)
2219 func = FuncRequest(LFUN_COMMAND_PREFIX);
2221 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2222 << d->keyseq.print(KeySequence::Portable) << ']');
2224 // already here we know if it any point in going further
2225 // why not return already here if action == -1 and
2226 // num_bytes == 0? (Lgb)
2228 if (d->keyseq.length() > 1 && current_view_)
2229 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2232 // Maybe user can only reach the key via holding down shift.
2233 // Let's see. But only if shift is the only modifier
2234 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2235 LYXERR(Debug::KEY, "Trying without shift");
2236 // If addkey looked up a command and did not find further commands then
2237 // seq has been reset at this point
2238 func = d->keyseq.addkey(keysym, NoModifier);
2239 LYXERR(Debug::KEY, "Action now " << func.action());
2242 if (func.action() == LFUN_UNKNOWN_ACTION) {
2243 // We didn't match any of the key sequences.
2244 // See if it's normal insertable text not already
2245 // covered by a binding
2246 if (keysym.isText() && d->keyseq.length() == 1) {
2247 // Non-printable characters (such as ASCII control characters)
2248 // must not be inserted (#5704)
2249 if (!isPrintable(encoded_last_key)) {
2250 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2252 current_view_->restartCaret();
2255 // The following modifier check is not needed on Mac.
2256 // The keysym is either not text or it is different
2257 // from the non-modifier keysym. See #9875 for the
2258 // broken alt-modifier effect of having this code active.
2259 #if !defined(Q_OS_MAC)
2260 // If a non-Shift Modifier is used we have a non-bound key sequence
2261 // (such as Alt+j = j). This should be omitted (#5575).
2262 // On Windows, AltModifier and ControlModifier are both
2263 // set when AltGr is pressed. Therefore, in order to not
2264 // break AltGr-bound symbols (see #5575 for details),
2265 // unbound Ctrl+Alt key sequences are allowed.
2266 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2267 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2268 && !(state & AltModifier && state & ControlModifier)
2272 if (current_view_) {
2273 current_view_->message(_("Unknown function."));
2274 current_view_->restartCaret();
2279 // Since all checks above were passed, we now really have text that
2280 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2281 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2283 LYXERR(Debug::KEY, "isText() is true, inserting.");
2284 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2286 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2287 if (current_view_) {
2288 current_view_->message(_("Unknown function."));
2289 current_view_->restartCaret();
2295 if (func.action() == LFUN_SELF_INSERT) {
2296 if (encoded_last_key != 0) {
2297 docstring const arg(1, encoded_last_key);
2298 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2299 FuncRequest::KEYBOARD));
2300 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2303 processFuncRequest(func);
2307 void GuiApplication::processFuncRequest(FuncRequest const & func)
2309 lyx::dispatch(func);
2313 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2315 addToFuncRequestQueue(func);
2316 processFuncRequestQueueAsync();
2320 void GuiApplication::processFuncRequestQueue()
2322 while (!d->func_request_queue_.empty()) {
2323 // take the item from the stack _before_ processing the
2324 // request in order to avoid race conditions from nested
2325 // or parallel requests (see #10406)
2326 FuncRequest const fr(d->func_request_queue_.front());
2327 d->func_request_queue_.pop();
2328 processFuncRequest(fr);
2333 void GuiApplication::processFuncRequestQueueAsync()
2335 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2339 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2341 d->func_request_queue_.push(func);
2345 void GuiApplication::resetGui()
2347 // Set the language defined by the user.
2351 if (!readUIFile(toqstr(lyxrc.ui_file)))
2352 // Gives some error box here.
2355 if (d->global_menubar_)
2356 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2358 QHash<int, GuiView *>::iterator it;
2359 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2362 gv->setLayoutDirection(layoutDirection());
2366 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2370 bool GuiApplication::rtlContext() const
2372 if (current_view_ && current_view_->currentBufferView()) {
2373 BufferView const * bv = current_view_->currentBufferView();
2374 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2376 return layoutDirection() == Qt::RightToLeft;
2380 void GuiApplication::createView(int view_id)
2382 createView(QString(), true, view_id);
2386 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2389 // release the keyboard which might have been grabbed by the global
2390 // menubar on Mac to catch shortcuts even without any GuiView.
2391 if (d->global_menubar_)
2392 d->global_menubar_->releaseKeyboard();
2396 while (d->views_.find(id) != d->views_.end())
2399 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2400 GuiView * view = new GuiView(id);
2401 // `view' is the new current_view_. Tell coverity that is is not 0.
2402 LATTEST(current_view_);
2404 d->views_[id] = view;
2408 setActiveWindow(view);
2411 if (!geometry_arg.isEmpty()) {
2412 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2416 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2417 re.indexIn(geometry_arg);
2418 w = re.cap(1).toInt();
2419 h = re.cap(2).toInt();
2420 x = re.cap(3).toInt();
2421 y = re.cap(4).toInt();
2422 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2423 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2424 // Set initial geometry such that we can get the frame size.
2425 view->setGeometry(x, y, w, h);
2426 int framewidth = view->geometry().x() - view->x();
2427 int titleheight = view->geometry().y() - view->y();
2428 // Negative displacements must be interpreted as distances
2429 // from the right or bottom screen borders.
2430 if (sx == '-' || sy == '-') {
2431 QRect rec = QApplication::desktop()->screenGeometry();
2433 x += rec.width() - w - framewidth;
2435 y += rec.height() - h - titleheight;
2436 view->setGeometry(x, y, w, h);
2438 // Make sure that the left and top frame borders are visible.
2439 if (view->x() < 0 || view->y() < 0) {
2444 view->setGeometry(x, y, w, h);
2452 bool GuiApplication::unhide(Buffer * buf)
2456 currentView()->setBuffer(buf, false);
2461 Clipboard & GuiApplication::clipboard()
2463 return d->clipboard_;
2467 Selection & GuiApplication::selection()
2469 return d->selection_;
2473 FontLoader & GuiApplication::fontLoader()
2475 return d->font_loader_;
2479 Toolbars const & GuiApplication::toolbars() const
2481 return d->toolbars_;
2485 Toolbars & GuiApplication::toolbars()
2487 return d->toolbars_;
2491 Menus const & GuiApplication::menus() const
2497 Menus & GuiApplication::menus()
2503 QList<int> GuiApplication::viewIds() const
2505 return d->views_.keys();
2509 ColorCache & GuiApplication::colorCache()
2511 return d->color_cache_;
2515 int GuiApplication::exec()
2517 // asynchronously handle batch commands. This event will be in
2518 // the event queue in front of other asynchronous events. Hence,
2519 // we can assume in the latter that the gui is setup already.
2520 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2522 return QApplication::exec();
2526 void GuiApplication::exit(int status)
2528 QApplication::exit(status);
2532 void GuiApplication::setGuiLanguage()
2536 // install translation file for Qt built-in dialogs
2537 QString const language_name = QString("qt_") + theLocale.name();
2538 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2539 // Short-named translator can be loaded from a long name, but not the
2540 // opposite. Therefore, long name should be used without truncation.
2541 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2542 if (!d->qt_trans_.load(language_name,
2543 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2544 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2547 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2551 switch (theLocale.language()) {
2552 case QLocale::Arabic :
2553 case QLocale::Hebrew :
2554 case QLocale::Persian :
2555 case QLocale::Urdu :
2556 setLayoutDirection(Qt::RightToLeft);
2559 setLayoutDirection(Qt::LeftToRight);
2564 void GuiApplication::execBatchCommands()
2569 if (!readUIFile(toqstr(lyxrc.ui_file)))
2570 // Gives some error box here.
2574 #if QT_VERSION > 0x040600
2575 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2577 #if QT_VERSION > 0x050100
2578 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2580 // Create the global default menubar which is shown for the dialogs
2581 // and if no GuiView is visible.
2582 // This must be done after the session was recovered to know the "last files".
2583 d->global_menubar_ = new QMenuBar(0);
2584 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2587 lyx::execBatchCommands();
2591 QAbstractItemModel * GuiApplication::languageModel()
2593 if (d->language_model_)
2594 return d->language_model_;
2596 QStandardItemModel * lang_model = new QStandardItemModel(this);
2597 lang_model->insertColumns(0, 3);
2598 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2599 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2600 Languages::const_iterator it = lyx::languages.begin();
2601 Languages::const_iterator end = lyx::languages.end();
2602 for (; it != end; ++it) {
2603 int current_row = lang_model->rowCount();
2604 lang_model->insertRows(current_row, 1);
2605 QModelIndex pl_item = lang_model->index(current_row, 0);
2606 QModelIndex sp_item = lang_model->index(current_row, 1);
2607 QModelIndex th_item = lang_model->index(current_row, 2);
2608 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2609 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2610 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2611 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2612 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2613 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2614 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2615 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2616 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2617 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2619 d->language_model_ = new QSortFilterProxyModel(this);
2620 d->language_model_->setSourceModel(lang_model);
2621 d->language_model_->setSortLocaleAware(true);
2622 return d->language_model_;
2626 void GuiApplication::restoreGuiSession()
2628 if (!lyxrc.load_session)
2631 Session & session = theSession();
2632 LastOpenedSection::LastOpened const & lastopened =
2633 session.lastOpened().getfiles();
2635 validateCurrentView();
2637 FileName active_file;
2638 // do not add to the lastfile list since these files are restored from
2639 // last session, and should be already there (regular files), or should
2640 // not be added at all (help files).
2641 for (size_t i = 0; i < lastopened.size(); ++i) {
2642 FileName const & file_name = lastopened[i].file_name;
2643 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2644 && current_view_->documentBufferView() != 0)) {
2645 boost::crc_32_type crc;
2646 string const & fname = file_name.absFileName();
2647 crc = for_each(fname.begin(), fname.end(), crc);
2648 createView(crc.checksum());
2650 current_view_->loadDocument(file_name, false);
2652 if (lastopened[i].active)
2653 active_file = file_name;
2656 // Restore last active buffer
2657 Buffer * buffer = theBufferList().getBuffer(active_file);
2658 if (buffer && current_view_)
2659 current_view_->setBuffer(buffer);
2661 // clear this list to save a few bytes of RAM
2662 session.lastOpened().clear();
2666 QString const GuiApplication::romanFontName()
2669 font.setStyleHint(QFont::Serif);
2670 font.setFamily("serif");
2672 return QFontInfo(font).family();
2676 QString const GuiApplication::sansFontName()
2679 font.setStyleHint(QFont::SansSerif);
2680 font.setFamily("sans");
2682 return QFontInfo(font).family();
2686 QString const GuiApplication::typewriterFontName()
2688 return QFontInfo(typewriterSystemFont()).family();
2693 // We cannot use QFont::fixedPitch() because it doesn't
2694 // return the fact but only if it is requested.
2695 static bool isFixedPitch(const QFont & font) {
2696 const QFontInfo fi(font);
2697 return fi.fixedPitch();
2702 QFont const GuiApplication::typewriterSystemFont()
2704 #if QT_VERSION >= 0x050200
2705 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2707 QFont font("monospace");
2709 if (!isFixedPitch(font)) {
2710 // try to enforce a real monospaced font
2711 font.setStyleHint(QFont::Monospace);
2712 if (!isFixedPitch(font)) {
2713 font.setStyleHint(QFont::TypeWriter);
2714 if (!isFixedPitch(font)) font.setFamily("courier");
2718 // On a Mac the result is too small and it's not practical to
2719 // rely on Qtconfig utility to change the system settings of Qt.
2720 font.setPointSize(12);
2726 void GuiApplication::handleRegularEvents()
2728 ForkedCallsController::handleCompletedProcesses();
2732 bool GuiApplication::event(QEvent * e)
2735 case QEvent::FileOpen: {
2736 // Open a file; this happens only on Mac OS X for now.
2738 // We do this asynchronously because on startup the batch
2739 // commands are not executed here yet and the gui is not ready
2741 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2742 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2743 processFuncRequestAsync(fr);
2747 #if (QT_VERSION < 0x050000)
2748 // Qt5 uses a signal for that, see above.
2749 case QEvent::KeyboardLayoutChange:
2750 //LYXERR0("keyboard change");
2751 if (currentView() && currentView()->currentBufferView())
2752 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2757 return QApplication::event(e);
2762 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2765 return QApplication::notify(receiver, event);
2767 catch (ExceptionMessage const & e) {
2769 case ErrorException:
2771 setQuitOnLastWindowClosed(false);
2773 Alert::error(e.title_, e.details_);
2775 // Properly crash in debug mode in order to get a useful backtrace.
2778 // In release mode, try to exit gracefully.
2780 // FIXME: GCC 7 thinks we can fall through here. Can we?
2782 case BufferException: {
2783 if (!current_view_ || !current_view_->documentBufferView())
2785 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2786 docstring details = e.details_ + '\n';
2787 details += buf->emergencyWrite();
2788 theBufferList().release(buf);
2789 details += "\n" + _("The current document was closed.");
2790 Alert::error(e.title_, details);
2793 case WarningException:
2794 Alert::warning(e.title_, e.details_);
2798 catch (exception const & e) {
2799 docstring s = _("LyX has caught an exception, it will now "
2800 "attempt to save all unsaved documents and exit."
2802 s += from_ascii(e.what());
2803 Alert::error(_("Software exception Detected"), s);
2807 docstring s = _("LyX has caught some really weird exception, it will "
2808 "now attempt to save all unsaved documents and exit.");
2809 Alert::error(_("Software exception Detected"), s);
2817 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2819 QColor const & qcol = d->color_cache_.get(col);
2820 if (!qcol.isValid()) {
2826 rgbcol.r = qcol.red();
2827 rgbcol.g = qcol.green();
2828 rgbcol.b = qcol.blue();
2833 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2835 QColor const qcol(lcolor.getX11Name(col).c_str());
2836 if (!qcol.isValid()) {
2842 rgbcol.r = qcol.red();
2843 rgbcol.g = qcol.green();
2844 rgbcol.b = qcol.blue();
2849 string const GuiApplication::hexName(ColorCode col)
2851 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2855 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2857 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2858 d->socket_notifiers_[fd] = sn;
2859 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2863 void GuiApplication::socketDataReceived(int fd)
2865 d->socket_notifiers_[fd]->func_();
2869 void GuiApplication::unregisterSocketCallback(int fd)
2871 d->socket_notifiers_.take(fd)->setEnabled(false);
2875 void GuiApplication::commitData(QSessionManager & sm)
2877 /** The implementation is required to avoid an application exit
2878 ** when session state save is triggered by session manager.
2879 ** The default implementation sends a close event to all
2880 ** visible top level widgets when session management allows
2882 ** We are changing that to check the state of each buffer in all
2883 ** views and ask the users what to do if buffers are dirty.
2884 ** Furthermore, we save the session state.
2885 ** We do NOT close the views here since the user still can cancel
2886 ** the logout process (see #9277); also, this would hide LyX from
2887 ** an OSes own session handling (application restoration).
2889 #ifdef QT_NO_SESSIONMANAGER
2891 #warning Qt is compiled without session manager
2893 #pragma message("warning: Qt is compiled without session manager")
2897 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2905 void GuiApplication::unregisterView(GuiView * gv)
2907 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2908 d->views_.remove(gv->id());
2909 if (current_view_ == gv)
2915 bool GuiApplication::closeAllViews()
2917 if (d->views_.empty())
2920 // When a view/window was closed before without quitting LyX, there
2921 // are already entries in the lastOpened list.
2922 theSession().lastOpened().clear();
2924 QList<GuiView *> const views = d->views_.values();
2925 for (GuiView * view : views) {
2926 if (!view->closeScheduled())
2935 bool GuiApplication::prepareAllViewsForLogout()
2937 if (d->views_.empty())
2940 QList<GuiView *> const views = d->views_.values();
2941 for (GuiView * view : views) {
2942 if (!view->prepareAllBuffersForLogout())
2950 GuiView & GuiApplication::view(int id) const
2952 LAPPERR(d->views_.contains(id));
2953 return *d->views_.value(id);
2957 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2959 QList<GuiView *> const views = d->views_.values();
2960 for (GuiView * view : views)
2961 view->hideDialog(name, inset);
2965 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2967 Buffer const * buf = 0;
2968 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2969 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2970 if (Buffer const * ptr = (*it)->updateInset(inset))
2977 bool GuiApplication::searchMenu(FuncRequest const & func,
2978 docstring_list & names) const
2980 BufferView * bv = 0;
2982 bv = current_view_->currentBufferView();
2983 return d->menus_.searchMenu(func, names, bv);
2987 bool GuiApplication::hasBufferView() const
2989 return (current_view_ && current_view_->currentBufferView());
2993 // Ensure that a file is read only once (prevents include loops)
2994 static QStringList uifiles;
2995 // store which ui files define Toolbars
2996 static QStringList toolbar_uifiles;
2999 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
3010 LexerKeyword uitags[] = {
3011 { "format", ui_format },
3012 { "include", ui_include },
3013 { "menuset", ui_menuset },
3014 { "toolbars", ui_toolbars },
3015 { "toolbarset", ui_toolbarset }
3019 lex.setFile(ui_path);
3021 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3025 if (lyxerr.debugging(Debug::PARSER))
3026 lex.printTable(lyxerr);
3029 // format before introduction of format tag
3030 unsigned int format = 0;
3031 while (lex.isOK()) {
3032 int const status = lex.lex();
3034 // we have to do this check here, outside the switch,
3035 // because otherwise we would start reading include files,
3036 // e.g., if the first tag we hit was an include tag.
3037 if (status == ui_format)
3039 format = lex.getInteger();
3043 // this will trigger unless the first tag we hit is a format
3044 // tag, with the right format.
3045 if (format != LFUN_FORMAT)
3046 return FormatMismatch;
3049 case Lexer::LEX_FEOF:
3054 QString const file = toqstr(lex.getString());
3055 bool const success = readUIFile(file, true);
3057 LYXERR0("Failed to read included file: " << fromqstr(file));
3064 d->menus_.read(lex);
3068 d->toolbars_.readToolbars(lex);
3072 d->toolbars_.readToolbarSettings(lex);
3073 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3077 if (!rtrim(lex.getString()).empty())
3078 lex.printError("LyX::ReadUIFile: "
3079 "Unknown menu tag: `$$Token'");
3081 LYXERR0("Error with status: " << status);
3087 return (error ? ReadError : ReadOK);
3091 bool GuiApplication::readUIFile(QString const & name, bool include)
3093 LYXERR(Debug::INIT, "About to read " << name << "...");
3097 ui_path = libFileSearch("ui", name, "inc");
3098 if (ui_path.empty())
3099 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3101 ui_path = libFileSearch("ui", name, "ui");
3104 if (ui_path.empty()) {
3105 static const QString defaultUIFile = "default";
3106 LYXERR(Debug::INIT, "Could not find " << name);
3108 Alert::warning(_("Could not find UI definition file"),
3109 bformat(_("Error while reading the included file\n%1$s\n"
3110 "Please check your installation."), qstring_to_ucs4(name)));
3113 if (name == defaultUIFile) {
3114 LYXERR(Debug::INIT, "Could not find default UI file!!");
3115 Alert::warning(_("Could not find default UI file"),
3116 _("LyX could not find the default UI file!\n"
3117 "Please check your installation."));
3120 Alert::warning(_("Could not find UI definition file"),
3121 bformat(_("Error while reading the configuration file\n%1$s\n"
3122 "Falling back to default.\n"
3123 "Please look under Tools>Preferences>User Interface and\n"
3124 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3125 return readUIFile(defaultUIFile, false);
3128 QString const uifile = toqstr(ui_path.absFileName());
3129 if (uifiles.contains(uifile)) {
3131 // We are reading again the top uifile so reset the safeguard:
3134 d->toolbars_.reset();
3136 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3137 << "Is this an include loop?");
3141 uifiles.push_back(uifile);
3143 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3145 ReturnValues retval = readUIFile(ui_path);
3147 if (retval == FormatMismatch) {
3148 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3149 TempFile tmp("convertXXXXXX.ui");
3150 FileName const tempfile = tmp.name();
3151 bool const success = prefs2prefs(ui_path, tempfile, true);
3153 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3154 " to format " << LFUN_FORMAT << ".");
3156 retval = readUIFile(tempfile);
3160 if (retval != ReadOK) {
3161 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3169 settings.beginGroup("ui_files");
3170 bool touched = false;
3171 for (int i = 0; i != uifiles.size(); ++i) {
3172 QFileInfo fi(uifiles[i]);
3173 QDateTime const date_value = fi.lastModified();
3174 QString const name_key = QString::number(i);
3175 // if an ui file which defines Toolbars has changed,
3176 // we have to reset the settings
3177 if (toolbar_uifiles.contains(uifiles[i])
3178 && (!settings.contains(name_key)
3179 || settings.value(name_key).toString() != uifiles[i]
3180 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3182 settings.setValue(name_key, uifiles[i]);
3183 settings.setValue(name_key + "/date", date_value);
3186 settings.endGroup();
3188 settings.remove("views");
3194 void GuiApplication::onLastWindowClosed()
3196 if (d->global_menubar_)
3197 d->global_menubar_->grabKeyboard();
3201 void GuiApplication::startLongOperation() {
3202 d->key_checker_.start();
3206 bool GuiApplication::longOperationCancelled() {
3207 return d->key_checker_.pressed();
3211 void GuiApplication::stopLongOperation() {
3212 d->key_checker_.stop();
3216 bool GuiApplication::longOperationStarted() {
3217 return d->key_checker_.started();
3221 ////////////////////////////////////////////////////////////////////////
3223 // X11 specific stuff goes here...
3226 bool GuiApplication::x11EventFilter(XEvent * xev)
3231 switch (xev->type) {
3232 case SelectionRequest: {
3233 if (xev->xselectionrequest.selection != XA_PRIMARY)
3235 LYXERR(Debug::SELECTION, "X requested selection.");
3236 BufferView * bv = current_view_->currentBufferView();
3238 docstring const sel = bv->requestSelection();
3240 d->selection_.put(sel);
3241 // Refresh the selection request timestamp.
3242 // We have to do this by ourselves as Qt seems
3243 // not doing that, maybe because of our
3244 // "persistent selection" implementation
3245 // (see comments in GuiSelection.cpp).
3246 XSelectionEvent nev;
3247 nev.type = SelectionNotify;
3248 nev.display = xev->xselectionrequest.display;
3249 nev.requestor = xev->xselectionrequest.requestor;
3250 nev.selection = xev->xselectionrequest.selection;
3251 nev.target = xev->xselectionrequest.target;
3252 nev.property = 0L; // None
3253 nev.time = CurrentTime;
3254 XSendEvent(QX11Info::display(),
3255 nev.requestor, False, 0,
3256 reinterpret_cast<XEvent *>(&nev));
3262 case SelectionClear: {
3263 if (xev->xselectionclear.selection != XA_PRIMARY)
3265 LYXERR(Debug::SELECTION, "Lost selection.");
3266 BufferView * bv = current_view_->currentBufferView();
3268 bv->clearSelection();
3274 #elif defined(QPA_XCB)
3275 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3276 void * message, long *)
3278 if (!current_view_ || eventType != "xcb_generic_event_t")
3281 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3283 switch (ev->response_type) {
3284 case XCB_SELECTION_REQUEST: {
3285 xcb_selection_request_event_t * srev =
3286 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3287 if (srev->selection != XCB_ATOM_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 #ifdef HAVE_QT5_X11_EXTRAS
3296 // Refresh the selection request timestamp.
3297 // We have to do this by ourselves as Qt seems
3298 // not doing that, maybe because of our
3299 // "persistent selection" implementation
3300 // (see comments in GuiSelection.cpp).
3301 // It is expected that every X11 event is
3302 // 32 bytes long, even if not all 32 bytes are
3304 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3305 struct alignas(32) padded_event
3306 : xcb_selection_notify_event_t {};
3307 padded_event nev = {};
3308 nev.response_type = XCB_SELECTION_NOTIFY;
3309 nev.requestor = srev->requestor;
3310 nev.selection = srev->selection;
3311 nev.target = srev->target;
3312 nev.property = XCB_NONE;
3313 nev.time = XCB_CURRENT_TIME;
3314 xcb_connection_t * con = QX11Info::connection();
3315 xcb_send_event(con, 0, srev->requestor,
3316 XCB_EVENT_MASK_NO_EVENT,
3317 reinterpret_cast<char const *>(&nev));
3325 case XCB_SELECTION_CLEAR: {
3326 xcb_selection_clear_event_t * scev =
3327 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3328 if (scev->selection != XCB_ATOM_PRIMARY)
3330 LYXERR(Debug::SELECTION, "Lost selection.");
3331 BufferView * bv = current_view_->currentBufferView();
3333 bv->clearSelection();
3341 } // namespace frontend
3344 void hideDialogs(std::string const & name, Inset * inset)
3347 frontend::guiApp->hideDialogs(name, inset);
3351 ////////////////////////////////////////////////////////////////////
3355 ////////////////////////////////////////////////////////////////////
3357 frontend::FontLoader & theFontLoader()
3359 LAPPERR(frontend::guiApp);
3360 return frontend::guiApp->fontLoader();
3364 frontend::FontMetrics const & theFontMetrics(Font const & f)
3366 return theFontMetrics(f.fontInfo());
3370 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3372 LAPPERR(frontend::guiApp);
3373 return frontend::guiApp->fontLoader().metrics(f);
3377 ////////////////////////////////////////////////////////////////////
3381 ////////////////////////////////////////////////////////////////////
3383 frontend::Clipboard & theClipboard()
3385 LAPPERR(frontend::guiApp);
3386 return frontend::guiApp->clipboard();
3390 frontend::Selection & theSelection()
3392 LAPPERR(frontend::guiApp);
3393 return frontend::guiApp->selection();
3399 #include "moc_GuiApplication.cpp"