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 #if QT_VERSION >= 0x050700
1007 setDesktopFileName(lyx_package);
1010 qsrand(QDateTime::currentDateTime().toTime_t());
1012 // Install LyX translator for missing Qt translations
1013 installTranslator(&d->gui_trans_);
1014 // Install Qt native translator for GUI elements.
1015 installTranslator(&d->qt_trans_);
1018 // Enable reception of XCB events.
1019 installNativeEventFilter(this);
1022 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1023 // lyxrc setting for this in order to let the application stay resident.
1024 // But then we need some kind of dock icon, at least on Windows.
1026 if (lyxrc.quit_on_last_window_closed)
1027 setQuitOnLastWindowClosed(false);
1030 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1031 // seems to be the default case for applications like LyX.
1032 setQuitOnLastWindowClosed(false);
1037 #if defined(Q_WS_X11) || defined(QPA_XCB)
1038 // doubleClickInterval() is 400 ms on X11 which is just too long.
1039 // On Windows and Mac OS X, the operating system's value is used.
1040 // On Microsoft Windows, calling this function sets the double
1041 // click interval for all applications. So we don't!
1042 QApplication::setDoubleClickInterval(300);
1045 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1047 // needs to be done before reading lyxrc
1049 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1053 // Initialize RC Fonts
1054 if (lyxrc.roman_font_name.empty())
1055 lyxrc.roman_font_name = fromqstr(romanFontName());
1057 if (lyxrc.sans_font_name.empty())
1058 lyxrc.sans_font_name = fromqstr(sansFontName());
1060 if (lyxrc.typewriter_font_name.empty())
1061 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1063 #if (QT_VERSION >= 0x050000)
1064 // Qt4 does this in event(), see below.
1065 // Track change of keyboard
1066 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1069 d->general_timer_.setInterval(500);
1070 connect(&d->general_timer_, SIGNAL(timeout()),
1071 this, SLOT(handleRegularEvents()));
1072 d->general_timer_.start();
1074 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1075 // This is clearly not enough in a time where we use threads for
1076 // document preview and/or export. 20 should be OK.
1077 QThreadPool::globalInstance()->setMaxThreadCount(20);
1079 // make sure tooltips are formatted
1080 installEventFilter(new ToolTipFormatter(this));
1084 GuiApplication * theGuiApp()
1086 return dynamic_cast<GuiApplication *>(theApp());
1090 double GuiApplication::pixelRatio() const
1092 #if QT_VERSION >= 0x050000
1093 return qt_scale_factor * devicePixelRatio();
1100 void GuiApplication::clearSession()
1107 docstring Application::iconName(FuncRequest const & f, bool unknown)
1109 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown, false).first);
1113 docstring Application::mathIcon(docstring const & c)
1115 return qstring_to_ucs4(findImg(toqstr(c)));
1119 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1123 BufferView * bv = 0;
1124 BufferView * doc_bv = 0;
1126 if (cmd.action() == LFUN_NOACTION) {
1127 status.message(from_utf8(N_("Nothing to do")));
1128 status.setEnabled(false);
1131 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1132 status.setUnknown(true);
1133 status.message(from_utf8(N_("Unknown action")));
1134 status.setEnabled(false);
1137 // Does the GuiApplication know something?
1138 else if (getStatus(cmd, status)) { }
1140 // If we do not have a GuiView, then other functions are disabled
1141 else if (!current_view_)
1142 status.setEnabled(false);
1144 // Does the GuiView know something?
1145 else if (current_view_->getStatus(cmd, status)) { }
1147 // In LyX/Mac, when a dialog is open, the menus of the
1148 // application can still be accessed without giving focus to
1149 // the main window. In this case, we want to disable the menu
1150 // entries that are buffer or view-related.
1151 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1153 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1154 status.setEnabled(false);
1157 // If we do not have a BufferView, then other functions are disabled
1158 else if (!(bv = current_view_->currentBufferView()))
1159 status.setEnabled(false);
1161 // Does the current BufferView know something?
1162 else if (bv->getStatus(cmd, status)) { }
1164 // Does the current Buffer know something?
1165 else if (bv->buffer().getStatus(cmd, status)) { }
1167 // If we do not have a document BufferView, different from the
1168 // current BufferView, then other functions are disabled
1169 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1170 status.setEnabled(false);
1172 // Does the document Buffer know something?
1173 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1176 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1177 status.message(from_utf8(N_("Command not handled")));
1178 status.setEnabled(false);
1181 // the default error message if we disable the command
1182 if (!status.enabled() && status.message().empty())
1183 status.message(from_utf8(N_("Command disabled")));
1189 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1191 // I would really like to avoid having this switch and rather try to
1192 // encode this in the function itself.
1193 // -- And I'd rather let an inset decide which LFUNs it is willing
1194 // to handle (Andre')
1196 switch (cmd.action()) {
1198 // This could be used for the no-GUI version. The GUI version is handled in
1199 // GuiView::getStatus(). See above.
1201 case LFUN_BUFFER_WRITE:
1202 case LFUN_BUFFER_WRITE_AS:
1203 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1204 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1205 enable = b && (b->isUnnamed() || !b->isClean());
1210 case LFUN_BOOKMARK_GOTO: {
1211 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1212 enable = theSession().bookmarks().isValid(num);
1216 case LFUN_BOOKMARK_CLEAR:
1217 enable = theSession().bookmarks().hasValid();
1220 // this one is difficult to get right. As a half-baked
1221 // solution, we consider only the first action of the sequence
1222 case LFUN_COMMAND_SEQUENCE: {
1223 // argument contains ';'-terminated commands
1224 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1225 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1226 func.setOrigin(cmd.origin());
1227 flag = getStatus(func);
1231 // we want to check if at least one of these is enabled
1232 case LFUN_COMMAND_ALTERNATIVES: {
1233 // argument contains ';'-terminated commands
1234 string arg = to_utf8(cmd.argument());
1235 while (!arg.empty()) {
1237 arg = split(arg, first, ';');
1238 FuncRequest func(lyxaction.lookupFunc(first));
1239 func.setOrigin(cmd.origin());
1240 flag = getStatus(func);
1241 // if this one is enabled, the whole thing is
1250 string name = to_utf8(cmd.argument());
1251 if (theTopLevelCmdDef().lock(name, func)) {
1252 func.setOrigin(cmd.origin());
1253 flag = getStatus(func);
1254 theTopLevelCmdDef().release(name);
1256 // catch recursion or unknown command
1257 // definition. all operations until the
1258 // recursion or unknown command definition
1259 // occurs are performed, so set the state to
1266 case LFUN_IF_RELATIVES: {
1267 string const lfun = to_utf8(cmd.argument());
1268 BufferView const * bv =
1269 current_view_ ? current_view_->currentBufferView() : nullptr;
1270 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1274 FuncRequest func(lyxaction.lookupFunc(lfun));
1275 func.setOrigin(cmd.origin());
1276 flag = getStatus(func);
1280 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1282 case LFUN_PREFERENCES_SAVE:
1283 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1284 case LFUN_DEBUG_LEVEL_SET:
1285 // these are handled in our dispatch()
1288 case LFUN_WINDOW_CLOSE:
1289 enable = d->views_.size() > 0;
1292 case LFUN_BUFFER_NEW:
1293 case LFUN_BUFFER_NEW_TEMPLATE:
1294 case LFUN_FILE_OPEN:
1295 case LFUN_HELP_OPEN:
1296 case LFUN_SCREEN_FONT_UPDATE:
1297 case LFUN_SET_COLOR:
1298 case LFUN_WINDOW_NEW:
1300 case LFUN_LYXRC_APPLY:
1301 case LFUN_COMMAND_PREFIX:
1303 case LFUN_META_PREFIX:
1304 case LFUN_RECONFIGURE:
1305 case LFUN_SERVER_GET_FILENAME:
1306 case LFUN_SERVER_NOTIFY:
1310 case LFUN_BUFFER_FORALL: {
1311 if (theBufferList().empty()) {
1312 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1313 flag.setEnabled(false);
1317 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1318 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1319 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1320 flag.setEnabled(false);
1325 case LFUN_DIALOG_SHOW: {
1326 string const name = cmd.getArg(0);
1327 return name == "aboutlyx"
1328 || name == "lyxfiles"
1330 || name == "texinfo"
1331 || name == "progress"
1332 || name == "compare";
1340 flag.setEnabled(false);
1344 /// make a post-dispatch status message
1345 static docstring makeDispatchMessage(docstring const & msg,
1346 FuncRequest const & cmd)
1348 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1349 || cmd.origin() == FuncRequest::TOOLBAR
1350 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1352 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1353 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1357 docstring dispatch_msg = msg;
1358 if (!dispatch_msg.empty())
1359 dispatch_msg += ' ';
1361 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1363 bool argsadded = false;
1365 if (!cmd.argument().empty()) {
1366 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1367 comname += ' ' + cmd.argument();
1371 docstring const shortcuts = theTopLevelKeymap().
1372 printBindings(cmd, KeySequence::ForGui);
1374 if (!shortcuts.empty())
1375 comname += ": " + shortcuts;
1376 else if (!argsadded && !cmd.argument().empty())
1377 comname += ' ' + cmd.argument();
1379 if (!comname.empty()) {
1380 comname = rtrim(comname);
1381 dispatch_msg += '(' + rtrim(comname) + ')';
1383 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1384 return dispatch_msg;
1388 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1392 Buffer * buffer = 0;
1393 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1394 //setCurrentView(cmd.view_origin); //does not work
1396 dr.setMessage(_("Wrong focus!"));
1397 d->dispatch_result_ = dr;
1398 return d->dispatch_result_;
1400 if (current_view_ && current_view_->currentBufferView()) {
1401 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1402 buffer = ¤t_view_->currentBufferView()->buffer();
1405 dr.screenUpdate(Update::FitCursor);
1407 // This handles undo groups automagically
1408 UndoGroupHelper ugh(buffer);
1410 // redraw the screen at the end (first of the two drawing steps).
1411 // This is done unless explicitly requested otherwise.
1412 // This code is kept inside the undo group because updateBuffer
1413 // can create undo actions (see #11292)
1414 updateCurrentView(cmd, dr);
1417 d->dispatch_result_ = dr;
1418 return d->dispatch_result_;
1422 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1427 BufferView * bv = current_view_->currentBufferView();
1429 if (dr.needBufferUpdate()) {
1430 bv->cursor().clearBufferUpdate();
1431 bv->buffer().updateBuffer();
1433 // BufferView::update() updates the ViewMetricsInfo and
1434 // also initializes the position cache for all insets in
1435 // (at least partially) visible top-level paragraphs.
1436 // We will redraw the screen only if needed.
1437 bv->processUpdateFlags(dr.screenUpdate());
1439 // Do we have a selection?
1440 theSelection().haveSelection(bv->cursor().selection());
1443 current_view_->restartCaret();
1445 if (dr.needMessageUpdate()) {
1446 // Some messages may already be translated, so we cannot use _()
1447 current_view_->message(makeDispatchMessage(
1448 translateIfPossible(dr.message()), cmd));
1453 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1454 bool switchToBuffer)
1456 if (!theSession().bookmarks().isValid(idx))
1458 BookmarksSection::Bookmark const & bm =
1459 theSession().bookmarks().bookmark(idx);
1460 LASSERT(!bm.filename.empty(), return);
1461 string const file = bm.filename.absFileName();
1462 // if the file is not opened, open it.
1463 if (!theBufferList().exists(bm.filename)) {
1465 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1469 // open may fail, so we need to test it again
1470 if (!theBufferList().exists(bm.filename))
1473 // bm can be changed when saving
1474 BookmarksSection::Bookmark tmp = bm;
1476 // Special case idx == 0 used for back-from-back jump navigation
1478 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1480 // if the current buffer is not that one, switch to it.
1481 BufferView * doc_bv = current_view_ ?
1482 current_view_->documentBufferView() : 0;
1483 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1484 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1485 if (switchToBuffer) {
1486 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1489 doc_bv = current_view_->documentBufferView();
1494 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1495 if (!doc_bv || !doc_bv->moveToPosition(
1496 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1499 Cursor & cur = doc_bv->cursor();
1500 if (old && cur != *old)
1501 notifyCursorLeavesOrEnters(*old, cur);
1507 // Cursor jump succeeded!
1508 pit_type new_pit = cur.pit();
1509 pos_type new_pos = cur.pos();
1510 int new_id = cur.paragraph().id();
1512 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1513 // see http://www.lyx.org/trac/ticket/3092
1514 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1515 || bm.top_id != new_id) {
1516 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1517 new_pit, new_pos, new_id);
1521 // This function runs "configure" and then rereads lyx.defaults to
1522 // reconfigure the automatic settings.
1523 void GuiApplication::reconfigure(string const & option)
1525 // emit message signal.
1527 current_view_->message(_("Running configure..."));
1529 // Run configure in user lyx directory
1530 string const lock_file = package().getConfigureLockName();
1531 int fd = fileLock(lock_file.c_str());
1532 int const ret = package().reconfigureUserLyXDir(option);
1533 // emit message signal.
1535 current_view_->message(_("Reloading configuration..."));
1536 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1537 // Re-read packages.lst
1538 LaTeXPackages::getAvailable();
1539 fileUnlock(fd, lock_file.c_str());
1542 Alert::information(_("System reconfiguration failed"),
1543 _("The system reconfiguration has failed.\n"
1544 "Default textclass is used but LyX may\n"
1545 "not be able to work properly.\n"
1546 "Please reconfigure again if needed."));
1548 Alert::information(_("System reconfigured"),
1549 _("The system has been reconfigured.\n"
1550 "You need to restart LyX to make use of any\n"
1551 "updated document class specifications."));
1554 void GuiApplication::validateCurrentView()
1556 if (!d->views_.empty() && !current_view_) {
1557 // currently at least one view exists but no view has the focus.
1558 // choose the last view to make it current.
1559 // a view without any open document is preferred.
1560 GuiView * candidate = 0;
1561 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1562 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1563 for (; it != end; ++it) {
1565 if (!candidate->documentBufferView())
1568 setCurrentView(candidate);
1572 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1574 string const argument = to_utf8(cmd.argument());
1575 FuncCode const action = cmd.action();
1577 LYXERR(Debug::ACTION, "cmd: " << cmd);
1579 // we have not done anything wrong yet.
1582 FuncStatus const flag = getStatus(cmd);
1583 if (!flag.enabled()) {
1584 // We cannot use this function here
1585 LYXERR(Debug::ACTION, "action "
1586 << lyxaction.getActionName(action)
1587 << " [" << action << "] is disabled at this location");
1588 dr.setMessage(flag.message());
1590 dr.dispatched(false);
1591 dr.screenUpdate(Update::None);
1592 dr.clearBufferUpdate();
1596 if (cmd.origin() == FuncRequest::LYXSERVER) {
1597 if (current_view_ && current_view_->currentBufferView())
1598 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1599 // we will also need to redraw the screen at the end
1600 dr.screenUpdate(Update::FitCursor);
1603 // Assumes that the action will be dispatched.
1604 dr.dispatched(true);
1606 switch (cmd.action()) {
1608 case LFUN_WINDOW_NEW:
1609 createView(toqstr(cmd.argument()));
1612 case LFUN_WINDOW_CLOSE:
1613 // update bookmark pit of the current buffer before window close
1614 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1615 gotoBookmark(i+1, false, false);
1616 // clear the last opened list, because
1617 // maybe this will end the session
1618 theSession().lastOpened().clear();
1619 // check for valid current_view_
1620 validateCurrentView();
1622 current_view_->closeScheduled();
1626 // quitting is triggered by the gui code
1627 // (leaving the event loop).
1629 current_view_->message(from_utf8(N_("Exiting.")));
1630 if (closeAllViews())
1634 case LFUN_SCREEN_FONT_UPDATE: {
1635 // handle the screen font changes.
1636 /* FIXME: this only updates the current document, whereas all
1637 * documents should see their metrics updated.
1639 d->font_loader_.update();
1640 dr.screenUpdate(Update::Force | Update::FitCursor);
1644 case LFUN_BUFFER_NEW:
1645 validateCurrentView();
1647 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1648 createView(QString(), false); // keep hidden
1649 current_view_->newDocument(to_utf8(cmd.argument()));
1650 current_view_->show();
1651 setActiveWindow(current_view_);
1653 current_view_->newDocument(to_utf8(cmd.argument()));
1657 case LFUN_BUFFER_NEW_TEMPLATE: {
1658 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1659 string const temp = cmd.getArg(1);
1660 validateCurrentView();
1662 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1664 current_view_->newDocument(file, temp, true);
1665 if (!current_view_->documentBufferView())
1666 current_view_->close();
1668 current_view_->newDocument(file, temp, true);
1673 case LFUN_FILE_OPEN: {
1674 // FIXME: normally the code below is not needed, since getStatus makes sure that
1675 // current_view_ is not null.
1676 validateCurrentView();
1677 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1678 string const fname = to_utf8(cmd.argument());
1679 bool const is_open = FileName::isAbsolute(fname)
1680 && theBufferList().getBuffer(FileName(fname));
1682 || (!lyxrc.open_buffers_in_tabs
1683 && current_view_->documentBufferView() != 0
1685 // We want the ui session to be saved per document and not per
1686 // window number. The filename crc is a good enough identifier.
1687 boost::crc_32_type crc;
1688 crc = for_each(fname.begin(), fname.end(), crc);
1689 createView(crc.checksum());
1690 current_view_->openDocument(fname);
1691 if (!current_view_->documentBufferView())
1692 current_view_->close();
1693 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1694 current_view_->raise();
1695 current_view_->activateWindow();
1696 current_view_->showNormal();
1699 current_view_->openDocument(fname);
1700 if (cmd.origin() == FuncRequest::LYXSERVER) {
1701 current_view_->raise();
1702 current_view_->activateWindow();
1703 current_view_->showNormal();
1709 case LFUN_HELP_OPEN: {
1710 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1711 if (current_view_ == 0)
1713 string const arg = to_utf8(cmd.argument());
1715 current_view_->message(_("Missing argument"));
1718 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1720 fname = i18nLibFileSearch("examples", arg, "lyx");
1722 if (fname.empty()) {
1723 lyxerr << "LyX: unable to find documentation file `"
1724 << arg << "'. Bad installation?" << endl;
1727 current_view_->message(bformat(_("Opening help file %1$s..."),
1728 makeDisplayPath(fname.absFileName())));
1729 Buffer * buf = current_view_->loadDocument(fname, false);
1731 buf->setReadonly(!current_view_->develMode());
1735 case LFUN_SET_COLOR: {
1736 string const lyx_name = cmd.getArg(0);
1737 string const x11_name = cmd.getArg(1);
1738 if (lyx_name.empty() || x11_name.empty()) {
1740 current_view_->message(
1741 _("Syntax: set-color <lyx_name> <x11_name>"));
1746 // FIXME: The graphics cache no longer has a changeDisplay method.
1747 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1748 bool const graphicsbg_changed =
1749 lyx_name == graphicsbg && x11_name != graphicsbg;
1750 if (graphicsbg_changed)
1751 graphics::GCache::get().changeDisplay(true);
1754 if (!lcolor.setColor(lyx_name, x11_name)) {
1756 current_view_->message(
1757 bformat(_("Set-color \"%1$s\" failed "
1758 "- color is undefined or "
1759 "may not be redefined"),
1760 from_utf8(lyx_name)));
1763 // Make sure we don't keep old colors in cache.
1764 d->color_cache_.clear();
1765 // Update the current view
1766 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1770 case LFUN_LYXRC_APPLY: {
1771 // reset active key sequences, since the bindings
1772 // are updated (bug 6064)
1774 LyXRC const lyxrc_orig = lyxrc;
1776 istringstream ss(to_utf8(cmd.argument()));
1777 bool const success = lyxrc.read(ss);
1780 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1781 << "Unable to read lyxrc data"
1786 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1788 // If the request comes from the minibuffer, then we can't reset
1789 // the GUI, since that would destroy the minibuffer itself and
1790 // cause a crash, since we are currently in one of the methods of
1791 // GuiCommandBuffer. See bug #8540.
1792 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1795 // FIXME Unfortunately, that leaves a bug here, since we cannot
1796 // reset the GUI in this case. If the changes to lyxrc affected the
1797 // UI, then, nothing would happen. This seems fairly unlikely, but
1798 // it definitely is a bug.
1800 dr.forceBufferUpdate();
1804 case LFUN_COMMAND_PREFIX:
1805 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1810 d->meta_fake_bit = NoModifier;
1811 GuiView * gv = currentView();
1812 if (gv && gv->currentBufferView())
1813 // cancel any selection
1814 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1815 dr.setMessage(from_ascii(N_("Cancel")));
1818 case LFUN_META_PREFIX:
1819 d->meta_fake_bit = AltModifier;
1820 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1823 // --- Menus -----------------------------------------------
1824 case LFUN_RECONFIGURE:
1825 // argument is any additional parameter to the configure.py command
1826 reconfigure(to_utf8(cmd.argument()));
1829 // --- lyxserver commands ----------------------------
1830 case LFUN_SERVER_GET_FILENAME: {
1831 if (current_view_ && current_view_->documentBufferView()) {
1832 docstring const fname = from_utf8(
1833 current_view_->documentBufferView()->buffer().absFileName());
1834 dr.setMessage(fname);
1835 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1837 dr.setMessage(docstring());
1838 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1843 case LFUN_SERVER_NOTIFY: {
1844 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1845 dr.setMessage(dispatch_buffer);
1846 theServer().notifyClient(to_utf8(dispatch_buffer));
1850 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1851 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1857 string rest = split(argument, countstr, ' ');
1858 int const count = convert<int>(countstr);
1859 // an arbitrary number to limit number of iterations
1860 int const max_iter = 10000;
1861 if (count > max_iter) {
1862 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1865 for (int i = 0; i < count; ++i) {
1866 FuncRequest lfun = lyxaction.lookupFunc(rest);
1867 lfun.allowAsync(false);
1874 case LFUN_COMMAND_SEQUENCE: {
1875 // argument contains ';'-terminated commands
1876 string arg = argument;
1877 // FIXME: this LFUN should also work without any view.
1878 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1879 ? &(current_view_->documentBufferView()->buffer()) : 0;
1880 // This handles undo groups automagically
1881 UndoGroupHelper ugh(buffer);
1882 while (!arg.empty()) {
1884 arg = split(arg, first, ';');
1885 FuncRequest func(lyxaction.lookupFunc(first));
1886 func.allowAsync(false);
1887 func.setOrigin(cmd.origin());
1893 case LFUN_BUFFER_FORALL: {
1894 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1895 funcToRun.allowAsync(false);
1897 map<Buffer *, GuiView *> views_lVisible;
1898 map<GuiView *, Buffer *> activeBuffers;
1900 QList<GuiView *> allViews = d->views_.values();
1902 // this for does not modify any buffer. It just collects info on local
1903 // visibility of buffers and on which buffer is active in each view.
1904 Buffer * const last = theBufferList().last();
1905 for(GuiView * view : allViews) {
1906 // all of the buffers might be locally hidden. That is, there is no
1908 if (!view || !view->currentBufferView())
1909 activeBuffers[view] = 0;
1911 activeBuffers[view] = &view->currentBufferView()->buffer();
1913 // find out if each is locally visible or locally hidden.
1914 // we don't use a for loop as the buffer list cycles.
1915 Buffer * b = theBufferList().first();
1917 bool const locallyVisible = view && view->workArea(*b);
1918 if (locallyVisible) {
1919 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1920 // only need to overwrite/add if we don't already know a buffer is globally
1921 // visible or we do know but we would prefer to dispatch LFUN from the
1922 // current view because of cursor position issues.
1923 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1924 views_lVisible[b] = view;
1928 b = theBufferList().next(b);
1932 GuiView * const homeView = currentView();
1933 Buffer * b = theBufferList().first();
1934 Buffer * nextBuf = 0;
1935 int numProcessed = 0;
1938 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1940 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1942 // first change to a view where b is locally visible, preferably current_view_.
1943 GuiView * const vLv = views_lVisible[b];
1945 lyx::dispatch(funcToRun);
1953 // put things back to how they were (if possible).
1954 for (GuiView * view : allViews) {
1955 Buffer * originalBuf = activeBuffers[view];
1956 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1957 if (theBufferList().isLoaded(originalBuf))
1958 view->setBuffer(originalBuf);
1960 homeView->setFocus();
1962 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1966 case LFUN_COMMAND_ALTERNATIVES: {
1967 // argument contains ';'-terminated commands
1968 string arg = argument;
1969 while (!arg.empty()) {
1971 arg = split(arg, first, ';');
1972 FuncRequest func(lyxaction.lookupFunc(first));
1973 func.setOrigin(cmd.origin());
1974 FuncStatus const stat = getStatus(func);
1975 if (stat.enabled()) {
1985 if (theTopLevelCmdDef().lock(argument, func)) {
1986 func.setOrigin(cmd.origin());
1988 theTopLevelCmdDef().release(argument);
1990 if (func.action() == LFUN_UNKNOWN_ACTION) {
1991 // unknown command definition
1992 lyxerr << "Warning: unknown command definition `"
1996 // recursion detected
1997 lyxerr << "Warning: Recursion in the command definition `"
1998 << argument << "' detected"
2005 case LFUN_IF_RELATIVES: {
2006 string const lfun = to_utf8(cmd.argument());
2007 FuncRequest func(lyxaction.lookupFunc(lfun));
2008 func.setOrigin(cmd.origin());
2009 FuncStatus const stat = getStatus(func);
2010 if (stat.enabled()) {
2017 case LFUN_PREFERENCES_SAVE:
2018 lyxrc.write(support::makeAbsPath("preferences",
2019 package().user_support().absFileName()), false);
2022 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2023 string const fname = addName(addPath(package().user_support().absFileName(),
2024 "templates/"), "defaults.lyx");
2025 Buffer defaults(fname);
2027 istringstream ss(argument);
2032 // We need to make sure that, after we recreat the DocumentClass,
2033 // which we do in readHeader, we apply it to the document itself.
2034 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2035 int const unknown_tokens = defaults.readHeader(lex);
2036 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2038 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2039 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2041 if (unknown_tokens != 0) {
2042 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2043 << unknown_tokens << " unknown token"
2044 << (unknown_tokens == 1 ? "" : "s")
2048 if (defaults.writeFile(FileName(defaults.absFileName())))
2049 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2050 makeDisplayPath(fname)));
2053 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2058 case LFUN_BOOKMARK_GOTO:
2059 // go to bookmark, open unopened file and switch to buffer if necessary
2060 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2061 dr.screenUpdate(Update::Force | Update::FitCursor);
2064 case LFUN_BOOKMARK_CLEAR:
2065 theSession().bookmarks().clear();
2068 case LFUN_DEBUG_LEVEL_SET:
2069 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2072 case LFUN_DIALOG_SHOW: {
2073 string const name = cmd.getArg(0);
2075 if ( name == "aboutlyx"
2077 || name == "texinfo"
2078 || name == "progress"
2079 || name == "compare")
2081 // work around: on Mac OS the application
2082 // is not terminated when closing the last view.
2083 // Create a new one to be able to dispatch the
2084 // LFUN_DIALOG_SHOW to this view.
2085 if (current_view_ == 0)
2091 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2094 current_view_->dispatch(cmd, dr);
2098 if (cmd.origin() == FuncRequest::LYXSERVER)
2099 updateCurrentView(cmd, dr);
2103 docstring GuiApplication::viewStatusMessage()
2105 // When meta-fake key is pressed, show the key sequence so far + "M-".
2106 if (d->meta_fake_bit != NoModifier)
2107 return d->keyseq.print(KeySequence::ForGui) + "M-";
2109 // Else, when a non-complete key sequence is pressed,
2110 // show the available options.
2111 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2112 return d->keyseq.printOptions(true);
2118 string GuiApplication::inputLanguageCode() const
2120 #if (QT_VERSION < 0x050000)
2121 QLocale loc = keyboardInputLocale();
2123 QLocale loc = inputMethod()->locale();
2125 //LYXERR0("input lang = " << fromqstr(loc.name()));
2126 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2130 void GuiApplication::onLocaleChanged()
2132 //LYXERR0("Change language to " << inputLanguage()->lang());
2133 if (currentView() && currentView()->currentBufferView())
2134 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2138 void GuiApplication::handleKeyFunc(FuncCode action)
2142 if (d->keyseq.length())
2144 GuiView * gv = currentView();
2145 LASSERT(gv && gv->currentBufferView(), return);
2146 BufferView * bv = gv->currentBufferView();
2147 bv->getIntl().getTransManager().deadkey(
2148 c, get_accent(action).accent, bv->cursor().innerText(),
2150 // Need to clear, in case the minibuffer calls these
2153 // copied verbatim from do_accent_char
2154 bv->cursor().resetAnchor();
2158 //Keep this in sync with GuiApplication::processKeySym below
2159 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2160 KeyModifier state) const
2162 // Do nothing if we have nothing
2163 if (!keysym.isOK() || keysym.isModifier())
2165 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2167 FuncRequest func = seq.addkey(keysym, state);
2168 // When not cancel or meta-fake, do the normal lookup.
2169 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2171 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2173 // Maybe user can only reach the key via holding down shift.
2174 // Let's see. But only if shift is the only modifier
2175 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2176 // If addkey looked up a command and did not find further commands then
2177 // seq has been reset at this point
2178 func = seq.addkey(keysym, NoModifier);
2180 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2181 << seq.print(KeySequence::Portable) << ']');
2182 return func.action() != LFUN_UNKNOWN_ACTION;
2186 //Keep this in sync with GuiApplication::queryKeySym above
2187 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2189 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2191 // Do nothing if we have nothing (JMarc)
2192 if (!keysym.isOK() || keysym.isModifier()) {
2194 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2196 current_view_->restartCaret();
2200 char_type encoded_last_key = keysym.getUCSEncoded();
2202 // Do a one-deep top-level lookup for
2203 // cancel and meta-fake keys. RVDK_PATCH_5
2204 d->cancel_meta_seq.reset();
2206 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2207 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2209 // When not cancel or meta-fake, do the normal lookup.
2210 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2211 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2212 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2213 // remove Caps Lock and Mod2 as a modifiers
2214 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2215 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2218 // Don't remove this unless you know what you are doing.
2219 d->meta_fake_bit = NoModifier;
2221 // Can this happen now ?
2222 if (func.action() == LFUN_NOACTION)
2223 func = FuncRequest(LFUN_COMMAND_PREFIX);
2225 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2226 << d->keyseq.print(KeySequence::Portable) << ']');
2228 // already here we know if it any point in going further
2229 // why not return already here if action == -1 and
2230 // num_bytes == 0? (Lgb)
2232 if (d->keyseq.length() > 1 && current_view_)
2233 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2236 // Maybe user can only reach the key via holding down shift.
2237 // Let's see. But only if shift is the only modifier
2238 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2239 LYXERR(Debug::KEY, "Trying without shift");
2240 // If addkey looked up a command and did not find further commands then
2241 // seq has been reset at this point
2242 func = d->keyseq.addkey(keysym, NoModifier);
2243 LYXERR(Debug::KEY, "Action now " << func.action());
2246 if (func.action() == LFUN_UNKNOWN_ACTION) {
2247 // We didn't match any of the key sequences.
2248 // See if it's normal insertable text not already
2249 // covered by a binding
2250 if (keysym.isText() && d->keyseq.length() == 1) {
2251 // Non-printable characters (such as ASCII control characters)
2252 // must not be inserted (#5704)
2253 if (!isPrintable(encoded_last_key)) {
2254 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2256 current_view_->restartCaret();
2259 // The following modifier check is not needed on Mac.
2260 // The keysym is either not text or it is different
2261 // from the non-modifier keysym. See #9875 for the
2262 // broken alt-modifier effect of having this code active.
2263 #if !defined(Q_OS_MAC)
2264 // If a non-Shift Modifier is used we have a non-bound key sequence
2265 // (such as Alt+j = j). This should be omitted (#5575).
2266 // On Windows, AltModifier and ControlModifier are both
2267 // set when AltGr is pressed. Therefore, in order to not
2268 // break AltGr-bound symbols (see #5575 for details),
2269 // unbound Ctrl+Alt key sequences are allowed.
2270 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2271 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2272 && !(state & AltModifier && state & ControlModifier)
2276 if (current_view_) {
2277 current_view_->message(_("Unknown function."));
2278 current_view_->restartCaret();
2283 // Since all checks above were passed, we now really have text that
2284 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2285 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2287 LYXERR(Debug::KEY, "isText() is true, inserting.");
2288 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2290 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2291 if (current_view_) {
2292 current_view_->message(_("Unknown function."));
2293 current_view_->restartCaret();
2299 if (func.action() == LFUN_SELF_INSERT) {
2300 if (encoded_last_key != 0) {
2301 docstring const arg(1, encoded_last_key);
2302 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2303 FuncRequest::KEYBOARD));
2304 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2307 processFuncRequest(func);
2311 void GuiApplication::processFuncRequest(FuncRequest const & func)
2313 lyx::dispatch(func);
2317 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2319 addToFuncRequestQueue(func);
2320 processFuncRequestQueueAsync();
2324 void GuiApplication::processFuncRequestQueue()
2326 while (!d->func_request_queue_.empty()) {
2327 // take the item from the stack _before_ processing the
2328 // request in order to avoid race conditions from nested
2329 // or parallel requests (see #10406)
2330 FuncRequest const fr(d->func_request_queue_.front());
2331 d->func_request_queue_.pop();
2332 processFuncRequest(fr);
2337 void GuiApplication::processFuncRequestQueueAsync()
2339 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2343 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2345 d->func_request_queue_.push(func);
2349 void GuiApplication::resetGui()
2351 // Set the language defined by the user.
2355 if (!readUIFile(toqstr(lyxrc.ui_file)))
2356 // Gives some error box here.
2359 if (d->global_menubar_)
2360 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2362 QHash<int, GuiView *>::iterator it;
2363 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2366 gv->setLayoutDirection(layoutDirection());
2370 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2374 bool GuiApplication::rtlContext() const
2376 if (current_view_ && current_view_->currentBufferView()) {
2377 BufferView const * bv = current_view_->currentBufferView();
2378 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2380 return layoutDirection() == Qt::RightToLeft;
2384 void GuiApplication::createView(int view_id)
2386 createView(QString(), true, view_id);
2390 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2393 // release the keyboard which might have been grabbed by the global
2394 // menubar on Mac to catch shortcuts even without any GuiView.
2395 if (d->global_menubar_)
2396 d->global_menubar_->releaseKeyboard();
2400 while (d->views_.find(id) != d->views_.end())
2403 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2404 GuiView * view = new GuiView(id);
2405 // `view' is the new current_view_. Tell coverity that is is not 0.
2406 LATTEST(current_view_);
2408 d->views_[id] = view;
2412 setActiveWindow(view);
2415 if (!geometry_arg.isEmpty()) {
2416 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2420 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2421 re.indexIn(geometry_arg);
2422 w = re.cap(1).toInt();
2423 h = re.cap(2).toInt();
2424 x = re.cap(3).toInt();
2425 y = re.cap(4).toInt();
2426 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2427 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2428 // Set initial geometry such that we can get the frame size.
2429 view->setGeometry(x, y, w, h);
2430 int framewidth = view->geometry().x() - view->x();
2431 int titleheight = view->geometry().y() - view->y();
2432 // Negative displacements must be interpreted as distances
2433 // from the right or bottom screen borders.
2434 if (sx == '-' || sy == '-') {
2435 QRect rec = QApplication::desktop()->screenGeometry();
2437 x += rec.width() - w - framewidth;
2439 y += rec.height() - h - titleheight;
2440 view->setGeometry(x, y, w, h);
2442 // Make sure that the left and top frame borders are visible.
2443 if (view->x() < 0 || view->y() < 0) {
2448 view->setGeometry(x, y, w, h);
2456 bool GuiApplication::unhide(Buffer * buf)
2460 currentView()->setBuffer(buf, false);
2465 Clipboard & GuiApplication::clipboard()
2467 return d->clipboard_;
2471 Selection & GuiApplication::selection()
2473 return d->selection_;
2477 FontLoader & GuiApplication::fontLoader()
2479 return d->font_loader_;
2483 Toolbars const & GuiApplication::toolbars() const
2485 return d->toolbars_;
2489 Toolbars & GuiApplication::toolbars()
2491 return d->toolbars_;
2495 Menus const & GuiApplication::menus() const
2501 Menus & GuiApplication::menus()
2507 QList<int> GuiApplication::viewIds() const
2509 return d->views_.keys();
2513 ColorCache & GuiApplication::colorCache()
2515 return d->color_cache_;
2519 int GuiApplication::exec()
2521 // asynchronously handle batch commands. This event will be in
2522 // the event queue in front of other asynchronous events. Hence,
2523 // we can assume in the latter that the gui is setup already.
2524 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2526 return QApplication::exec();
2530 void GuiApplication::exit(int status)
2532 QApplication::exit(status);
2536 void GuiApplication::setGuiLanguage()
2540 // install translation file for Qt built-in dialogs
2541 QString const language_name = QString("qt_") + theLocale.name();
2542 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2543 // Short-named translator can be loaded from a long name, but not the
2544 // opposite. Therefore, long name should be used without truncation.
2545 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2546 if (!d->qt_trans_.load(language_name,
2547 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2548 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2551 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2555 switch (theLocale.language()) {
2556 case QLocale::Arabic :
2557 case QLocale::Hebrew :
2558 case QLocale::Persian :
2559 case QLocale::Urdu :
2560 setLayoutDirection(Qt::RightToLeft);
2563 setLayoutDirection(Qt::LeftToRight);
2568 void GuiApplication::execBatchCommands()
2573 if (!readUIFile(toqstr(lyxrc.ui_file)))
2574 // Gives some error box here.
2578 #if QT_VERSION > 0x040600
2579 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2581 #if QT_VERSION > 0x050100
2582 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2584 // Create the global default menubar which is shown for the dialogs
2585 // and if no GuiView is visible.
2586 // This must be done after the session was recovered to know the "last files".
2587 d->global_menubar_ = new QMenuBar(0);
2588 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2591 lyx::execBatchCommands();
2595 QAbstractItemModel * GuiApplication::languageModel()
2597 if (d->language_model_)
2598 return d->language_model_;
2600 QStandardItemModel * lang_model = new QStandardItemModel(this);
2601 lang_model->insertColumns(0, 3);
2602 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2603 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2604 Languages::const_iterator it = lyx::languages.begin();
2605 Languages::const_iterator end = lyx::languages.end();
2606 for (; it != end; ++it) {
2607 int current_row = lang_model->rowCount();
2608 lang_model->insertRows(current_row, 1);
2609 QModelIndex pl_item = lang_model->index(current_row, 0);
2610 QModelIndex sp_item = lang_model->index(current_row, 1);
2611 QModelIndex th_item = lang_model->index(current_row, 2);
2612 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2613 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2614 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2615 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2616 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2617 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2618 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2619 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2620 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2621 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2623 d->language_model_ = new QSortFilterProxyModel(this);
2624 d->language_model_->setSourceModel(lang_model);
2625 d->language_model_->setSortLocaleAware(true);
2626 return d->language_model_;
2630 void GuiApplication::restoreGuiSession()
2632 if (!lyxrc.load_session)
2635 Session & session = theSession();
2636 LastOpenedSection::LastOpened const & lastopened =
2637 session.lastOpened().getfiles();
2639 validateCurrentView();
2641 FileName active_file;
2642 // do not add to the lastfile list since these files are restored from
2643 // last session, and should be already there (regular files), or should
2644 // not be added at all (help files).
2645 for (size_t i = 0; i < lastopened.size(); ++i) {
2646 FileName const & file_name = lastopened[i].file_name;
2647 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2648 && current_view_->documentBufferView() != 0)) {
2649 boost::crc_32_type crc;
2650 string const & fname = file_name.absFileName();
2651 crc = for_each(fname.begin(), fname.end(), crc);
2652 createView(crc.checksum());
2654 current_view_->loadDocument(file_name, false);
2656 if (lastopened[i].active)
2657 active_file = file_name;
2660 // Restore last active buffer
2661 Buffer * buffer = theBufferList().getBuffer(active_file);
2662 if (buffer && current_view_)
2663 current_view_->setBuffer(buffer);
2665 // clear this list to save a few bytes of RAM
2666 session.lastOpened().clear();
2670 QString const GuiApplication::romanFontName()
2673 font.setStyleHint(QFont::Serif);
2674 font.setFamily("serif");
2676 return QFontInfo(font).family();
2680 QString const GuiApplication::sansFontName()
2683 font.setStyleHint(QFont::SansSerif);
2684 font.setFamily("sans");
2686 return QFontInfo(font).family();
2690 QString const GuiApplication::typewriterFontName()
2692 return QFontInfo(typewriterSystemFont()).family();
2697 // We cannot use QFont::fixedPitch() because it doesn't
2698 // return the fact but only if it is requested.
2699 static bool isFixedPitch(const QFont & font) {
2700 const QFontInfo fi(font);
2701 return fi.fixedPitch();
2706 QFont const GuiApplication::typewriterSystemFont()
2708 #if QT_VERSION >= 0x050200
2709 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2711 QFont font("monospace");
2713 if (!isFixedPitch(font)) {
2714 // try to enforce a real monospaced font
2715 font.setStyleHint(QFont::Monospace);
2716 if (!isFixedPitch(font)) {
2717 font.setStyleHint(QFont::TypeWriter);
2718 if (!isFixedPitch(font)) font.setFamily("courier");
2722 // On a Mac the result is too small and it's not practical to
2723 // rely on Qtconfig utility to change the system settings of Qt.
2724 font.setPointSize(12);
2730 void GuiApplication::handleRegularEvents()
2732 ForkedCallsController::handleCompletedProcesses();
2736 bool GuiApplication::event(QEvent * e)
2739 case QEvent::FileOpen: {
2740 // Open a file; this happens only on Mac OS X for now.
2742 // We do this asynchronously because on startup the batch
2743 // commands are not executed here yet and the gui is not ready
2745 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2746 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2747 processFuncRequestAsync(fr);
2751 #if (QT_VERSION < 0x050000)
2752 // Qt5 uses a signal for that, see above.
2753 case QEvent::KeyboardLayoutChange:
2754 //LYXERR0("keyboard change");
2755 if (currentView() && currentView()->currentBufferView())
2756 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2761 return QApplication::event(e);
2766 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2769 return QApplication::notify(receiver, event);
2771 catch (ExceptionMessage const & e) {
2773 case ErrorException:
2775 setQuitOnLastWindowClosed(false);
2777 Alert::error(e.title_, e.details_);
2779 // Properly crash in debug mode in order to get a useful backtrace.
2782 // In release mode, try to exit gracefully.
2784 // FIXME: GCC 7 thinks we can fall through here. Can we?
2786 case BufferException: {
2787 if (!current_view_ || !current_view_->documentBufferView())
2789 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2790 docstring details = e.details_ + '\n';
2791 details += buf->emergencyWrite();
2792 theBufferList().release(buf);
2793 details += "\n" + _("The current document was closed.");
2794 Alert::error(e.title_, details);
2797 case WarningException:
2798 Alert::warning(e.title_, e.details_);
2802 catch (exception const & e) {
2803 docstring s = _("LyX has caught an exception, it will now "
2804 "attempt to save all unsaved documents and exit."
2806 s += from_ascii(e.what());
2807 Alert::error(_("Software exception Detected"), s);
2811 docstring s = _("LyX has caught some really weird exception, it will "
2812 "now attempt to save all unsaved documents and exit.");
2813 Alert::error(_("Software exception Detected"), s);
2821 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2823 QColor const & qcol = d->color_cache_.get(col);
2824 if (!qcol.isValid()) {
2830 rgbcol.r = qcol.red();
2831 rgbcol.g = qcol.green();
2832 rgbcol.b = qcol.blue();
2837 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2839 QColor const qcol(lcolor.getX11Name(col).c_str());
2840 if (!qcol.isValid()) {
2846 rgbcol.r = qcol.red();
2847 rgbcol.g = qcol.green();
2848 rgbcol.b = qcol.blue();
2853 string const GuiApplication::hexName(ColorCode col)
2855 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2859 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2861 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2862 d->socket_notifiers_[fd] = sn;
2863 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2867 void GuiApplication::socketDataReceived(int fd)
2869 d->socket_notifiers_[fd]->func_();
2873 void GuiApplication::unregisterSocketCallback(int fd)
2875 d->socket_notifiers_.take(fd)->setEnabled(false);
2879 void GuiApplication::commitData(QSessionManager & sm)
2881 /** The implementation is required to avoid an application exit
2882 ** when session state save is triggered by session manager.
2883 ** The default implementation sends a close event to all
2884 ** visible top level widgets when session management allows
2886 ** We are changing that to check the state of each buffer in all
2887 ** views and ask the users what to do if buffers are dirty.
2888 ** Furthermore, we save the session state.
2889 ** We do NOT close the views here since the user still can cancel
2890 ** the logout process (see #9277); also, this would hide LyX from
2891 ** an OSes own session handling (application restoration).
2893 #ifdef QT_NO_SESSIONMANAGER
2895 #warning Qt is compiled without session manager
2897 #pragma message("warning: Qt is compiled without session manager")
2901 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2909 void GuiApplication::unregisterView(GuiView * gv)
2911 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2912 d->views_.remove(gv->id());
2913 if (current_view_ == gv)
2919 bool GuiApplication::closeAllViews()
2921 if (d->views_.empty())
2924 // When a view/window was closed before without quitting LyX, there
2925 // are already entries in the lastOpened list.
2926 theSession().lastOpened().clear();
2928 QList<GuiView *> const views = d->views_.values();
2929 for (GuiView * view : views) {
2930 if (!view->closeScheduled())
2939 bool GuiApplication::prepareAllViewsForLogout()
2941 if (d->views_.empty())
2944 QList<GuiView *> const views = d->views_.values();
2945 for (GuiView * view : views) {
2946 if (!view->prepareAllBuffersForLogout())
2954 GuiView & GuiApplication::view(int id) const
2956 LAPPERR(d->views_.contains(id));
2957 return *d->views_.value(id);
2961 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2963 QList<GuiView *> const views = d->views_.values();
2964 for (GuiView * view : views)
2965 view->hideDialog(name, inset);
2969 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2971 Buffer const * buf = 0;
2972 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2973 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2974 if (Buffer const * ptr = (*it)->updateInset(inset))
2981 bool GuiApplication::searchMenu(FuncRequest const & func,
2982 docstring_list & names) const
2984 BufferView * bv = 0;
2986 bv = current_view_->currentBufferView();
2987 return d->menus_.searchMenu(func, names, bv);
2991 bool GuiApplication::hasBufferView() const
2993 return (current_view_ && current_view_->currentBufferView());
2997 // Ensure that a file is read only once (prevents include loops)
2998 static QStringList uifiles;
2999 // store which ui files define Toolbars
3000 static QStringList toolbar_uifiles;
3003 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
3014 LexerKeyword uitags[] = {
3015 { "format", ui_format },
3016 { "include", ui_include },
3017 { "menuset", ui_menuset },
3018 { "toolbars", ui_toolbars },
3019 { "toolbarset", ui_toolbarset }
3023 lex.setFile(ui_path);
3025 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3029 if (lyxerr.debugging(Debug::PARSER))
3030 lex.printTable(lyxerr);
3033 // format before introduction of format tag
3034 unsigned int format = 0;
3035 while (lex.isOK()) {
3036 int const status = lex.lex();
3038 // we have to do this check here, outside the switch,
3039 // because otherwise we would start reading include files,
3040 // e.g., if the first tag we hit was an include tag.
3041 if (status == ui_format)
3043 format = lex.getInteger();
3047 // this will trigger unless the first tag we hit is a format
3048 // tag, with the right format.
3049 if (format != LFUN_FORMAT)
3050 return FormatMismatch;
3053 case Lexer::LEX_FEOF:
3058 QString const file = toqstr(lex.getString());
3059 bool const success = readUIFile(file, true);
3061 LYXERR0("Failed to read included file: " << fromqstr(file));
3068 d->menus_.read(lex);
3072 d->toolbars_.readToolbars(lex);
3076 d->toolbars_.readToolbarSettings(lex);
3077 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3081 if (!rtrim(lex.getString()).empty())
3082 lex.printError("LyX::ReadUIFile: "
3083 "Unknown menu tag: `$$Token'");
3085 LYXERR0("Error with status: " << status);
3091 return (error ? ReadError : ReadOK);
3095 bool GuiApplication::readUIFile(QString const & name, bool include)
3097 LYXERR(Debug::INIT, "About to read " << name << "...");
3101 ui_path = libFileSearch("ui", name, "inc");
3102 if (ui_path.empty())
3103 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3105 ui_path = libFileSearch("ui", name, "ui");
3108 if (ui_path.empty()) {
3109 static const QString defaultUIFile = "default";
3110 LYXERR(Debug::INIT, "Could not find " << name);
3112 Alert::warning(_("Could not find UI definition file"),
3113 bformat(_("Error while reading the included file\n%1$s\n"
3114 "Please check your installation."), qstring_to_ucs4(name)));
3117 if (name == defaultUIFile) {
3118 LYXERR(Debug::INIT, "Could not find default UI file!!");
3119 Alert::warning(_("Could not find default UI file"),
3120 _("LyX could not find the default UI file!\n"
3121 "Please check your installation."));
3124 Alert::warning(_("Could not find UI definition file"),
3125 bformat(_("Error while reading the configuration file\n%1$s\n"
3126 "Falling back to default.\n"
3127 "Please look under Tools>Preferences>User Interface and\n"
3128 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3129 return readUIFile(defaultUIFile, false);
3132 QString const uifile = toqstr(ui_path.absFileName());
3133 if (uifiles.contains(uifile)) {
3135 // We are reading again the top uifile so reset the safeguard:
3138 d->toolbars_.reset();
3140 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3141 << "Is this an include loop?");
3145 uifiles.push_back(uifile);
3147 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3149 ReturnValues retval = readUIFile(ui_path);
3151 if (retval == FormatMismatch) {
3152 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3153 TempFile tmp("convertXXXXXX.ui");
3154 FileName const tempfile = tmp.name();
3155 bool const success = prefs2prefs(ui_path, tempfile, true);
3157 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3158 " to format " << LFUN_FORMAT << ".");
3160 retval = readUIFile(tempfile);
3164 if (retval != ReadOK) {
3165 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3173 settings.beginGroup("ui_files");
3174 bool touched = false;
3175 for (int i = 0; i != uifiles.size(); ++i) {
3176 QFileInfo fi(uifiles[i]);
3177 QDateTime const date_value = fi.lastModified();
3178 QString const name_key = QString::number(i);
3179 // if an ui file which defines Toolbars has changed,
3180 // we have to reset the settings
3181 if (toolbar_uifiles.contains(uifiles[i])
3182 && (!settings.contains(name_key)
3183 || settings.value(name_key).toString() != uifiles[i]
3184 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3186 settings.setValue(name_key, uifiles[i]);
3187 settings.setValue(name_key + "/date", date_value);
3190 settings.endGroup();
3192 settings.remove("views");
3198 void GuiApplication::onLastWindowClosed()
3200 if (d->global_menubar_)
3201 d->global_menubar_->grabKeyboard();
3205 void GuiApplication::startLongOperation() {
3206 d->key_checker_.start();
3210 bool GuiApplication::longOperationCancelled() {
3211 return d->key_checker_.pressed();
3215 void GuiApplication::stopLongOperation() {
3216 d->key_checker_.stop();
3220 bool GuiApplication::longOperationStarted() {
3221 return d->key_checker_.started();
3225 ////////////////////////////////////////////////////////////////////////
3227 // X11 specific stuff goes here...
3230 bool GuiApplication::x11EventFilter(XEvent * xev)
3235 switch (xev->type) {
3236 case SelectionRequest: {
3237 if (xev->xselectionrequest.selection != XA_PRIMARY)
3239 LYXERR(Debug::SELECTION, "X requested selection.");
3240 BufferView * bv = current_view_->currentBufferView();
3242 docstring const sel = bv->requestSelection();
3244 d->selection_.put(sel);
3245 // Refresh the selection request timestamp.
3246 // We have to do this by ourselves as Qt seems
3247 // not doing that, maybe because of our
3248 // "persistent selection" implementation
3249 // (see comments in GuiSelection.cpp).
3250 XSelectionEvent nev;
3251 nev.type = SelectionNotify;
3252 nev.display = xev->xselectionrequest.display;
3253 nev.requestor = xev->xselectionrequest.requestor;
3254 nev.selection = xev->xselectionrequest.selection;
3255 nev.target = xev->xselectionrequest.target;
3256 nev.property = 0L; // None
3257 nev.time = CurrentTime;
3258 XSendEvent(QX11Info::display(),
3259 nev.requestor, False, 0,
3260 reinterpret_cast<XEvent *>(&nev));
3266 case SelectionClear: {
3267 if (xev->xselectionclear.selection != XA_PRIMARY)
3269 LYXERR(Debug::SELECTION, "Lost selection.");
3270 BufferView * bv = current_view_->currentBufferView();
3272 bv->clearSelection();
3278 #elif defined(QPA_XCB)
3279 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3280 void * message, long *)
3282 if (!current_view_ || eventType != "xcb_generic_event_t")
3285 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3287 switch (ev->response_type) {
3288 case XCB_SELECTION_REQUEST: {
3289 xcb_selection_request_event_t * srev =
3290 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3291 if (srev->selection != XCB_ATOM_PRIMARY)
3293 LYXERR(Debug::SELECTION, "X requested selection.");
3294 BufferView * bv = current_view_->currentBufferView();
3296 docstring const sel = bv->requestSelection();
3298 d->selection_.put(sel);
3299 #ifdef HAVE_QT5_X11_EXTRAS
3300 // Refresh the selection request timestamp.
3301 // We have to do this by ourselves as Qt seems
3302 // not doing that, maybe because of our
3303 // "persistent selection" implementation
3304 // (see comments in GuiSelection.cpp).
3305 // It is expected that every X11 event is
3306 // 32 bytes long, even if not all 32 bytes are
3308 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3309 struct alignas(32) padded_event
3310 : xcb_selection_notify_event_t {};
3311 padded_event nev = {};
3312 nev.response_type = XCB_SELECTION_NOTIFY;
3313 nev.requestor = srev->requestor;
3314 nev.selection = srev->selection;
3315 nev.target = srev->target;
3316 nev.property = XCB_NONE;
3317 nev.time = XCB_CURRENT_TIME;
3318 xcb_connection_t * con = QX11Info::connection();
3319 xcb_send_event(con, 0, srev->requestor,
3320 XCB_EVENT_MASK_NO_EVENT,
3321 reinterpret_cast<char const *>(&nev));
3329 case XCB_SELECTION_CLEAR: {
3330 xcb_selection_clear_event_t * scev =
3331 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3332 if (scev->selection != XCB_ATOM_PRIMARY)
3334 LYXERR(Debug::SELECTION, "Lost selection.");
3335 BufferView * bv = current_view_->currentBufferView();
3337 bv->clearSelection();
3345 } // namespace frontend
3348 void hideDialogs(std::string const & name, Inset * inset)
3351 frontend::guiApp->hideDialogs(name, inset);
3355 ////////////////////////////////////////////////////////////////////
3359 ////////////////////////////////////////////////////////////////////
3361 frontend::FontLoader & theFontLoader()
3363 LAPPERR(frontend::guiApp);
3364 return frontend::guiApp->fontLoader();
3368 frontend::FontMetrics const & theFontMetrics(Font const & f)
3370 return theFontMetrics(f.fontInfo());
3374 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3376 LAPPERR(frontend::guiApp);
3377 return frontend::guiApp->fontLoader().metrics(f);
3381 ////////////////////////////////////////////////////////////////////
3385 ////////////////////////////////////////////////////////////////////
3387 frontend::Clipboard & theClipboard()
3389 LAPPERR(frontend::guiApp);
3390 return frontend::guiApp->clipboard();
3394 frontend::Selection & theSelection()
3396 LAPPERR(frontend::guiApp);
3397 return frontend::guiApp->selection();
3403 #include "moc_GuiApplication.cpp"