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"
19 #include "GuiClipboard.h"
20 #include "GuiSelection.h"
23 #include "qt_helpers.h"
26 #include "frontends/alert.h"
27 #include "frontends/Application.h"
28 #include "frontends/FontLoader.h"
29 #include "frontends/FontMetrics.h"
32 #include "BufferList.h"
33 #include "BufferParams.h"
34 #include "BufferView.h"
37 #include "Converter.h"
39 #include "CutAndPaste.h"
40 #include "ErrorList.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
44 #include "GuiWorkArea.h"
48 #include "LaTeXPackages.h"
51 #include "LyXAction.h"
53 #include "Paragraph.h"
56 #include "SpellChecker.h"
57 #include "Thesaurus.h"
60 #include "insets/InsetText.h"
62 #include "support/checksum.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/AppleSupport.h"
82 #include "support/linkback/LinkBackProxy.h"
90 #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>
155 using namespace lyx::support;
160 frontend::Application * createApplication(int & argc, char * argv[])
162 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
163 // prune -geometry argument(s) by shifting
164 // the following ones 2 places down.
165 for (int i = 0 ; i < argc ; ++i) {
166 if (strcmp(argv[i], "-geometry") == 0) {
167 int const remove = (i+1) < argc ? 2 : 1;
169 for (int j = i; j < argc; ++j)
170 argv[j] = argv[j + remove];
176 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
177 // On Windows, allow bringing the LyX window to top
178 AllowSetForegroundWindow(ASFW_ANY);
181 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
182 // I'd rather do that in the constructor, but I do not think that
183 // the palette is accessible there.
184 guiApp->colorCache().setPalette(guiApp->palette());
193 if (lyxrc.gui_language == "auto") {
194 theLocale = QLocale::system();
195 code = fromqstr(theLocale.name());
197 Language const * l = languages.getLanguage(lyxrc.gui_language);
198 code = l ? l->code() : "C";
199 theLocale = QLocale(toqstr(code));
201 // Qt tries to outsmart us and transforms en_US to C.
202 Messages::guiLanguage((code == "C") ? "en_US" : code);
203 QLocale::setDefault(theLocale);
204 setlocale(LC_NUMERIC, "C");
211 /// Return the list of loadable formats.
212 vector<string> loadableImageFormats()
216 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
218 LYXERR(Debug::GRAPHICS,
219 "\nThe image loader can load the following directly:\n");
221 if (qt_formats.empty())
222 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
224 bool jpeg_found = false;
225 bool jpg_found = false;
226 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
228 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
230 string ext = ascii_lowercase((const char *) *it);
238 else if (ext == "jpg") {
243 else if (lyxrc.use_converter_cache &&
244 (ext == "svg" || ext == "svgz") &&
245 theConverters().isReachable("svg", "png"))
246 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
247 // the SVG as in the output. However we require that the converter
248 // cache is enabled since this is expensive. We also require that
249 // an explicit svg->png converter is defined, since the default
250 // converter could produce bad quality as well. This assumes that
251 // png can always be loaded.
260 ////////////////////////////////////////////////////////////////////////
262 // Icon loading support code
264 ////////////////////////////////////////////////////////////////////////
274 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
276 return lhs.key < rhs.key;
282 CompareKey(QString const & name) : name_(name) {}
283 bool operator()(ImgMap const & other) const { return other.key == name_; }
289 // this must be sorted alphabetically
290 // Upper case comes before lower case
291 // Please don't change the formatting, this list is parsed by
292 // development/tools/generate_symbols_images.py.
293 ImgMap sorted_img_map[] = {
294 { "Arrownot", "arrownot2"},
295 { "Arrowvert", "arrowvert2"},
296 { "Bowtie", "bowtie2" },
298 { "Bumpeq", "bumpeq2" },
299 { "CIRCLE", "circle3" },
301 { "CheckedBox", "checkedbox2" },
302 { "Circle", "circle2" },
303 { "Colonapprox", "colonapprox2" },
304 { "Coloneq", "coloneq2" },
305 { "Coloneqq", "coloneqq2" },
306 { "Colonsim", "colonsim2" },
308 { "DOWNarrow", "downarrow3" },
309 { "Delta", "delta2" },
310 { "Diamond", "diamond2" },
311 { "Doteq", "doteq2" },
312 { "Downarrow", "downarrow2" },
313 { "Eqcolon", "eqcolon2" },
314 { "Eqqcolon", "eqqcolon2" },
315 { "Gamma", "gamma2" },
317 { "LEFTCIRCLE", "leftcircle3" },
318 { "LEFTarrow", "leftarrow3" },
319 { "LEFTcircle", "leftcircle4" },
321 { "Lambda", "lambda2" },
323 { "Leftarrow", "leftarrow2" },
324 { "Leftcircle", "leftcircle2" },
325 { "Leftrightarrow", "leftrightarrow2" },
326 { "Longarrownot", "longarrownot2"},
327 { "Longleftarrow", "longleftarrow2" },
328 { "Longleftrightarrow", "longleftrightarrow2" },
329 { "Longmapsfrom", "longmapsfrom2"},
330 { "Longmapsto", "longmapsto2"},
331 { "Longrightarrow", "longrightarrow2" },
332 { "Mapsfrom", "mapsfrom2"},
333 { "Mapsfromchar", "mapsfromchar2"},
334 { "Mapsto", "mapsto2"},
335 { "Mapstochar", "mapstochar2"},
336 { "Omega", "omega2" },
341 { "RIGHTCIRCLE", "rightcircle3" },
342 { "RIGHTarrow", "rightarrow3" },
343 { "RIGHTcircle", "rightcircle4" },
345 { "Rightarrow", "rightarrow2" },
346 { "Rightcircle", "rightcircle2" },
347 { "Sigma", "sigma2" },
348 { "Square", "square2" },
349 { "Subset", "subset2" },
350 { "Supset", "supset2" },
351 { "Theta", "theta2" },
352 { "Thorn", "thorn2" },
353 { "UParrow", "uparrow3" },
354 { "Uparrow", "uparrow2" },
355 { "Updownarrow", "updownarrow2" },
356 { "Upsilon", "upsilon2" },
357 { "Vdash", "vdash3" },
362 { "lVert", "vert2" },
364 { "nLeftarrow", "nleftarrow2" },
365 { "nLeftrightarrow", "nleftrightarrow2" },
366 { "nRightarrow", "nrightarrow2" },
367 { "nVDash", "nvdash3" },
368 { "nVdash", "nvdash4" },
369 { "nvDash", "nvdash2" },
370 { "rVert", "vert2" },
372 { "textrm \\AA", "textrm_AA"},
373 { "textrm \\O", "textrm_O"},
374 { "vDash", "vdash2" },
375 { "varDelta", "vardelta2" },
376 { "varGamma", "vargamma2" },
377 { "varLambda", "varlambda2" },
378 { "varOmega", "varomega2" },
379 { "varPhi", "varphi2" },
380 { "varPi", "varpi2" },
381 { "varPsi", "varpsi2" },
382 { "varSigma", "varsigma2" },
383 { "varTheta", "vartheta2" },
384 { "varUpsilon", "varupsilon2" },
385 { "varXi", "varxi2" }
389 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
391 // This list specifies which system's theme icon is related to which lyx
392 // command. It was based on:
393 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
394 // this must be sorted alphabetically
395 // Upper case comes before lower case
396 ImgMap sorted_theme_icon_map[] = {
397 { "bookmark-goto 0", "go-jump" },
398 { "buffer-new", "document-new" },
399 { "buffer-write", "document-save" },
400 { "buffer-write-as", "document-save-as" },
401 { "buffer-zoom-in", "zoom-in" },
402 { "buffer-zoom-out", "zoom-out" },
403 { "copy", "edit-copy" },
404 { "cut", "edit-cut" },
405 { "depth-decrement", "format-indent-less" },
406 { "depth-increment", "format-indent-more" },
407 { "dialog-show spellchecker", "tools-check-spelling" },
408 { "dialog-show-new-inset graphics", "insert-image" },
409 { "dialog-toggle findreplaceadv", "edit-find-replace" },
410 { "file-open", "document-open" },
411 { "font-bold", "format-text-bold" },
412 { "font-ital", "format-text-italic" },
413 { "font-strikeout", "format-text-strikethrough" },
414 { "font-underline", "format-text-underline" },
415 { "lyx-quit", "application-exit" },
416 { "paste", "edit-paste" },
417 { "redo", "edit-redo" },
418 { "undo", "edit-undo" },
419 { "window-close", "window-close" },
420 { "window-new", "window-new" }
423 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
426 QString findImg(QString const & name)
428 ImgMap const * const begin = sorted_img_map;
429 ImgMap const * const end = begin + nr_sorted_img_map;
430 LATTEST(sorted(begin, end));
432 ImgMap const * const it = find_if(begin, end, CompareKey(name));
436 img_name = it->value;
439 img_name.replace('_', "underscore");
440 img_name.replace(' ', '_');
442 // This way we can have "math-delim { }" on the toolbar.
443 img_name.replace('(', "lparen");
444 img_name.replace(')', "rparen");
445 img_name.replace('[', "lbracket");
446 img_name.replace(']', "rbracket");
447 img_name.replace('{', "lbrace");
448 img_name.replace('}', "rbrace");
449 img_name.replace('|', "bars");
450 img_name.replace(',', "thinspace");
451 img_name.replace(':', "mediumspace");
452 img_name.replace(';', "thickspace");
453 img_name.replace('!', "negthinspace");
456 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
457 << "Looking for math icon called \"" << img_name << '"');
464 QString themeIconName(QString const & action)
466 ImgMap const * const begin = sorted_theme_icon_map;
467 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
468 LASSERT(sorted(begin, end), /**/);
470 ImgMap const * const it = find_if(begin, end, CompareKey(action));
478 // the returned bool is true if the icon needs to be flipped
479 pair<QString,bool> iconName(FuncRequest const & f, bool unknown, bool rtl)
482 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
484 if (!f.argument().empty()) {
485 // if there are arguments, first search an icon which name is the full thing
486 QString name = lfunname + ' ' + toqstr(f.argument());
487 name.replace(' ', '_');
488 name.replace(';', '_');
489 name.replace('\\', "backslash");
492 // then special default icon for some lfuns
493 switch (f.action()) {
494 case LFUN_MATH_INSERT:
495 names << "math/" + findImg(toqstr(f.argument()).mid(1));
497 case LFUN_MATH_DELIM:
498 case LFUN_MATH_BIGDELIM:
499 names << "math/" + findImg(toqstr(f.argument()));
502 names << "commands/" + toqstr(f.argument());
504 case LFUN_COMMAND_ALTERNATIVES: {
505 // use the first of the alternative commands
507 docstring dummy = split(f.argument(), firstcom, ';');
508 QString name1 = toqstr(firstcom);
509 name1.replace(' ', '_');
510 name1.replace(';', '_');
511 name1.replace('\\', "backslash");
520 // next thing to try is function name alone
523 // and finally maybe the unknown icon
527 search_mode const mode = theGuiApp()->imageSearchMode();
528 // The folders where icons are searched for
529 QStringList imagedirs;
530 imagedirs << "images/" << "images/ipa/";
531 // This is used to search for rtl version of icons which have the +rrtl suffix.
532 QStringList suffixes;
535 suffixes << QString();
537 for (QString const & imagedir : imagedirs)
538 for (QString const & name : names)
539 for (QString const & suffix : suffixes) {
540 QString id = imagedir;
541 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
543 return make_pair(toqstr(fname.absFileName()),
544 rtl && suffix.isEmpty());
547 LYXERR(Debug::GUI, "Cannot find icon for command \""
548 << lyxaction.getActionName(f.action())
549 << '(' << to_utf8(f.argument()) << ")\"");
551 return make_pair(QString(), false);
555 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
557 QString imagedir = path;
558 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
559 QString fpath = toqstr(fname.absFileName());
560 QPixmap pixmap = QPixmap();
562 if (pixmap.load(fpath))
565 bool const list = ext.contains(",");
566 LYXERR(Debug::GUI, "Cannot load pixmap \""
567 << path << "/" << name << "." << (list ? "{" : "") << ext
568 << (list ? "}" : "") << "\".");
574 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
576 #if (QT_VERSION >= 0x040600)
577 if (lyxrc.use_system_theme_icons) {
578 // use the icons from system theme that are available
579 QString action = toqstr(lyxaction.getActionName(f.action()));
580 if (!f.argument().empty())
581 action += " " + toqstr(f.argument());
582 QString const theme_icon = themeIconName(action);
583 if (QIcon::hasThemeIcon(theme_icon)) {
584 QIcon const thmicn = QIcon::fromTheme(theme_icon);
585 if (!thmicn.isNull())
593 tie(icon, flip) = iconName(f, unknown, rtl);
597 //LYXERR(Debug::GUI, "Found icon: " << icon);
598 QPixmap pixmap = QPixmap();
599 if (!pixmap.load(icon)) {
600 LYXERR0("Cannot load icon " << icon << ".");
605 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
607 return QIcon(pixmap);
611 ////////////////////////////////////////////////////////////////////////
613 // LyX server support code.
615 ////////////////////////////////////////////////////////////////////////
617 class SocketNotifier : public QSocketNotifier
620 /// connect a connection notification from the LyXServerSocket
621 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
622 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
626 /// The callback function
627 Application::SocketCallback func_;
631 class GuiTranslator : public QTranslator
634 GuiTranslator(QObject * parent = nullptr)
635 : QTranslator(parent)
638 QString translate(const char * /* context */,
639 const char *sourceText,
640 #if QT_VERSION >= 0x050000
641 const char * /* disambiguation */ = 0, int /* n */ = -1) const override
643 const char * /*comment*/ = 0) const override
646 // Here we declare the strings that need to be translated from Qt own GUI
647 // This is needed to include these strings to po files
651 _("Restore Defaults");
654 // Already in po: "Cancel", "&Cancel"
655 _("Apply"); // Already in po: "&Apply"
656 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
659 docstring s = getGuiMessages().getIfFound(sourceText);
660 // This test should eventually be removed when translations are updated
662 LYXERR(Debug::LOCALE, "Missing translation for `"
663 << string(sourceText) << "'");
669 ////////////////////////////////////////////////////////////////////////
671 // Mac specific stuff goes here...
673 ////////////////////////////////////////////////////////////////////////
676 // QMacPasteboardMimeGraphics can only be compiled on Mac.
678 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
681 QMacPasteboardMimeGraphics()
682 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
685 QString convertorName() { return "Graphics"; }
687 QString flavorFor(QString const & mime)
689 LYXERR(Debug::ACTION, "flavorFor " << mime);
690 if (mime == pdfMimeType())
691 return QLatin1String("com.adobe.pdf");
695 QString mimeFor(QString flav)
697 LYXERR(Debug::ACTION, "mimeFor " << flav);
698 if (flav == QLatin1String("com.adobe.pdf"))
699 return pdfMimeType();
703 bool canConvert(QString const & mime, QString flav)
705 return mimeFor(flav) == mime;
708 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
712 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
716 QList<QByteArray> convertFromMime(QString const & /*mime*/,
717 QVariant data, QString /*flav*/)
719 QList<QByteArray> ret;
720 ret.append(data.toByteArray());
726 ///////////////////////////////////////////////////////////////
728 // You can find more platform specific stuff at the end of this file...
730 ///////////////////////////////////////////////////////////////
732 ////////////////////////////////////////////////////////////////////////
733 // Windows specific stuff goes here...
735 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
736 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
737 // QWindowsMimeMetafile can only be compiled on Windows.
739 static FORMATETC cfFromMime(QString const & mimetype)
742 if (mimetype == emfMimeType()) {
743 formatetc.cfFormat = CF_ENHMETAFILE;
744 formatetc.tymed = TYMED_ENHMF;
745 } else if (mimetype == wmfMimeType()) {
746 formatetc.cfFormat = CF_METAFILEPICT;
747 formatetc.tymed = TYMED_MFPICT;
750 formatetc.dwAspect = DVASPECT_CONTENT;
751 formatetc.lindex = -1;
756 class QWindowsMimeMetafile : public QWINDOWSMIME {
758 QWindowsMimeMetafile() {}
760 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
761 QMimeData const * /*mimedata*/) const override
766 bool canConvertToMime(QString const & mimetype,
767 IDataObject * pDataObj) const override
769 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
771 FORMATETC formatetc = cfFromMime(mimetype);
772 return pDataObj->QueryGetData(&formatetc) == S_OK;
775 bool convertFromMime(FORMATETC const & /*formatetc*/,
776 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
781 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
782 QVariant::Type /*preferredType*/) const override
785 if (!canConvertToMime(mimetype, pDataObj))
788 FORMATETC formatetc = cfFromMime(mimetype);
790 if (pDataObj->GetData(&formatetc, &s) != S_OK)
794 if (s.tymed == TYMED_ENHMF) {
795 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
796 data.resize(dataSize);
797 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
798 (LPBYTE)data.data());
799 } else if (s.tymed == TYMED_MFPICT) {
800 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
801 data.resize(dataSize);
802 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
803 (LPBYTE)data.data());
806 ReleaseStgMedium(&s);
812 QVector<FORMATETC> formatsForMime(QString const & mimetype,
813 QMimeData const * /*mimedata*/) const override
815 QVector<FORMATETC> formats;
816 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
817 formats += cfFromMime(mimetype);
821 QString mimeForFormat(FORMATETC const & formatetc) const override
823 switch (formatetc.cfFormat) {
825 return emfMimeType();
826 case CF_METAFILEPICT:
827 return wmfMimeType();
837 /// Allows to check whether ESC was pressed during a long operation
838 class KeyChecker : public QObject {
843 KeyChecker() : pressed_(false), started_(false) {}
846 QCoreApplication::instance()->installEventFilter(this);
851 QCoreApplication::instance()->removeEventFilter(this);
855 QCoreApplication::processEvents();
858 bool started() const {
861 bool eventFilter(QObject *obj, QEvent *event) override {
862 LYXERR(Debug::ACTION, "Event Type: " << event->type());
863 switch (event->type()) {
867 case QEvent::UpdateRequest:
868 case QEvent::CursorChange:
869 case QEvent::ActionChanged:
870 case QEvent::EnabledChange:
871 case QEvent::SockAct:
874 case QEvent::ToolTipChange:
875 case QEvent::LayoutRequest:
876 case QEvent::MetaCall:
877 return QObject::eventFilter(obj, event);
879 // FIXME Blocking all these events is a bad idea.
880 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
881 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
889 ////////////////////////////////////////////////////////////////////////
890 // GuiApplication::Private definition and implementation.
891 ////////////////////////////////////////////////////////////////////////
893 struct GuiApplication::Private
895 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
896 global_menubar_(nullptr)
898 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
899 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
900 /// WMF Mime handler for Windows clipboard.
901 wmf_mime_ = new QWindowsMimeMetafile;
904 initKeySequences(&theTopLevelKeymap());
907 void initKeySequences(KeyMap * kb)
909 keyseq = KeySequence(kb, kb);
910 cancel_meta_seq = KeySequence(kb, kb);
914 QSortFilterProxyModel * language_model_;
916 GuiClipboard clipboard_;
918 GuiSelection selection_;
920 FontLoader font_loader_;
922 ColorCache color_cache_;
923 /// the built-in Qt translation mechanism
924 QTranslator qt_trans_;
925 /// LyX gettext-based translation for Qt elements
926 GuiTranslator gui_trans_;
928 QHash<int, SocketNotifier *> socket_notifiers_;
932 /// The global instance
935 /// this timer is used for any regular events one wants to
936 /// perform. at present it is used to check if forked processes
938 QTimer general_timer_;
940 /// delayed FuncRequests
941 std::queue<FuncRequest> func_request_queue_;
946 KeySequence cancel_meta_seq;
948 KeyModifier meta_fake_bit;
950 /// The result of last dispatch action
951 DispatchResult dispatch_result_;
953 /// Multiple views container.
955 * Warning: This must not be a smart pointer as the destruction of the
956 * object is handled by Qt when the view is closed
957 * \sa Qt::WA_DeleteOnClose attribute.
959 QHash<int, GuiView *> views_;
961 /// Only used on mac.
962 QMenuBar * global_menubar_;
965 /// Linkback mime handler for MacOSX.
966 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
969 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
970 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
971 /// WMF Mime handler for Windows clipboard.
972 QWindowsMimeMetafile * wmf_mime_;
976 /// Allows to check whether ESC was pressed during a long operation
977 KeyChecker key_checker_;
981 GuiApplication * guiApp;
983 GuiApplication::~GuiApplication()
986 closeAllLinkBackLinks();
992 GuiApplication::GuiApplication(int & argc, char ** argv)
993 : QApplication(argc, argv), current_view_(nullptr),
994 d(new GuiApplication::Private)
996 QString app_name = "LyX";
997 QCoreApplication::setOrganizationName(app_name);
998 QCoreApplication::setOrganizationDomain("lyx.org");
999 QCoreApplication::setApplicationName(lyx_package);
1000 #if QT_VERSION >= 0x050000
1001 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1004 #if QT_VERSION >= 0x050700
1005 setDesktopFileName(lyx_package);
1008 qsrand(QDateTime::currentDateTime().toTime_t());
1010 // Install LyX translator for missing Qt translations
1011 installTranslator(&d->gui_trans_);
1012 // Install Qt native translator for GUI elements.
1013 installTranslator(&d->qt_trans_);
1016 // Enable reception of XCB events.
1017 installNativeEventFilter(this);
1020 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1021 // lyxrc setting for this in order to let the application stay resident.
1022 // But then we need some kind of dock icon, at least on Windows.
1024 if (lyxrc.quit_on_last_window_closed)
1025 setQuitOnLastWindowClosed(false);
1028 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1029 // seems to be the default case for applications like LyX.
1030 setQuitOnLastWindowClosed(false);
1033 appleCleanupEditMenu();
1034 appleCleanupViewMenu();
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 #if QT_VERSION < 0x050000
1091 // Emulate platformName() for Qt4
1093 // FIXME: when ditching this method, remove all tests
1094 // platformName() == "qt4x11"
1096 QString GuiApplication::platformName() const
1098 # if defined(Q_WS_X11)
1099 // Note that this one does not really exist
1101 # elif defined(Q_OS_MAC)
1103 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1106 LYXERR0("Unknown platform!");
1113 double GuiApplication::pixelRatio() const
1115 #if QT_VERSION >= 0x050000
1116 return qt_scale_factor * devicePixelRatio();
1123 void GuiApplication::clearSession()
1130 docstring Application::iconName(FuncRequest const & f, bool unknown)
1132 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown, false).first);
1136 docstring Application::mathIcon(docstring const & c)
1138 return qstring_to_ucs4(findImg(toqstr(c)));
1142 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1146 BufferView * bv = nullptr;
1147 BufferView * doc_bv = nullptr;
1149 if (cmd.action() == LFUN_NOACTION) {
1150 status.message(from_utf8(N_("Nothing to do")));
1151 status.setEnabled(false);
1154 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1155 status.setUnknown(true);
1156 status.message(from_utf8(N_("Unknown action")));
1157 status.setEnabled(false);
1160 // Does the GuiApplication know something?
1161 else if (getStatus(cmd, status)) { }
1163 // If we do not have a GuiView, then other functions are disabled
1164 else if (!current_view_)
1165 status.setEnabled(false);
1167 // Does the GuiView know something?
1168 else if (current_view_->getStatus(cmd, status)) { }
1170 // In LyX/Mac, when a dialog is open, the menus of the
1171 // application can still be accessed without giving focus to
1172 // the main window. In this case, we want to disable the menu
1173 // entries that are buffer or view-related.
1174 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1176 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1177 status.setEnabled(false);
1180 // If we do not have a BufferView, then other functions are disabled
1181 else if (!(bv = current_view_->currentBufferView()))
1182 status.setEnabled(false);
1184 // Does the current BufferView know something?
1185 else if (bv->getStatus(cmd, status)) { }
1187 // Does the current Buffer know something?
1188 else if (bv->buffer().getStatus(cmd, status)) { }
1190 // If we do not have a document BufferView, different from the
1191 // current BufferView, then other functions are disabled
1192 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1193 status.setEnabled(false);
1195 // Does the document Buffer know something?
1196 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1199 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1200 status.message(from_utf8(N_("Command not handled")));
1201 status.setEnabled(false);
1204 // the default error message if we disable the command
1205 if (!status.enabled() && status.message().empty())
1206 status.message(from_utf8(N_("Command disabled")));
1212 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1214 // I would really like to avoid having this switch and rather try to
1215 // encode this in the function itself.
1216 // -- And I'd rather let an inset decide which LFUNs it is willing
1217 // to handle (Andre')
1219 switch (cmd.action()) {
1221 // This could be used for the no-GUI version. The GUI version is handled in
1222 // GuiView::getStatus(). See above.
1224 case LFUN_BUFFER_WRITE:
1225 case LFUN_BUFFER_WRITE_AS:
1226 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1227 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1228 enable = b && (b->isUnnamed() || !b->isClean());
1233 case LFUN_BOOKMARK_GOTO: {
1234 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1235 enable = theSession().bookmarks().isValid(num);
1239 case LFUN_BOOKMARK_CLEAR:
1240 enable = theSession().bookmarks().hasValid();
1243 // this one is difficult to get right. As a half-baked
1244 // solution, we consider only the first action of the sequence
1245 case LFUN_COMMAND_SEQUENCE: {
1246 // argument contains ';'-terminated commands
1247 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1248 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1249 func.setOrigin(cmd.origin());
1250 flag = getStatus(func);
1254 // we want to check if at least one of these is enabled
1255 case LFUN_COMMAND_ALTERNATIVES: {
1256 // argument contains ';'-terminated commands
1257 string arg = to_utf8(cmd.argument());
1258 while (!arg.empty()) {
1260 arg = split(arg, first, ';');
1261 FuncRequest func(lyxaction.lookupFunc(first));
1262 func.setOrigin(cmd.origin());
1263 flag = getStatus(func);
1264 // if this one is enabled, the whole thing is
1273 string name = to_utf8(cmd.argument());
1274 if (theTopLevelCmdDef().lock(name, func)) {
1275 func.setOrigin(cmd.origin());
1276 flag = getStatus(func);
1277 theTopLevelCmdDef().release(name);
1279 // catch recursion or unknown command
1280 // definition. all operations until the
1281 // recursion or unknown command definition
1282 // occurs are performed, so set the state to
1289 case LFUN_IF_RELATIVES: {
1290 string const lfun = to_utf8(cmd.argument());
1291 BufferView const * bv =
1292 current_view_ ? current_view_->currentBufferView() : nullptr;
1293 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1297 FuncRequest func(lyxaction.lookupFunc(lfun));
1298 func.setOrigin(cmd.origin());
1299 flag = getStatus(func);
1303 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1305 case LFUN_PREFERENCES_SAVE:
1306 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1307 case LFUN_DEBUG_LEVEL_SET:
1308 // these are handled in our dispatch()
1311 case LFUN_WINDOW_CLOSE:
1312 enable = !d->views_.empty();
1315 case LFUN_BUFFER_NEW:
1316 case LFUN_BUFFER_NEW_TEMPLATE:
1317 case LFUN_FILE_OPEN:
1318 case LFUN_HELP_OPEN:
1319 case LFUN_SCREEN_FONT_UPDATE:
1320 case LFUN_SET_COLOR:
1321 case LFUN_WINDOW_NEW:
1323 case LFUN_LYXRC_APPLY:
1324 case LFUN_COMMAND_PREFIX:
1326 case LFUN_META_PREFIX:
1327 case LFUN_RECONFIGURE:
1328 case LFUN_SERVER_GET_FILENAME:
1329 case LFUN_SERVER_NOTIFY:
1333 case LFUN_BUFFER_FORALL: {
1334 if (theBufferList().empty()) {
1335 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1336 flag.setEnabled(false);
1340 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1341 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1342 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1343 flag.setEnabled(false);
1348 case LFUN_DIALOG_SHOW: {
1349 string const name = cmd.getArg(0);
1350 return name == "aboutlyx"
1351 || name == "lyxfiles"
1353 || name == "texinfo"
1354 || name == "progress"
1355 || name == "compare";
1363 flag.setEnabled(false);
1367 /// make a post-dispatch status message
1368 static docstring makeDispatchMessage(docstring const & msg,
1369 FuncRequest const & cmd)
1371 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1372 || cmd.origin() == FuncRequest::TOOLBAR
1373 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1375 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1376 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1380 docstring dispatch_msg = msg;
1381 if (!dispatch_msg.empty())
1382 dispatch_msg += ' ';
1384 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1386 bool argsadded = false;
1388 if (!cmd.argument().empty()) {
1389 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1390 comname += ' ' + cmd.argument();
1394 docstring const shortcuts = theTopLevelKeymap().
1395 printBindings(cmd, KeySequence::ForGui);
1397 if (!shortcuts.empty())
1398 comname += ": " + shortcuts;
1399 else if (!argsadded && !cmd.argument().empty())
1400 comname += ' ' + cmd.argument();
1402 if (!comname.empty()) {
1403 comname = rtrim(comname);
1404 dispatch_msg += '(' + rtrim(comname) + ')';
1406 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1407 return dispatch_msg;
1411 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1415 Buffer * buffer = 0;
1416 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1417 //setCurrentView(cmd.view_origin); //does not work
1419 dr.setMessage(_("Wrong focus!"));
1420 d->dispatch_result_ = dr;
1421 return d->dispatch_result_;
1423 if (current_view_ && current_view_->currentBufferView()) {
1424 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1425 buffer = ¤t_view_->currentBufferView()->buffer();
1428 dr.screenUpdate(Update::FitCursor);
1430 // This handles undo groups automagically
1431 UndoGroupHelper ugh(buffer);
1433 // redraw the screen at the end (first of the two drawing steps).
1434 // This is done unless explicitly requested otherwise.
1435 // This code is kept inside the undo group because updateBuffer
1436 // can create undo actions (see #11292)
1437 updateCurrentView(cmd, dr);
1440 d->dispatch_result_ = dr;
1441 return d->dispatch_result_;
1445 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1450 BufferView * bv = current_view_->currentBufferView();
1452 if (dr.needBufferUpdate()) {
1453 bv->cursor().clearBufferUpdate();
1454 bv->buffer().updateBuffer();
1456 // BufferView::update() updates the ViewMetricsInfo and
1457 // also initializes the position cache for all insets in
1458 // (at least partially) visible top-level paragraphs.
1459 // We will redraw the screen only if needed.
1460 bv->processUpdateFlags(dr.screenUpdate());
1462 // Do we have a selection?
1463 theSelection().haveSelection(bv->cursor().selection());
1466 current_view_->restartCaret();
1468 if (dr.needMessageUpdate()) {
1469 // Some messages may already be translated, so we cannot use _()
1470 current_view_->message(makeDispatchMessage(
1471 translateIfPossible(dr.message()), cmd));
1476 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1477 bool switchToBuffer)
1479 if (!theSession().bookmarks().isValid(idx))
1481 BookmarksSection::Bookmark const & bm =
1482 theSession().bookmarks().bookmark(idx);
1483 LASSERT(!bm.filename.empty(), return);
1484 string const file = bm.filename.absFileName();
1485 // if the file is not opened, open it.
1486 if (!theBufferList().exists(bm.filename)) {
1488 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1492 // open may fail, so we need to test it again
1493 if (!theBufferList().exists(bm.filename))
1496 // bm can be changed when saving
1497 BookmarksSection::Bookmark tmp = bm;
1499 // Special case idx == 0 used for back-from-back jump navigation
1501 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1503 // if the current buffer is not that one, switch to it.
1504 BufferView * doc_bv = current_view_ ?
1505 current_view_->documentBufferView() : 0;
1506 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1507 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1508 if (switchToBuffer) {
1509 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1512 doc_bv = current_view_->documentBufferView();
1517 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1518 if (!doc_bv || !doc_bv->moveToPosition(
1519 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1522 Cursor & cur = doc_bv->cursor();
1523 if (old && cur != *old)
1524 notifyCursorLeavesOrEnters(*old, cur);
1530 // Cursor jump succeeded!
1531 pit_type new_pit = cur.pit();
1532 pos_type new_pos = cur.pos();
1533 int new_id = cur.paragraph().id();
1535 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1536 // see http://www.lyx.org/trac/ticket/3092
1537 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1538 || bm.top_id != new_id) {
1539 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1540 new_pit, new_pos, new_id);
1544 // This function runs "configure" and then rereads lyx.defaults to
1545 // reconfigure the automatic settings.
1546 void GuiApplication::reconfigure(string const & option)
1548 // emit message signal.
1550 current_view_->message(_("Running configure..."));
1552 // Run configure in user lyx directory
1553 string const lock_file = package().getConfigureLockName();
1554 int fd = fileLock(lock_file.c_str());
1555 int const ret = package().reconfigureUserLyXDir(option);
1556 // emit message signal.
1558 current_view_->message(_("Reloading configuration..."));
1559 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1560 // Re-read packages.lst
1561 LaTeXPackages::getAvailable();
1562 fileUnlock(fd, lock_file.c_str());
1565 Alert::information(_("System reconfiguration failed"),
1566 _("The system reconfiguration has failed.\n"
1567 "Default textclass is used but LyX may\n"
1568 "not be able to work properly.\n"
1569 "Please reconfigure again if needed."));
1571 Alert::information(_("System reconfigured"),
1572 _("The system has been reconfigured.\n"
1573 "You need to restart LyX to make use of any\n"
1574 "updated document class specifications."));
1577 void GuiApplication::validateCurrentView()
1579 if (!d->views_.empty() && !current_view_) {
1580 // currently at least one view exists but no view has the focus.
1581 // choose the last view to make it current.
1582 // a view without any open document is preferred.
1583 GuiView * candidate = 0;
1584 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1585 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1586 for (; it != end; ++it) {
1588 if (!candidate->documentBufferView())
1591 setCurrentView(candidate);
1595 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1597 string const argument = to_utf8(cmd.argument());
1598 FuncCode const action = cmd.action();
1600 LYXERR(Debug::ACTION, "cmd: " << cmd);
1602 // we have not done anything wrong yet.
1605 FuncStatus const flag = getStatus(cmd);
1606 if (!flag.enabled()) {
1607 // We cannot use this function here
1608 LYXERR(Debug::ACTION, "action "
1609 << lyxaction.getActionName(action)
1610 << " [" << action << "] is disabled at this location");
1611 dr.setMessage(flag.message());
1613 dr.dispatched(false);
1614 dr.screenUpdate(Update::None);
1615 dr.clearBufferUpdate();
1619 if (cmd.origin() == FuncRequest::LYXSERVER) {
1620 if (current_view_ && current_view_->currentBufferView())
1621 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1622 // we will also need to redraw the screen at the end
1623 dr.screenUpdate(Update::FitCursor);
1626 // Assumes that the action will be dispatched.
1627 dr.dispatched(true);
1629 switch (cmd.action()) {
1631 case LFUN_WINDOW_NEW:
1632 createView(toqstr(cmd.argument()));
1635 case LFUN_WINDOW_CLOSE:
1636 // update bookmark pit of the current buffer before window close
1637 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1638 gotoBookmark(i+1, false, false);
1639 // clear the last opened list, because
1640 // maybe this will end the session
1641 theSession().lastOpened().clear();
1642 // check for valid current_view_
1643 validateCurrentView();
1645 current_view_->closeScheduled();
1649 // quitting is triggered by the gui code
1650 // (leaving the event loop).
1652 current_view_->message(from_utf8(N_("Exiting.")));
1653 if (closeAllViews())
1657 case LFUN_SCREEN_FONT_UPDATE: {
1658 // handle the screen font changes.
1659 /* FIXME: this only updates the current document, whereas all
1660 * documents should see their metrics updated.
1662 d->font_loader_.update();
1663 dr.screenUpdate(Update::Force | Update::FitCursor);
1667 case LFUN_BUFFER_NEW:
1668 validateCurrentView();
1670 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1671 createView(QString(), false); // keep hidden
1672 current_view_->newDocument(to_utf8(cmd.argument()));
1673 current_view_->show();
1674 setActiveWindow(current_view_);
1676 current_view_->newDocument(to_utf8(cmd.argument()));
1680 case LFUN_BUFFER_NEW_TEMPLATE: {
1681 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1682 string const temp = cmd.getArg(1);
1683 validateCurrentView();
1685 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1687 current_view_->newDocument(file, temp, true);
1688 if (!current_view_->documentBufferView())
1689 current_view_->close();
1691 current_view_->newDocument(file, temp, true);
1696 case LFUN_FILE_OPEN: {
1697 // FIXME: normally the code below is not needed, since getStatus makes sure that
1698 // current_view_ is not null.
1699 validateCurrentView();
1700 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1701 string const fname = to_utf8(cmd.argument());
1702 bool const is_open = FileName::isAbsolute(fname)
1703 && theBufferList().getBuffer(FileName(fname));
1705 || (!lyxrc.open_buffers_in_tabs
1706 && current_view_->documentBufferView() != 0
1708 // We want the ui session to be saved per document and not per
1709 // window number. The filename crc is a good enough identifier.
1710 createView(support::checksum(fname));
1711 current_view_->openDocument(fname);
1712 if (!current_view_->documentBufferView())
1713 current_view_->close();
1714 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1715 current_view_->raise();
1716 current_view_->activateWindow();
1717 current_view_->showNormal();
1720 current_view_->openDocument(fname);
1721 if (cmd.origin() == FuncRequest::LYXSERVER) {
1722 current_view_->raise();
1723 current_view_->activateWindow();
1724 current_view_->showNormal();
1730 case LFUN_HELP_OPEN: {
1731 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1732 if (current_view_ == 0)
1734 string const arg = to_utf8(cmd.argument());
1736 current_view_->message(_("Missing argument"));
1739 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1741 fname = i18nLibFileSearch("examples", arg, "lyx");
1743 if (fname.empty()) {
1744 lyxerr << "LyX: unable to find documentation file `"
1745 << arg << "'. Bad installation?" << endl;
1748 current_view_->message(bformat(_("Opening help file %1$s..."),
1749 makeDisplayPath(fname.absFileName())));
1750 Buffer * buf = current_view_->loadDocument(fname, false);
1752 buf->setReadonly(!current_view_->develMode());
1756 case LFUN_SET_COLOR: {
1757 string const lyx_name = cmd.getArg(0);
1758 string const x11_name = cmd.getArg(1);
1759 if (lyx_name.empty() || x11_name.empty()) {
1761 current_view_->message(
1762 _("Syntax: set-color <lyx_name> <x11_name>"));
1767 // FIXME: The graphics cache no longer has a changeDisplay method.
1768 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1769 bool const graphicsbg_changed =
1770 lyx_name == graphicsbg && x11_name != graphicsbg;
1771 if (graphicsbg_changed)
1772 graphics::GCache::get().changeDisplay(true);
1775 if (!lcolor.setColor(lyx_name, x11_name)) {
1777 current_view_->message(
1778 bformat(_("Set-color \"%1$s\" failed "
1779 "- color is undefined or "
1780 "may not be redefined"),
1781 from_utf8(lyx_name)));
1784 // Make sure we don't keep old colors in cache.
1785 d->color_cache_.clear();
1786 // Update the current view
1787 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1791 case LFUN_LYXRC_APPLY: {
1792 // reset active key sequences, since the bindings
1793 // are updated (bug 6064)
1795 LyXRC const lyxrc_orig = lyxrc;
1797 istringstream ss(to_utf8(cmd.argument()));
1798 bool const success = lyxrc.read(ss);
1801 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1802 << "Unable to read lyxrc data"
1807 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1809 // If the request comes from the minibuffer, then we can't reset
1810 // the GUI, since that would destroy the minibuffer itself and
1811 // cause a crash, since we are currently in one of the methods of
1812 // GuiCommandBuffer. See bug #8540.
1813 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1816 // FIXME Unfortunately, that leaves a bug here, since we cannot
1817 // reset the GUI in this case. If the changes to lyxrc affected the
1818 // UI, then, nothing would happen. This seems fairly unlikely, but
1819 // it definitely is a bug.
1821 dr.forceBufferUpdate();
1825 case LFUN_COMMAND_PREFIX:
1826 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1831 d->meta_fake_bit = NoModifier;
1832 GuiView * gv = currentView();
1833 if (gv && gv->currentBufferView())
1834 // cancel any selection
1835 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1836 dr.setMessage(from_ascii(N_("Cancel")));
1839 case LFUN_META_PREFIX:
1840 d->meta_fake_bit = AltModifier;
1841 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1844 // --- Menus -----------------------------------------------
1845 case LFUN_RECONFIGURE:
1846 // argument is any additional parameter to the configure.py command
1847 reconfigure(to_utf8(cmd.argument()));
1850 // --- lyxserver commands ----------------------------
1851 case LFUN_SERVER_GET_FILENAME: {
1852 if (current_view_ && current_view_->documentBufferView()) {
1853 docstring const fname = from_utf8(
1854 current_view_->documentBufferView()->buffer().absFileName());
1855 dr.setMessage(fname);
1856 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1858 dr.setMessage(docstring());
1859 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1864 case LFUN_SERVER_NOTIFY: {
1865 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1866 dr.setMessage(dispatch_buffer);
1867 theServer().notifyClient(to_utf8(dispatch_buffer));
1871 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1872 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1878 string rest = split(argument, countstr, ' ');
1879 int const count = convert<int>(countstr);
1880 // an arbitrary number to limit number of iterations
1881 int const max_iter = 10000;
1882 if (count > max_iter) {
1883 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1886 for (int i = 0; i < count; ++i) {
1887 FuncRequest lfun = lyxaction.lookupFunc(rest);
1888 lfun.allowAsync(false);
1895 case LFUN_COMMAND_SEQUENCE: {
1896 // argument contains ';'-terminated commands
1897 string arg = argument;
1898 // FIXME: this LFUN should also work without any view.
1899 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1900 ? &(current_view_->documentBufferView()->buffer()) : 0;
1901 // This handles undo groups automagically
1902 UndoGroupHelper ugh(buffer);
1903 while (!arg.empty()) {
1905 arg = split(arg, first, ';');
1906 FuncRequest func(lyxaction.lookupFunc(first));
1907 func.allowAsync(false);
1908 func.setOrigin(cmd.origin());
1914 case LFUN_BUFFER_FORALL: {
1915 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1916 funcToRun.allowAsync(false);
1918 map<Buffer *, GuiView *> views_lVisible;
1919 map<GuiView *, Buffer *> activeBuffers;
1921 QList<GuiView *> allViews = d->views_.values();
1923 // this for does not modify any buffer. It just collects info on local
1924 // visibility of buffers and on which buffer is active in each view.
1925 Buffer * const last = theBufferList().last();
1926 for(GuiView * view : allViews) {
1927 // all of the buffers might be locally hidden. That is, there is no
1929 if (!view || !view->currentBufferView())
1930 activeBuffers[view] = 0;
1932 activeBuffers[view] = &view->currentBufferView()->buffer();
1934 // find out if each is locally visible or locally hidden.
1935 // we don't use a for loop as the buffer list cycles.
1936 Buffer * b = theBufferList().first();
1938 bool const locallyVisible = view && view->workArea(*b);
1939 if (locallyVisible) {
1940 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1941 // only need to overwrite/add if we don't already know a buffer is globally
1942 // visible or we do know but we would prefer to dispatch LFUN from the
1943 // current view because of cursor position issues.
1944 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1945 views_lVisible[b] = view;
1949 b = theBufferList().next(b);
1953 GuiView * const homeView = currentView();
1954 Buffer * b = theBufferList().first();
1955 Buffer * nextBuf = 0;
1956 int numProcessed = 0;
1959 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1961 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1963 // first change to a view where b is locally visible, preferably current_view_.
1964 GuiView * const vLv = views_lVisible[b];
1966 lyx::dispatch(funcToRun);
1974 // put things back to how they were (if possible).
1975 for (GuiView * view : allViews) {
1976 Buffer * originalBuf = activeBuffers[view];
1977 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1978 if (theBufferList().isLoaded(originalBuf))
1979 view->setBuffer(originalBuf);
1981 homeView->setFocus();
1983 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1987 case LFUN_COMMAND_ALTERNATIVES: {
1988 // argument contains ';'-terminated commands
1989 string arg = argument;
1990 while (!arg.empty()) {
1992 arg = split(arg, first, ';');
1993 FuncRequest func(lyxaction.lookupFunc(first));
1994 func.setOrigin(cmd.origin());
1995 FuncStatus const stat = getStatus(func);
1996 if (stat.enabled()) {
2006 if (theTopLevelCmdDef().lock(argument, func)) {
2007 func.setOrigin(cmd.origin());
2009 theTopLevelCmdDef().release(argument);
2011 if (func.action() == LFUN_UNKNOWN_ACTION) {
2012 // unknown command definition
2013 lyxerr << "Warning: unknown command definition `"
2017 // recursion detected
2018 lyxerr << "Warning: Recursion in the command definition `"
2019 << argument << "' detected"
2026 case LFUN_IF_RELATIVES: {
2027 string const lfun = to_utf8(cmd.argument());
2028 FuncRequest func(lyxaction.lookupFunc(lfun));
2029 func.setOrigin(cmd.origin());
2030 FuncStatus const stat = getStatus(func);
2031 if (stat.enabled()) {
2038 case LFUN_PREFERENCES_SAVE:
2039 lyxrc.write(support::makeAbsPath("preferences",
2040 package().user_support().absFileName()), false);
2043 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2044 string const fname = addName(addPath(package().user_support().absFileName(),
2045 "templates/"), "defaults.lyx");
2046 Buffer defaults(fname);
2048 istringstream ss(argument);
2053 // We need to make sure that, after we recreat the DocumentClass,
2054 // which we do in readHeader, we apply it to the document itself.
2055 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2056 int const unknown_tokens = defaults.readHeader(lex);
2057 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2059 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2060 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2062 if (unknown_tokens != 0) {
2063 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2064 << unknown_tokens << " unknown token"
2065 << (unknown_tokens == 1 ? "" : "s")
2069 if (defaults.writeFile(FileName(defaults.absFileName())))
2070 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2071 makeDisplayPath(fname)));
2074 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2079 case LFUN_BOOKMARK_GOTO:
2080 // go to bookmark, open unopened file and switch to buffer if necessary
2081 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2082 dr.screenUpdate(Update::Force | Update::FitCursor);
2085 case LFUN_BOOKMARK_CLEAR:
2086 theSession().bookmarks().clear();
2089 case LFUN_DEBUG_LEVEL_SET:
2090 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2093 case LFUN_DIALOG_SHOW: {
2094 string const name = cmd.getArg(0);
2096 if ( name == "aboutlyx"
2098 || name == "texinfo"
2099 || name == "progress"
2100 || name == "compare")
2102 // work around: on Mac OS the application
2103 // is not terminated when closing the last view.
2104 // Create a new one to be able to dispatch the
2105 // LFUN_DIALOG_SHOW to this view.
2106 if (current_view_ == 0)
2112 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2115 current_view_->dispatch(cmd, dr);
2119 if (cmd.origin() == FuncRequest::LYXSERVER)
2120 updateCurrentView(cmd, dr);
2124 docstring GuiApplication::viewStatusMessage()
2126 // When meta-fake key is pressed, show the key sequence so far + "M-".
2127 if (d->meta_fake_bit != NoModifier)
2128 return d->keyseq.print(KeySequence::ForGui) + "M-";
2130 // Else, when a non-complete key sequence is pressed,
2131 // show the available options.
2132 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2133 return d->keyseq.printOptions(true);
2139 string GuiApplication::inputLanguageCode() const
2141 #if (QT_VERSION < 0x050000)
2142 QLocale loc = keyboardInputLocale();
2144 QLocale loc = inputMethod()->locale();
2146 //LYXERR0("input lang = " << fromqstr(loc.name()));
2147 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2151 void GuiApplication::onLocaleChanged()
2153 //LYXERR0("Change language to " << inputLanguage()->lang());
2154 if (currentView() && currentView()->currentBufferView())
2155 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2159 void GuiApplication::handleKeyFunc(FuncCode action)
2163 if (d->keyseq.length())
2165 GuiView * gv = currentView();
2166 LASSERT(gv && gv->currentBufferView(), return);
2167 BufferView * bv = gv->currentBufferView();
2168 bv->getIntl().getTransManager().deadkey(
2169 c, get_accent(action).accent, bv->cursor().innerText(),
2171 // Need to clear, in case the minibuffer calls these
2174 // copied verbatim from do_accent_char
2175 bv->cursor().resetAnchor();
2179 //Keep this in sync with GuiApplication::processKeySym below
2180 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2181 KeyModifier state) const
2183 // Do nothing if we have nothing
2184 if (!keysym.isOK() || keysym.isModifier())
2186 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2188 FuncRequest func = seq.addkey(keysym, state);
2189 // When not cancel or meta-fake, do the normal lookup.
2190 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2192 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2194 // Maybe user can only reach the key via holding down shift.
2195 // Let's see. But only if shift is the only modifier
2196 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2197 // If addkey looked up a command and did not find further commands then
2198 // seq has been reset at this point
2199 func = seq.addkey(keysym, NoModifier);
2201 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2202 << seq.print(KeySequence::Portable) << ']');
2203 return func.action() != LFUN_UNKNOWN_ACTION;
2207 //Keep this in sync with GuiApplication::queryKeySym above
2208 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2210 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2212 // Do nothing if we have nothing (JMarc)
2213 if (!keysym.isOK() || keysym.isModifier()) {
2215 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2217 current_view_->restartCaret();
2221 char_type encoded_last_key = keysym.getUCSEncoded();
2223 // Do a one-deep top-level lookup for
2224 // cancel and meta-fake keys. RVDK_PATCH_5
2225 d->cancel_meta_seq.reset();
2227 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2228 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2230 // When not cancel or meta-fake, do the normal lookup.
2231 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2232 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2233 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2234 // remove Caps Lock and Mod2 as a modifiers
2235 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2236 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2239 // Don't remove this unless you know what you are doing.
2240 d->meta_fake_bit = NoModifier;
2242 // Can this happen now ?
2243 if (func.action() == LFUN_NOACTION)
2244 func = FuncRequest(LFUN_COMMAND_PREFIX);
2246 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2247 << d->keyseq.print(KeySequence::Portable) << ']');
2249 // already here we know if it any point in going further
2250 // why not return already here if action == -1 and
2251 // num_bytes == 0? (Lgb)
2253 if (d->keyseq.length() > 1 && current_view_)
2254 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2257 // Maybe user can only reach the key via holding down shift.
2258 // Let's see. But only if shift is the only modifier
2259 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2260 LYXERR(Debug::KEY, "Trying without shift");
2261 // If addkey looked up a command and did not find further commands then
2262 // seq has been reset at this point
2263 func = d->keyseq.addkey(keysym, NoModifier);
2264 LYXERR(Debug::KEY, "Action now " << func.action());
2267 if (func.action() == LFUN_UNKNOWN_ACTION) {
2268 // We didn't match any of the key sequences.
2269 // See if it's normal insertable text not already
2270 // covered by a binding
2271 if (keysym.isText() && d->keyseq.length() == 1) {
2272 // Non-printable characters (such as ASCII control characters)
2273 // must not be inserted (#5704)
2274 if (!isPrintable(encoded_last_key)) {
2275 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2277 current_view_->restartCaret();
2280 // The following modifier check is not needed on Mac.
2281 // The keysym is either not text or it is different
2282 // from the non-modifier keysym. See #9875 for the
2283 // broken alt-modifier effect of having this code active.
2284 #if !defined(Q_OS_MAC)
2285 // If a non-Shift Modifier is used we have a non-bound key sequence
2286 // (such as Alt+j = j). This should be omitted (#5575).
2287 // On Windows, AltModifier and ControlModifier are both
2288 // set when AltGr is pressed. Therefore, in order to not
2289 // break AltGr-bound symbols (see #5575 for details),
2290 // unbound Ctrl+Alt key sequences are allowed.
2291 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2292 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2293 && !(state & AltModifier && state & ControlModifier)
2297 if (current_view_) {
2298 current_view_->message(_("Unknown function."));
2299 current_view_->restartCaret();
2304 // Since all checks above were passed, we now really have text that
2305 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2306 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2308 LYXERR(Debug::KEY, "isText() is true, inserting.");
2309 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2311 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2312 if (current_view_) {
2313 current_view_->message(_("Unknown function."));
2314 current_view_->restartCaret();
2320 if (func.action() == LFUN_SELF_INSERT) {
2321 if (encoded_last_key != 0) {
2322 docstring const arg(1, encoded_last_key);
2323 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2324 FuncRequest::KEYBOARD));
2325 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2328 processFuncRequest(func);
2332 void GuiApplication::processFuncRequest(FuncRequest const & func)
2334 lyx::dispatch(func);
2338 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2340 addToFuncRequestQueue(func);
2341 processFuncRequestQueueAsync();
2345 void GuiApplication::processFuncRequestQueue()
2347 while (!d->func_request_queue_.empty()) {
2348 // take the item from the stack _before_ processing the
2349 // request in order to avoid race conditions from nested
2350 // or parallel requests (see #10406)
2351 FuncRequest const fr(d->func_request_queue_.front());
2352 d->func_request_queue_.pop();
2353 processFuncRequest(fr);
2358 void GuiApplication::processFuncRequestQueueAsync()
2360 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2364 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2366 d->func_request_queue_.push(func);
2370 void GuiApplication::resetGui()
2372 // Set the language defined by the user.
2376 if (!readUIFile(toqstr(lyxrc.ui_file)))
2377 // Gives some error box here.
2380 if (d->global_menubar_)
2381 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2383 QHash<int, GuiView *>::iterator it;
2384 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2387 gv->setLayoutDirection(layoutDirection());
2391 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2395 bool GuiApplication::rtlContext() const
2397 if (current_view_ && current_view_->currentBufferView()) {
2398 BufferView const * bv = current_view_->currentBufferView();
2399 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2401 return layoutDirection() == Qt::RightToLeft;
2405 void GuiApplication::createView(int view_id)
2407 createView(QString(), true, view_id);
2411 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2414 // release the keyboard which might have been grabbed by the global
2415 // menubar on Mac to catch shortcuts even without any GuiView.
2416 if (d->global_menubar_)
2417 d->global_menubar_->releaseKeyboard();
2421 while (d->views_.find(id) != d->views_.end())
2424 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2425 GuiView * view = new GuiView(id);
2426 // `view' is the new current_view_. Tell coverity that is is not 0.
2427 LATTEST(current_view_);
2429 d->views_[id] = view;
2433 setActiveWindow(view);
2436 if (!geometry_arg.isEmpty()) {
2437 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2441 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2442 re.indexIn(geometry_arg);
2443 w = re.cap(1).toInt();
2444 h = re.cap(2).toInt();
2445 x = re.cap(3).toInt();
2446 y = re.cap(4).toInt();
2447 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2448 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2449 // Set initial geometry such that we can get the frame size.
2450 view->setGeometry(x, y, w, h);
2451 int framewidth = view->geometry().x() - view->x();
2452 int titleheight = view->geometry().y() - view->y();
2453 // Negative displacements must be interpreted as distances
2454 // from the right or bottom screen borders.
2455 if (sx == '-' || sy == '-') {
2456 QRect rec = QApplication::desktop()->screenGeometry();
2458 x += rec.width() - w - framewidth;
2460 y += rec.height() - h - titleheight;
2461 view->setGeometry(x, y, w, h);
2463 // Make sure that the left and top frame borders are visible.
2464 if (view->x() < 0 || view->y() < 0) {
2469 view->setGeometry(x, y, w, h);
2477 bool GuiApplication::unhide(Buffer * buf)
2481 currentView()->setBuffer(buf, false);
2486 Clipboard & GuiApplication::clipboard()
2488 return d->clipboard_;
2492 Selection & GuiApplication::selection()
2494 return d->selection_;
2498 FontLoader & GuiApplication::fontLoader()
2500 return d->font_loader_;
2504 Toolbars const & GuiApplication::toolbars() const
2506 return d->toolbars_;
2510 Toolbars & GuiApplication::toolbars()
2512 return d->toolbars_;
2516 Menus const & GuiApplication::menus() const
2522 Menus & GuiApplication::menus()
2528 QList<int> GuiApplication::viewIds() const
2530 return d->views_.keys();
2534 ColorCache & GuiApplication::colorCache()
2536 return d->color_cache_;
2540 int GuiApplication::exec()
2542 // asynchronously handle batch commands. This event will be in
2543 // the event queue in front of other asynchronous events. Hence,
2544 // we can assume in the latter that the gui is setup already.
2545 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2547 return QApplication::exec();
2551 void GuiApplication::exit(int status)
2553 QApplication::exit(status);
2557 void GuiApplication::setGuiLanguage()
2561 // install translation file for Qt built-in dialogs
2562 QString const language_name = QString("qt_") + theLocale.name();
2563 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2564 // Short-named translator can be loaded from a long name, but not the
2565 // opposite. Therefore, long name should be used without truncation.
2566 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2567 if (!d->qt_trans_.load(language_name,
2568 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2569 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2572 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2576 switch (theLocale.language()) {
2577 case QLocale::Arabic :
2578 case QLocale::Hebrew :
2579 case QLocale::Persian :
2580 case QLocale::Urdu :
2581 setLayoutDirection(Qt::RightToLeft);
2584 setLayoutDirection(Qt::LeftToRight);
2589 void GuiApplication::execBatchCommands()
2594 if (!readUIFile(toqstr(lyxrc.ui_file)))
2595 // Gives some error box here.
2599 #if QT_VERSION > 0x040600
2600 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2602 #if QT_VERSION > 0x050100
2603 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2605 // Create the global default menubar which is shown for the dialogs
2606 // and if no GuiView is visible.
2607 // This must be done after the session was recovered to know the "last files".
2608 d->global_menubar_ = new QMenuBar(0);
2609 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2612 lyx::execBatchCommands();
2616 QAbstractItemModel * GuiApplication::languageModel()
2618 if (d->language_model_)
2619 return d->language_model_;
2621 QStandardItemModel * lang_model = new QStandardItemModel(this);
2622 lang_model->insertColumns(0, 3);
2623 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2624 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2625 Languages::const_iterator it = lyx::languages.begin();
2626 Languages::const_iterator end = lyx::languages.end();
2627 for (; it != end; ++it) {
2628 int current_row = lang_model->rowCount();
2629 lang_model->insertRows(current_row, 1);
2630 QModelIndex pl_item = lang_model->index(current_row, 0);
2631 QModelIndex sp_item = lang_model->index(current_row, 1);
2632 QModelIndex th_item = lang_model->index(current_row, 2);
2633 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2634 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2635 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2636 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2637 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2638 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2639 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2640 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2641 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2642 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2644 d->language_model_ = new QSortFilterProxyModel(this);
2645 d->language_model_->setSourceModel(lang_model);
2646 d->language_model_->setSortLocaleAware(true);
2647 return d->language_model_;
2651 void GuiApplication::restoreGuiSession()
2653 if (!lyxrc.load_session)
2656 Session & session = theSession();
2657 LastOpenedSection::LastOpened const & lastopened =
2658 session.lastOpened().getfiles();
2660 validateCurrentView();
2662 FileName active_file;
2663 // do not add to the lastfile list since these files are restored from
2664 // last session, and should be already there (regular files), or should
2665 // not be added at all (help files).
2666 for (auto const & last : lastopened) {
2667 FileName const & file_name = last.file_name;
2668 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2669 && current_view_->documentBufferView() != 0)) {
2670 string const & fname = file_name.absFileName();
2671 createView(support::checksum(fname));
2673 current_view_->loadDocument(file_name, false);
2676 active_file = file_name;
2679 // Restore last active buffer
2680 Buffer * buffer = theBufferList().getBuffer(active_file);
2681 if (buffer && current_view_)
2682 current_view_->setBuffer(buffer);
2684 // clear this list to save a few bytes of RAM
2685 session.lastOpened().clear();
2689 QString const GuiApplication::romanFontName()
2692 font.setStyleHint(QFont::Serif);
2693 font.setFamily("serif");
2695 return QFontInfo(font).family();
2699 QString const GuiApplication::sansFontName()
2702 font.setStyleHint(QFont::SansSerif);
2703 font.setFamily("sans");
2705 return QFontInfo(font).family();
2709 QString const GuiApplication::typewriterFontName()
2711 return QFontInfo(typewriterSystemFont()).family();
2716 // We cannot use QFont::fixedPitch() because it doesn't
2717 // return the fact but only if it is requested.
2718 static bool isFixedPitch(const QFont & font) {
2719 const QFontInfo fi(font);
2720 return fi.fixedPitch();
2725 QFont const GuiApplication::typewriterSystemFont()
2727 #if QT_VERSION >= 0x050200
2728 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2730 QFont font("monospace");
2732 if (!isFixedPitch(font)) {
2733 // try to enforce a real monospaced font
2734 font.setStyleHint(QFont::Monospace);
2735 if (!isFixedPitch(font)) {
2736 font.setStyleHint(QFont::TypeWriter);
2737 if (!isFixedPitch(font)) font.setFamily("courier");
2741 // On a Mac the result is too small and it's not practical to
2742 // rely on Qtconfig utility to change the system settings of Qt.
2743 font.setPointSize(12);
2749 void GuiApplication::handleRegularEvents()
2751 ForkedCallsController::handleCompletedProcesses();
2755 bool GuiApplication::event(QEvent * e)
2758 case QEvent::FileOpen: {
2759 // Open a file; this happens only on Mac OS X for now.
2761 // We do this asynchronously because on startup the batch
2762 // commands are not executed here yet and the gui is not ready
2764 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2765 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2766 processFuncRequestAsync(fr);
2770 #if (QT_VERSION < 0x050000)
2771 // Qt5 uses a signal for that, see above.
2772 case QEvent::KeyboardLayoutChange:
2773 //LYXERR0("keyboard change");
2774 if (currentView() && currentView()->currentBufferView())
2775 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2780 return QApplication::event(e);
2785 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2788 return QApplication::notify(receiver, event);
2790 catch (ExceptionMessage const & e) {
2792 case ErrorException:
2794 setQuitOnLastWindowClosed(false);
2796 Alert::error(e.title_, e.details_);
2798 // Properly crash in debug mode in order to get a useful backtrace.
2801 // In release mode, try to exit gracefully.
2803 // FIXME: GCC 7 thinks we can fall through here. Can we?
2805 case BufferException: {
2806 if (!current_view_ || !current_view_->documentBufferView())
2808 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2809 docstring details = e.details_ + '\n';
2810 details += buf->emergencyWrite();
2811 theBufferList().release(buf);
2812 details += "\n" + _("The current document was closed.");
2813 Alert::error(e.title_, details);
2816 case WarningException:
2817 Alert::warning(e.title_, e.details_);
2821 catch (exception const & e) {
2822 docstring s = _("LyX has caught an exception, it will now "
2823 "attempt to save all unsaved documents and exit."
2825 s += from_ascii(e.what());
2826 Alert::error(_("Software exception Detected"), s);
2830 docstring s = _("LyX has caught some really weird exception, it will "
2831 "now attempt to save all unsaved documents and exit.");
2832 Alert::error(_("Software exception Detected"), s);
2840 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2842 QColor const & qcol = d->color_cache_.get(col);
2843 if (!qcol.isValid()) {
2849 rgbcol.r = qcol.red();
2850 rgbcol.g = qcol.green();
2851 rgbcol.b = qcol.blue();
2856 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2858 QColor const qcol(lcolor.getX11HexName(col).c_str());
2859 if (!qcol.isValid()) {
2865 rgbcol.r = qcol.red();
2866 rgbcol.g = qcol.green();
2867 rgbcol.b = qcol.blue();
2872 string const GuiApplication::hexName(ColorCode col)
2874 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2878 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2880 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2881 d->socket_notifiers_[fd] = sn;
2882 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2886 void GuiApplication::socketDataReceived(int fd)
2888 d->socket_notifiers_[fd]->func_();
2892 void GuiApplication::unregisterSocketCallback(int fd)
2894 d->socket_notifiers_.take(fd)->setEnabled(false);
2898 void GuiApplication::commitData(QSessionManager & sm)
2900 /** The implementation is required to avoid an application exit
2901 ** when session state save is triggered by session manager.
2902 ** The default implementation sends a close event to all
2903 ** visible top level widgets when session management allows
2905 ** We are changing that to check the state of each buffer in all
2906 ** views and ask the users what to do if buffers are dirty.
2907 ** Furthermore, we save the session state.
2908 ** We do NOT close the views here since the user still can cancel
2909 ** the logout process (see #9277); also, this would hide LyX from
2910 ** an OSes own session handling (application restoration).
2912 #ifdef QT_NO_SESSIONMANAGER
2914 #warning Qt is compiled without session manager
2916 #pragma message("warning: Qt is compiled without session manager")
2920 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2928 void GuiApplication::unregisterView(GuiView * gv)
2930 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2931 d->views_.remove(gv->id());
2932 if (current_view_ == gv)
2938 bool GuiApplication::closeAllViews()
2940 if (d->views_.empty())
2943 // When a view/window was closed before without quitting LyX, there
2944 // are already entries in the lastOpened list.
2945 theSession().lastOpened().clear();
2947 QList<GuiView *> const views = d->views_.values();
2948 for (GuiView * view : views) {
2949 if (!view->closeScheduled())
2958 bool GuiApplication::prepareAllViewsForLogout()
2960 if (d->views_.empty())
2963 QList<GuiView *> const views = d->views_.values();
2964 for (GuiView * view : views) {
2965 if (!view->prepareAllBuffersForLogout())
2973 GuiView & GuiApplication::view(int id) const
2975 LAPPERR(d->views_.contains(id));
2976 return *d->views_.value(id);
2980 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2982 QList<GuiView *> const views = d->views_.values();
2983 for (GuiView * view : views)
2984 view->hideDialog(name, inset);
2988 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2990 Buffer const * buf = 0;
2991 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2992 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2993 if (Buffer const * ptr = (*it)->updateInset(inset))
3000 bool GuiApplication::searchMenu(FuncRequest const & func,
3001 docstring_list & names) const
3003 BufferView * bv = 0;
3005 bv = current_view_->currentBufferView();
3006 return d->menus_.searchMenu(func, names, bv);
3010 bool GuiApplication::hasBufferView() const
3012 return (current_view_ && current_view_->currentBufferView());
3016 // Ensure that a file is read only once (prevents include loops)
3017 static QStringList uifiles;
3018 // store which ui files define Toolbars
3019 static QStringList toolbar_uifiles;
3022 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3033 LexerKeyword uitags[] = {
3034 { "format", ui_format },
3035 { "include", ui_include },
3036 { "menuset", ui_menuset },
3037 { "toolbars", ui_toolbars },
3038 { "toolbarset", ui_toolbarset }
3042 lex.setFile(ui_path);
3044 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3048 if (lyxerr.debugging(Debug::PARSER))
3049 lex.printTable(lyxerr);
3052 // format before introduction of format tag
3053 unsigned int format = 0;
3054 while (lex.isOK()) {
3055 int const status = lex.lex();
3057 // we have to do this check here, outside the switch,
3058 // because otherwise we would start reading include files,
3059 // e.g., if the first tag we hit was an include tag.
3060 if (status == ui_format)
3062 format = lex.getInteger();
3066 // this will trigger unless the first tag we hit is a format
3067 // tag, with the right format.
3068 if (format != LFUN_FORMAT)
3069 return FormatMismatch;
3072 case Lexer::LEX_FEOF:
3077 QString const file = toqstr(lex.getString());
3078 bool const success = readUIFile(file, true);
3080 LYXERR0("Failed to read included file: " << fromqstr(file));
3087 d->menus_.read(lex);
3091 d->toolbars_.readToolbars(lex);
3095 d->toolbars_.readToolbarSettings(lex);
3096 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3100 if (!rtrim(lex.getString()).empty())
3101 lex.printError("LyX::ReadUIFile: "
3102 "Unknown menu tag: `$$Token'");
3104 LYXERR0("Error with status: " << status);
3110 return (error ? ReadError : ReadOK);
3114 bool GuiApplication::readUIFile(QString const & name, bool include)
3116 LYXERR(Debug::INIT, "About to read " << name << "...");
3120 ui_path = libFileSearch("ui", name, "inc");
3121 if (ui_path.empty())
3122 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3124 ui_path = libFileSearch("ui", name, "ui");
3127 if (ui_path.empty()) {
3128 static const QString defaultUIFile = "default";
3129 LYXERR(Debug::INIT, "Could not find " << name);
3131 Alert::warning(_("Could not find UI definition file"),
3132 bformat(_("Error while reading the included file\n%1$s\n"
3133 "Please check your installation."), qstring_to_ucs4(name)));
3136 if (name == defaultUIFile) {
3137 LYXERR(Debug::INIT, "Could not find default UI file!!");
3138 Alert::warning(_("Could not find default UI file"),
3139 _("LyX could not find the default UI file!\n"
3140 "Please check your installation."));
3143 Alert::warning(_("Could not find UI definition file"),
3144 bformat(_("Error while reading the configuration file\n%1$s\n"
3145 "Falling back to default.\n"
3146 "Please look under Tools>Preferences>User Interface and\n"
3147 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3148 return readUIFile(defaultUIFile, false);
3151 QString const uifile = toqstr(ui_path.absFileName());
3152 if (uifiles.contains(uifile)) {
3154 // We are reading again the top uifile so reset the safeguard:
3157 d->toolbars_.reset();
3159 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3160 << "Is this an include loop?");
3164 uifiles.push_back(uifile);
3166 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3168 ReturnValues retval = readUIFile(ui_path);
3170 if (retval == FormatMismatch) {
3171 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3172 TempFile tmp("convertXXXXXX.ui");
3173 FileName const tempfile = tmp.name();
3174 bool const success = prefs2prefs(ui_path, tempfile, true);
3176 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3177 " to format " << LFUN_FORMAT << ".");
3179 retval = readUIFile(tempfile);
3183 if (retval != ReadOK) {
3184 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3192 settings.beginGroup("ui_files");
3193 bool touched = false;
3194 for (int i = 0; i != uifiles.size(); ++i) {
3195 QFileInfo fi(uifiles[i]);
3196 QDateTime const date_value = fi.lastModified();
3197 QString const name_key = QString::number(i);
3198 // if an ui file which defines Toolbars has changed,
3199 // we have to reset the settings
3200 if (toolbar_uifiles.contains(uifiles[i])
3201 && (!settings.contains(name_key)
3202 || settings.value(name_key).toString() != uifiles[i]
3203 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3205 settings.setValue(name_key, uifiles[i]);
3206 settings.setValue(name_key + "/date", date_value);
3209 settings.endGroup();
3211 settings.remove("views");
3217 void GuiApplication::onLastWindowClosed()
3219 if (d->global_menubar_)
3220 d->global_menubar_->grabKeyboard();
3224 void GuiApplication::startLongOperation() {
3225 d->key_checker_.start();
3229 bool GuiApplication::longOperationCancelled() {
3230 return d->key_checker_.pressed();
3234 void GuiApplication::stopLongOperation() {
3235 d->key_checker_.stop();
3239 bool GuiApplication::longOperationStarted() {
3240 return d->key_checker_.started();
3244 ////////////////////////////////////////////////////////////////////////
3246 // X11 specific stuff goes here...
3249 bool GuiApplication::x11EventFilter(XEvent * xev)
3254 switch (xev->type) {
3255 case SelectionRequest: {
3256 if (xev->xselectionrequest.selection != XA_PRIMARY)
3258 LYXERR(Debug::SELECTION, "X requested selection.");
3259 BufferView * bv = current_view_->currentBufferView();
3261 docstring const sel = bv->requestSelection();
3263 d->selection_.put(sel);
3264 // Refresh the selection request timestamp.
3265 // We have to do this by ourselves as Qt seems
3266 // not doing that, maybe because of our
3267 // "persistent selection" implementation
3268 // (see comments in GuiSelection.cpp).
3269 XSelectionEvent nev;
3270 nev.type = SelectionNotify;
3271 nev.display = xev->xselectionrequest.display;
3272 nev.requestor = xev->xselectionrequest.requestor;
3273 nev.selection = xev->xselectionrequest.selection;
3274 nev.target = xev->xselectionrequest.target;
3275 nev.property = 0L; // None
3276 nev.time = CurrentTime;
3277 XSendEvent(QX11Info::display(),
3278 nev.requestor, False, 0,
3279 reinterpret_cast<XEvent *>(&nev));
3285 case SelectionClear: {
3286 if (xev->xselectionclear.selection != XA_PRIMARY)
3288 LYXERR(Debug::SELECTION, "Lost selection.");
3289 BufferView * bv = current_view_->currentBufferView();
3291 bv->clearSelection();
3297 #elif defined(QPA_XCB)
3298 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3299 void * message, long *)
3301 if (!current_view_ || eventType != "xcb_generic_event_t")
3304 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3306 switch (ev->response_type) {
3307 case XCB_SELECTION_REQUEST: {
3308 xcb_selection_request_event_t * srev =
3309 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3310 if (srev->selection != XCB_ATOM_PRIMARY)
3312 LYXERR(Debug::SELECTION, "X requested selection.");
3313 BufferView * bv = current_view_->currentBufferView();
3315 docstring const sel = bv->requestSelection();
3317 d->selection_.put(sel);
3318 #ifdef HAVE_QT5_X11_EXTRAS
3319 // Refresh the selection request timestamp.
3320 // We have to do this by ourselves as Qt seems
3321 // not doing that, maybe because of our
3322 // "persistent selection" implementation
3323 // (see comments in GuiSelection.cpp).
3324 // It is expected that every X11 event is
3325 // 32 bytes long, even if not all 32 bytes are
3327 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3328 struct alignas(32) padded_event
3329 : xcb_selection_notify_event_t {};
3330 padded_event nev = {};
3331 nev.response_type = XCB_SELECTION_NOTIFY;
3332 nev.requestor = srev->requestor;
3333 nev.selection = srev->selection;
3334 nev.target = srev->target;
3335 nev.property = XCB_NONE;
3336 nev.time = XCB_CURRENT_TIME;
3337 xcb_connection_t * con = QX11Info::connection();
3338 xcb_send_event(con, 0, srev->requestor,
3339 XCB_EVENT_MASK_NO_EVENT,
3340 reinterpret_cast<char const *>(&nev));
3348 case XCB_SELECTION_CLEAR: {
3349 xcb_selection_clear_event_t * scev =
3350 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3351 if (scev->selection != XCB_ATOM_PRIMARY)
3353 LYXERR(Debug::SELECTION, "Lost selection.");
3354 BufferView * bv = current_view_->currentBufferView();
3356 bv->clearSelection();
3364 } // namespace frontend
3367 void hideDialogs(std::string const & name, Inset * inset)
3370 frontend::guiApp->hideDialogs(name, inset);
3374 ////////////////////////////////////////////////////////////////////
3378 ////////////////////////////////////////////////////////////////////
3380 frontend::FontLoader & theFontLoader()
3382 LAPPERR(frontend::guiApp);
3383 return frontend::guiApp->fontLoader();
3387 frontend::FontMetrics const & theFontMetrics(Font const & f)
3389 return theFontMetrics(f.fontInfo());
3393 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3395 LAPPERR(frontend::guiApp);
3396 return frontend::guiApp->fontLoader().metrics(f);
3400 ////////////////////////////////////////////////////////////////////
3404 ////////////////////////////////////////////////////////////////////
3406 frontend::Clipboard & theClipboard()
3408 LAPPERR(frontend::guiApp);
3409 return frontend::guiApp->clipboard();
3413 frontend::Selection & theSelection()
3415 LAPPERR(frontend::guiApp);
3416 return frontend::guiApp->selection();
3422 #include "moc_GuiApplication.cpp"