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"
88 #include <QDesktopWidget>
91 #include <QFileOpenEvent>
93 #include <QFontDatabase>
96 #include <QImageReader>
99 #include <QLibraryInfo>
105 #include <QPixmapCache>
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;
160 static void initializeResources()
162 static bool initialized = false;
164 Q_INIT_RESOURCE(Resources);
172 frontend::Application * createApplication(int & argc, char * argv[])
174 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
175 // prune -geometry argument(s) by shifting
176 // the following ones 2 places down.
177 for (int i = 0 ; i < argc ; ++i) {
178 if (strcmp(argv[i], "-geometry") == 0) {
179 int const remove = (i+1) < argc ? 2 : 1;
181 for (int j = i; j < argc; ++j)
182 argv[j] = argv[j + remove];
188 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
189 // On Windows, allow bringing the LyX window to top
190 AllowSetForegroundWindow(ASFW_ANY);
193 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
194 // I'd rather do that in the constructor, but I do not think that
195 // the palette is accessible there.
196 guiApp->colorCache().setPalette(guiApp->palette());
205 if (lyxrc.gui_language == "auto") {
206 theLocale = QLocale::system();
207 code = fromqstr(theLocale.name());
209 Language const * l = languages.getLanguage(lyxrc.gui_language);
210 code = l ? l->code() : "C";
211 theLocale = QLocale(toqstr(code));
213 // Qt tries to outsmart us and transforms en_US to C.
214 Messages::guiLanguage((code == "C") ? "en_US" : code);
215 QLocale::setDefault(theLocale);
216 setlocale(LC_NUMERIC, "C");
223 /// Return the list of loadable formats.
224 vector<string> loadableImageFormats()
228 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
230 LYXERR(Debug::GRAPHICS,
231 "\nThe image loader can load the following directly:\n");
233 if (qt_formats.empty())
234 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
236 bool jpeg_found = false;
237 bool jpg_found = false;
238 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
240 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
242 string ext = ascii_lowercase((const char *) *it);
250 else if (ext == "jpg") {
255 else if (lyxrc.use_converter_cache &&
256 (ext == "svg" || ext == "svgz") &&
257 theConverters().isReachable("svg", "png"))
258 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
259 // the SVG as in the output. However we require that the converter
260 // cache is enabled since this is expensive. We also require that
261 // an explicit svg->png converter is defined, since the default
262 // converter could produce bad quality as well. This assumes that
263 // png can always be loaded.
272 ////////////////////////////////////////////////////////////////////////
274 // Icon loading support code
276 ////////////////////////////////////////////////////////////////////////
286 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
288 return lhs.key < rhs.key;
294 CompareKey(QString const & name) : name_(name) {}
295 bool operator()(ImgMap const & other) const { return other.key == name_; }
301 // this must be sorted alphabetically
302 // Upper case comes before lower case
303 // Please don't change the formatting, this list is parsed by
304 // development/tools/generate_symbols_images.py.
305 ImgMap sorted_img_map[] = {
306 { "Arrownot", "arrownot2"},
307 { "Arrowvert", "arrowvert2"},
308 { "Bowtie", "bowtie2" },
310 { "Bumpeq", "bumpeq2" },
311 { "CIRCLE", "circle3" },
313 { "CheckedBox", "checkedbox2" },
314 { "Circle", "circle2" },
315 { "Colonapprox", "colonapprox2" },
316 { "Coloneq", "coloneq2" },
317 { "Coloneqq", "coloneqq2" },
318 { "Colonsim", "colonsim2" },
320 { "DOWNarrow", "downarrow3" },
321 { "Delta", "delta2" },
322 { "Diamond", "diamond2" },
323 { "Doteq", "doteq2" },
324 { "Downarrow", "downarrow2" },
325 { "Eqcolon", "eqcolon2" },
326 { "Eqqcolon", "eqqcolon2" },
327 { "Gamma", "gamma2" },
329 { "LEFTCIRCLE", "leftcircle3" },
330 { "LEFTarrow", "leftarrow3" },
331 { "LEFTcircle", "leftcircle4" },
333 { "Lambda", "lambda2" },
335 { "Leftarrow", "leftarrow2" },
336 { "Leftcircle", "leftcircle2" },
337 { "Leftrightarrow", "leftrightarrow2" },
338 { "Longarrownot", "longarrownot2"},
339 { "Longleftarrow", "longleftarrow2" },
340 { "Longleftrightarrow", "longleftrightarrow2" },
341 { "Longmapsfrom", "longmapsfrom2"},
342 { "Longmapsto", "longmapsto2"},
343 { "Longrightarrow", "longrightarrow2" },
344 { "Mapsfrom", "mapsfrom2"},
345 { "Mapsfromchar", "mapsfromchar2"},
346 { "Mapsto", "mapsto2"},
347 { "Mapstochar", "mapstochar2"},
348 { "Omega", "omega2" },
353 { "RIGHTCIRCLE", "rightcircle3" },
354 { "RIGHTarrow", "rightarrow3" },
355 { "RIGHTcircle", "rightcircle4" },
357 { "Rightarrow", "rightarrow2" },
358 { "Rightcircle", "rightcircle2" },
359 { "Sigma", "sigma2" },
360 { "Square", "square2" },
361 { "Subset", "subset2" },
362 { "Supset", "supset2" },
363 { "Theta", "theta2" },
364 { "Thorn", "thorn2" },
365 { "UParrow", "uparrow3" },
366 { "Uparrow", "uparrow2" },
367 { "Updownarrow", "updownarrow2" },
368 { "Upsilon", "upsilon2" },
369 { "Vdash", "vdash3" },
374 { "lVert", "vert2" },
376 { "nLeftarrow", "nleftarrow2" },
377 { "nLeftrightarrow", "nleftrightarrow2" },
378 { "nRightarrow", "nrightarrow2" },
379 { "nVDash", "nvdash3" },
380 { "nVdash", "nvdash4" },
381 { "nvDash", "nvdash2" },
382 { "rVert", "vert2" },
384 { "textrm \\AA", "textrm_AA"},
385 { "textrm \\O", "textrm_O"},
386 { "vDash", "vdash2" },
387 { "varDelta", "vardelta2" },
388 { "varGamma", "vargamma2" },
389 { "varLambda", "varlambda2" },
390 { "varOmega", "varomega2" },
391 { "varPhi", "varphi2" },
392 { "varPi", "varpi2" },
393 { "varPsi", "varpsi2" },
394 { "varSigma", "varsigma2" },
395 { "varTheta", "vartheta2" },
396 { "varUpsilon", "varupsilon2" },
397 { "varXi", "varxi2" }
401 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
403 // This list specifies which system's theme icon is related to which lyx
404 // command. It was based on:
405 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
406 // this must be sorted alphabetically
407 // Upper case comes before lower case
408 ImgMap sorted_theme_icon_map[] = {
409 { "bookmark-goto 0", "go-jump" },
410 { "buffer-new", "document-new" },
411 { "buffer-write", "document-save" },
412 { "buffer-write-as", "document-save-as" },
413 { "buffer-zoom-in", "zoom-in" },
414 { "buffer-zoom-out", "zoom-out" },
415 { "copy", "edit-copy" },
416 { "cut", "edit-cut" },
417 { "depth-decrement", "format-indent-less" },
418 { "depth-increment", "format-indent-more" },
419 { "dialog-show spellchecker", "tools-check-spelling" },
420 { "dialog-show-new-inset graphics", "insert-image" },
421 { "dialog-toggle findreplaceadv", "edit-find-replace" },
422 { "file-open", "document-open" },
423 { "font-bold", "format-text-bold" },
424 { "font-ital", "format-text-italic" },
425 { "font-strikeout", "format-text-strikethrough" },
426 { "font-underline", "format-text-underline" },
427 { "lyx-quit", "application-exit" },
428 { "paste", "edit-paste" },
429 { "redo", "edit-redo" },
430 { "undo", "edit-undo" },
431 { "window-close", "window-close" },
432 { "window-new", "window-new" }
435 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
438 QString findImg(QString const & name)
440 ImgMap const * const begin = sorted_img_map;
441 ImgMap const * const end = begin + nr_sorted_img_map;
442 LATTEST(sorted(begin, end));
444 ImgMap const * const it = find_if(begin, end, CompareKey(name));
448 img_name = it->value;
451 img_name.replace('_', "underscore");
452 img_name.replace(' ', '_');
454 // This way we can have "math-delim { }" on the toolbar.
455 img_name.replace('(', "lparen");
456 img_name.replace(')', "rparen");
457 img_name.replace('[', "lbracket");
458 img_name.replace(']', "rbracket");
459 img_name.replace('{', "lbrace");
460 img_name.replace('}', "rbrace");
461 img_name.replace('|', "bars");
462 img_name.replace(',', "thinspace");
463 img_name.replace(':', "mediumspace");
464 img_name.replace(';', "thickspace");
465 img_name.replace('!', "negthinspace");
468 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
469 << "Looking for math icon called \"" << img_name << '"');
476 QString themeIconName(QString const & action)
478 ImgMap const * const begin = sorted_theme_icon_map;
479 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
480 LASSERT(sorted(begin, end), /**/);
482 ImgMap const * const it = find_if(begin, end, CompareKey(action));
490 QString iconName(FuncRequest const & f, bool unknown)
492 initializeResources();
496 switch (f.action()) {
497 case LFUN_MATH_INSERT:
498 if (!f.argument().empty()) {
500 name1 = findImg(toqstr(f.argument()).mid(1));
503 case LFUN_MATH_DELIM:
504 case LFUN_MATH_BIGDELIM:
506 name1 = findImg(toqstr(f.argument()));
510 name1 = toqstr(f.argument());
512 case LFUN_COMMAND_ALTERNATIVES: {
513 // use the first of the alternative commands
515 docstring dummy = split(f.argument(), firstcom, ';');
516 name1 = toqstr(firstcom);
517 name1.replace(' ', '_');
521 name2 = toqstr(lyxaction.getActionName(f.action()));
524 if (!f.argument().empty()) {
525 name1 = name2 + ' ' + toqstr(f.argument());
526 name1.replace(' ', '_');
527 name1.replace('\\', "backslash");
531 QStringList imagedirs;
532 imagedirs << "images/" << "images/ipa/";
533 search_mode mode = theGuiApp()->imageSearchMode();
534 for (int i = 0; i < imagedirs.size(); ++i) {
535 QString imagedir = imagedirs.at(i) + path;
536 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
538 return toqstr(fname.absFileName());
540 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
542 return toqstr(fname.absFileName());
545 path = ":/images/" + path;
548 LYXERR0("Directory " << path << " not found in resource!");
551 if (res.exists(name1 + ".svgz"))
552 return path + name1 + ".svgz";
553 else if (res.exists(name1 + ".png"))
554 return path + name1 + ".png";
556 if (res.exists(name2 + ".svgz"))
557 return path + name2 + ".svgz";
558 else if (res.exists(name2 + ".png"))
559 return path + name2 + ".png";
561 LYXERR(Debug::GUI, "Cannot find icon with filename "
562 << "\"" << name1 << ".{svgz,png}\""
564 << "\"" << name2 << ".{svgz,png}\""
566 << lyxaction.getActionName(f.action())
567 << '(' << to_utf8(f.argument()) << ")\"");
570 QString imagedir = "images/";
571 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
573 return toqstr(fname.absFileName());
574 return QString(":/images/unknown.svgz");
581 bool getPixmap(QPixmap & pixmap, QString const & path)
583 return pixmap.load(path);
587 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
589 QString imagedir = path;
590 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
591 QString fpath = toqstr(fname.absFileName());
592 QPixmap pixmap = QPixmap();
594 if (getPixmap(pixmap, fpath)) {
598 QStringList exts = ext.split(",");
599 fpath = ":/" + path + name + ".";
600 for (int i = 0; i < exts.size(); ++i) {
601 if (getPixmap(pixmap, fpath + exts.at(i))) {
606 bool const list = ext.contains(",");
607 LYXERR0("Cannot load pixmap \""
608 << path << name << "." << (list ? "{" : "") << ext
609 << (list ? "}" : "") << "\", please verify resource system!");
615 QIcon getIcon(FuncRequest const & f, bool unknown)
617 #if (QT_VERSION >= 0x040600)
618 if (lyxrc.use_system_theme_icons) {
619 // use the icons from system theme that are available
620 QString action = toqstr(lyxaction.getActionName(f.action()));
621 if (!f.argument().empty())
622 action += " " + toqstr(f.argument());
623 QString const theme_icon = themeIconName(action);
624 if (QIcon::hasThemeIcon(theme_icon)) {
625 QIcon const thmicn = QIcon::fromTheme(theme_icon);
626 if (!thmicn.isNull())
632 QString icon = iconName(f, unknown);
636 //LYXERR(Debug::GUI, "Found icon: " << icon);
637 QPixmap pixmap = QPixmap();
638 if (!getPixmap(pixmap,icon)) {
639 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
643 return QIcon(pixmap);
647 ////////////////////////////////////////////////////////////////////////
649 // LyX server support code.
651 ////////////////////////////////////////////////////////////////////////
653 class SocketNotifier : public QSocketNotifier
656 /// connect a connection notification from the LyXServerSocket
657 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
658 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
662 /// The callback function
663 Application::SocketCallback func_;
667 class GuiTranslator : public QTranslator
670 GuiTranslator(QObject * parent = nullptr)
671 : QTranslator(parent)
674 virtual QString translate(const char * /* context */,
675 const char *sourceText,
676 #if QT_VERSION >= 0x050000
677 const char * /* disambiguation */ = 0, int /* n */ = -1) const
679 const char * /*comment*/ = 0) const
682 // Here we declare the strings that need to be translated from Qt own GUI
683 // This is needed to include these strings to po files
689 // Already in po: "Cancel", "&Cancel"
690 _("Apply"); // Already in po: "&Apply"
691 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
693 docstring s = getGuiMessages().getIfFound(sourceText);
694 // This test should eventually be removed when translations are updated
696 LYXERR(Debug::LOCALE, "Missing translation for `"
697 << string(sourceText) << "'");
703 ////////////////////////////////////////////////////////////////////////
705 // Mac specific stuff goes here...
707 ////////////////////////////////////////////////////////////////////////
710 // QMacPasteboardMimeGraphics can only be compiled on Mac.
712 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
715 QMacPasteboardMimeGraphics()
716 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
719 QString convertorName() { return "Graphics"; }
721 QString flavorFor(QString const & mime)
723 LYXERR(Debug::ACTION, "flavorFor " << mime);
724 if (mime == pdfMimeType())
725 return QLatin1String("com.adobe.pdf");
729 QString mimeFor(QString flav)
731 LYXERR(Debug::ACTION, "mimeFor " << flav);
732 if (flav == QLatin1String("com.adobe.pdf"))
733 return pdfMimeType();
737 bool canConvert(QString const & mime, QString flav)
739 return mimeFor(flav) == mime;
742 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
746 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
750 QList<QByteArray> convertFromMime(QString const & /*mime*/,
751 QVariant data, QString /*flav*/)
753 QList<QByteArray> ret;
754 ret.append(data.toByteArray());
760 ///////////////////////////////////////////////////////////////
762 // You can find more platform specific stuff at the end of this file...
764 ///////////////////////////////////////////////////////////////
766 ////////////////////////////////////////////////////////////////////////
767 // Windows specific stuff goes here...
769 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
770 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
771 // QWindowsMimeMetafile can only be compiled on Windows.
773 static FORMATETC cfFromMime(QString const & mimetype)
776 if (mimetype == emfMimeType()) {
777 formatetc.cfFormat = CF_ENHMETAFILE;
778 formatetc.tymed = TYMED_ENHMF;
779 } else if (mimetype == wmfMimeType()) {
780 formatetc.cfFormat = CF_METAFILEPICT;
781 formatetc.tymed = TYMED_MFPICT;
784 formatetc.dwAspect = DVASPECT_CONTENT;
785 formatetc.lindex = -1;
790 class QWindowsMimeMetafile : public QWINDOWSMIME {
792 QWindowsMimeMetafile() {}
794 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
795 QMimeData const * /*mimedata*/) const
800 bool canConvertToMime(QString const & mimetype,
801 IDataObject * pDataObj) const
803 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
805 FORMATETC formatetc = cfFromMime(mimetype);
806 return pDataObj->QueryGetData(&formatetc) == S_OK;
809 bool convertFromMime(FORMATETC const & /*formatetc*/,
810 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
815 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
816 QVariant::Type /*preferredType*/) const
819 if (!canConvertToMime(mimetype, pDataObj))
822 FORMATETC formatetc = cfFromMime(mimetype);
824 if (pDataObj->GetData(&formatetc, &s) != S_OK)
828 if (s.tymed == TYMED_ENHMF) {
829 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
830 data.resize(dataSize);
831 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
832 (LPBYTE)data.data());
833 } else if (s.tymed == TYMED_MFPICT) {
834 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
835 data.resize(dataSize);
836 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
837 (LPBYTE)data.data());
840 ReleaseStgMedium(&s);
846 QVector<FORMATETC> formatsForMime(QString const & mimetype,
847 QMimeData const * /*mimedata*/) const
849 QVector<FORMATETC> formats;
850 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
851 formats += cfFromMime(mimetype);
855 QString mimeForFormat(FORMATETC const & formatetc) const
857 switch (formatetc.cfFormat) {
859 return emfMimeType();
860 case CF_METAFILEPICT:
861 return wmfMimeType();
871 /// Allows to check whether ESC was pressed during a long operation
872 class KeyChecker : public QObject {
877 KeyChecker() : pressed_(false), started_(false) {}
880 QCoreApplication::instance()->installEventFilter(this);
885 QCoreApplication::instance()->removeEventFilter(this);
889 QCoreApplication::processEvents();
892 bool started() const {
895 bool eventFilter(QObject *obj, QEvent *event) {
896 LYXERR(Debug::ACTION, "Event Type: " << event->type());
897 switch (event->type()) {
901 case QEvent::UpdateRequest:
902 case QEvent::CursorChange:
903 case QEvent::ActionChanged:
904 case QEvent::EnabledChange:
905 case QEvent::SockAct:
908 case QEvent::ToolTipChange:
909 case QEvent::LayoutRequest:
910 case QEvent::MetaCall:
911 return QObject::eventFilter(obj, event);
913 // FIXME Blocking all these events is a bad idea.
914 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
915 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
923 ////////////////////////////////////////////////////////////////////////
924 // GuiApplication::Private definition and implementation.
925 ////////////////////////////////////////////////////////////////////////
927 struct GuiApplication::Private
929 Private(): language_model_(0), meta_fake_bit(NoModifier),
932 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
933 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
934 /// WMF Mime handler for Windows clipboard.
935 wmf_mime_ = new QWindowsMimeMetafile;
938 initKeySequences(&theTopLevelKeymap());
941 void initKeySequences(KeyMap * kb)
943 keyseq = KeySequence(kb, kb);
944 cancel_meta_seq = KeySequence(kb, kb);
948 QSortFilterProxyModel * language_model_;
950 GuiClipboard clipboard_;
952 GuiSelection selection_;
954 FontLoader font_loader_;
956 ColorCache color_cache_;
957 /// the built-in Qt translation mechanism
958 QTranslator qt_trans_;
959 /// LyX gettext-based translation for Qt elements
960 GuiTranslator gui_trans_;
962 QHash<int, SocketNotifier *> socket_notifiers_;
966 /// The global instance
969 /// this timer is used for any regular events one wants to
970 /// perform. at present it is used to check if forked processes
972 QTimer general_timer_;
974 /// delayed FuncRequests
975 std::queue<FuncRequest> func_request_queue_;
980 KeySequence cancel_meta_seq;
982 KeyModifier meta_fake_bit;
984 /// The result of last dispatch action
985 DispatchResult dispatch_result_;
987 /// Multiple views container.
989 * Warning: This must not be a smart pointer as the destruction of the
990 * object is handled by Qt when the view is closed
991 * \sa Qt::WA_DeleteOnClose attribute.
993 QHash<int, GuiView *> views_;
995 /// Only used on mac.
996 QMenuBar * global_menubar_;
999 /// Linkback mime handler for MacOSX.
1000 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1003 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1004 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1005 /// WMF Mime handler for Windows clipboard.
1006 QWindowsMimeMetafile * wmf_mime_;
1010 /// Allows to check whether ESC was pressed during a long operation
1011 KeyChecker key_checker_;
1015 GuiApplication * guiApp;
1017 GuiApplication::~GuiApplication()
1020 closeAllLinkBackLinks();
1026 GuiApplication::GuiApplication(int & argc, char ** argv)
1027 : QApplication(argc, argv), current_view_(0),
1028 d(new GuiApplication::Private)
1030 QString app_name = "LyX";
1031 QCoreApplication::setOrganizationName(app_name);
1032 QCoreApplication::setOrganizationDomain("lyx.org");
1033 QCoreApplication::setApplicationName(lyx_package);
1034 #if QT_VERSION >= 0x050000
1035 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1038 qsrand(QDateTime::currentDateTime().toTime_t());
1040 // Install LyX translator for missing Qt translations
1041 installTranslator(&d->gui_trans_);
1042 // Install Qt native translator for GUI elements.
1043 installTranslator(&d->qt_trans_);
1046 // Enable reception of XCB events.
1047 installNativeEventFilter(this);
1050 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1051 // lyxrc setting for this in order to let the application stay resident.
1052 // But then we need some kind of dock icon, at least on Windows.
1054 if (lyxrc.quit_on_last_window_closed)
1055 setQuitOnLastWindowClosed(false);
1058 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1059 // seems to be the default case for applications like LyX.
1060 setQuitOnLastWindowClosed(false);
1065 #if defined(Q_WS_X11) || defined(QPA_XCB)
1066 // doubleClickInterval() is 400 ms on X11 which is just too long.
1067 // On Windows and Mac OS X, the operating system's value is used.
1068 // On Microsoft Windows, calling this function sets the double
1069 // click interval for all applications. So we don't!
1070 QApplication::setDoubleClickInterval(300);
1073 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1075 // needs to be done before reading lyxrc
1077 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1081 // Set the cache to 5120 kilobytes which corresponds to screen size of
1082 // 1280 by 1024 pixels with a color depth of 32 bits.
1083 QPixmapCache::setCacheLimit(5120);
1085 // Initialize RC Fonts
1086 if (lyxrc.roman_font_name.empty())
1087 lyxrc.roman_font_name = fromqstr(romanFontName());
1089 if (lyxrc.sans_font_name.empty())
1090 lyxrc.sans_font_name = fromqstr(sansFontName());
1092 if (lyxrc.typewriter_font_name.empty())
1093 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1095 d->general_timer_.setInterval(500);
1096 connect(&d->general_timer_, SIGNAL(timeout()),
1097 this, SLOT(handleRegularEvents()));
1098 d->general_timer_.start();
1100 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1101 // This is clearly not enough in a time where we use threads for
1102 // document preview and/or export. 20 should be OK.
1103 QThreadPool::globalInstance()->setMaxThreadCount(20);
1105 // make sure tooltips are formatted
1106 installEventFilter(new ToolTipFormatter(this));
1110 GuiApplication * theGuiApp()
1112 return dynamic_cast<GuiApplication *>(theApp());
1116 double GuiApplication::pixelRatio() const
1118 #if QT_VERSION >= 0x050000
1119 return qt_scale_factor * devicePixelRatio();
1126 void GuiApplication::clearSession()
1133 docstring Application::iconName(FuncRequest const & f, bool unknown)
1135 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1139 docstring Application::mathIcon(docstring const & c)
1141 return qstring_to_ucs4(findImg(toqstr(c)));
1145 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1149 BufferView * bv = 0;
1150 BufferView * doc_bv = 0;
1152 if (cmd.action() == LFUN_NOACTION) {
1153 status.message(from_utf8(N_("Nothing to do")));
1154 status.setEnabled(false);
1157 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1158 status.setUnknown(true);
1159 status.message(from_utf8(N_("Unknown action")));
1160 status.setEnabled(false);
1163 // Does the GuiApplication know something?
1164 else if (getStatus(cmd, status)) { }
1166 // If we do not have a GuiView, then other functions are disabled
1167 else if (!current_view_)
1168 status.setEnabled(false);
1170 // Does the GuiView know something?
1171 else if (current_view_->getStatus(cmd, status)) { }
1173 // In LyX/Mac, when a dialog is open, the menus of the
1174 // application can still be accessed without giving focus to
1175 // the main window. In this case, we want to disable the menu
1176 // entries that are buffer or view-related.
1177 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1179 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1180 status.setEnabled(false);
1183 // If we do not have a BufferView, then other functions are disabled
1184 else if (!(bv = current_view_->currentBufferView()))
1185 status.setEnabled(false);
1187 // Does the current BufferView know something?
1188 else if (bv->getStatus(cmd, status)) { }
1190 // Does the current Buffer know something?
1191 else if (bv->buffer().getStatus(cmd, status)) { }
1193 // If we do not have a document BufferView, different from the
1194 // current BufferView, then other functions are disabled
1195 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1196 status.setEnabled(false);
1198 // Does the document Buffer know something?
1199 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1202 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1203 status.message(from_utf8(N_("Command not handled")));
1204 status.setEnabled(false);
1207 // the default error message if we disable the command
1208 if (!status.enabled() && status.message().empty())
1209 status.message(from_utf8(N_("Command disabled")));
1215 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1217 // I would really like to avoid having this switch and rather try to
1218 // encode this in the function itself.
1219 // -- And I'd rather let an inset decide which LFUNs it is willing
1220 // to handle (Andre')
1222 switch (cmd.action()) {
1224 // This could be used for the no-GUI version. The GUI version is handled in
1225 // GuiView::getStatus(). See above.
1227 case LFUN_BUFFER_WRITE:
1228 case LFUN_BUFFER_WRITE_AS: {
1229 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1230 enable = b && (b->isUnnamed() || !b->isClean());
1235 case LFUN_BOOKMARK_GOTO: {
1236 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1237 enable = theSession().bookmarks().isValid(num);
1241 case LFUN_BOOKMARK_CLEAR:
1242 enable = theSession().bookmarks().hasValid();
1245 // this one is difficult to get right. As a half-baked
1246 // solution, we consider only the first action of the sequence
1247 case LFUN_COMMAND_SEQUENCE: {
1248 // argument contains ';'-terminated commands
1249 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1250 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1251 func.setOrigin(cmd.origin());
1252 flag = getStatus(func);
1256 // we want to check if at least one of these is enabled
1257 case LFUN_COMMAND_ALTERNATIVES: {
1258 // argument contains ';'-terminated commands
1259 string arg = to_utf8(cmd.argument());
1260 while (!arg.empty()) {
1262 arg = split(arg, first, ';');
1263 FuncRequest func(lyxaction.lookupFunc(first));
1264 func.setOrigin(cmd.origin());
1265 flag = getStatus(func);
1266 // if this one is enabled, the whole thing is
1275 string name = to_utf8(cmd.argument());
1276 if (theTopLevelCmdDef().lock(name, func)) {
1277 func.setOrigin(cmd.origin());
1278 flag = getStatus(func);
1279 theTopLevelCmdDef().release(name);
1281 // catch recursion or unknown command
1282 // definition. all operations until the
1283 // recursion or unknown command definition
1284 // occurs are performed, so set the state to
1291 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1293 case LFUN_PREFERENCES_SAVE:
1294 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1295 case LFUN_DEBUG_LEVEL_SET:
1296 // these are handled in our dispatch()
1299 case LFUN_WINDOW_CLOSE:
1300 enable = d->views_.size() > 0;
1303 case LFUN_BUFFER_NEW:
1304 case LFUN_BUFFER_NEW_TEMPLATE:
1305 case LFUN_FILE_OPEN:
1306 case LFUN_HELP_OPEN:
1307 case LFUN_SCREEN_FONT_UPDATE:
1308 case LFUN_SET_COLOR:
1309 case LFUN_WINDOW_NEW:
1311 case LFUN_LYXRC_APPLY:
1312 case LFUN_COMMAND_PREFIX:
1314 case LFUN_META_PREFIX:
1315 case LFUN_RECONFIGURE:
1316 case LFUN_SERVER_GET_FILENAME:
1317 case LFUN_SERVER_NOTIFY:
1321 case LFUN_BUFFER_FORALL: {
1322 if (theBufferList().empty()) {
1323 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1324 flag.setEnabled(false);
1328 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1329 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1330 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1331 flag.setEnabled(false);
1336 case LFUN_DIALOG_SHOW: {
1337 string const name = cmd.getArg(0);
1338 return name == "aboutlyx"
1340 || name == "texinfo"
1341 || name == "progress"
1342 || name == "compare";
1350 flag.setEnabled(false);
1354 /// make a post-dispatch status message
1355 static docstring makeDispatchMessage(docstring const & msg,
1356 FuncRequest const & cmd)
1358 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1359 || cmd.origin() == FuncRequest::TOOLBAR
1360 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1362 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1363 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1367 docstring dispatch_msg = msg;
1368 if (!dispatch_msg.empty())
1369 dispatch_msg += ' ';
1371 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1373 bool argsadded = false;
1375 if (!cmd.argument().empty()) {
1376 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1377 comname += ' ' + cmd.argument();
1381 docstring const shortcuts = theTopLevelKeymap().
1382 printBindings(cmd, KeySequence::ForGui);
1384 if (!shortcuts.empty())
1385 comname += ": " + shortcuts;
1386 else if (!argsadded && !cmd.argument().empty())
1387 comname += ' ' + cmd.argument();
1389 if (!comname.empty()) {
1390 comname = rtrim(comname);
1391 dispatch_msg += '(' + rtrim(comname) + ')';
1393 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1394 return dispatch_msg;
1398 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1402 Buffer * buffer = 0;
1403 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1404 //setCurrentView(cmd.view_origin); //does not work
1406 dr.setMessage(_("Wrong focus!"));
1407 d->dispatch_result_ = dr;
1408 return d->dispatch_result_;
1410 if (current_view_ && current_view_->currentBufferView()) {
1411 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1412 buffer = ¤t_view_->currentBufferView()->buffer();
1415 dr.screenUpdate(Update::FitCursor);
1417 // This handles undo groups automagically
1418 UndoGroupHelper ugh(buffer);
1422 // redraw the screen at the end (first of the two drawing steps).
1423 // This is done unless explicitly requested otherwise
1424 updateCurrentView(cmd, dr);
1425 d->dispatch_result_ = dr;
1426 return d->dispatch_result_;
1430 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1435 BufferView * bv = current_view_->currentBufferView();
1437 if (dr.needBufferUpdate()) {
1438 bv->cursor().clearBufferUpdate();
1439 bv->buffer().updateBuffer();
1440 } else if (dr.needChangesUpdate()) {
1441 // updateBuffer() already updates the change-tracking presence flag
1442 bv->buffer().updateChangesPresent();
1444 // BufferView::update() updates the ViewMetricsInfo and
1445 // also initializes the position cache for all insets in
1446 // (at least partially) visible top-level paragraphs.
1447 // We will redraw the screen only if needed.
1448 bv->processUpdateFlags(dr.screenUpdate());
1450 // Do we have a selection?
1451 theSelection().haveSelection(bv->cursor().selection());
1454 current_view_->restartCaret();
1456 if (dr.needMessageUpdate()) {
1457 // Some messages may already be translated, so we cannot use _()
1458 current_view_->message(makeDispatchMessage(
1459 translateIfPossible(dr.message()), cmd));
1464 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1465 bool switchToBuffer)
1467 if (!theSession().bookmarks().isValid(idx))
1469 BookmarksSection::Bookmark const & bm =
1470 theSession().bookmarks().bookmark(idx);
1471 LASSERT(!bm.filename.empty(), return);
1472 string const file = bm.filename.absFileName();
1473 // if the file is not opened, open it.
1474 if (!theBufferList().exists(bm.filename)) {
1476 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1480 // open may fail, so we need to test it again
1481 if (!theBufferList().exists(bm.filename))
1484 // bm can be changed when saving
1485 BookmarksSection::Bookmark tmp = bm;
1487 // Special case idx == 0 used for back-from-back jump navigation
1489 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1491 // if the current buffer is not that one, switch to it.
1492 BufferView * doc_bv = current_view_ ?
1493 current_view_->documentBufferView() : 0;
1494 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1495 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1496 if (switchToBuffer) {
1497 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1500 doc_bv = current_view_->documentBufferView();
1505 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1506 if (!doc_bv || !doc_bv->moveToPosition(
1507 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1510 Cursor & cur = doc_bv->cursor();
1511 if (old && cur != *old)
1512 notifyCursorLeavesOrEnters(*old, cur);
1518 // Cursor jump succeeded!
1519 pit_type new_pit = cur.pit();
1520 pos_type new_pos = cur.pos();
1521 int new_id = cur.paragraph().id();
1523 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1524 // see http://www.lyx.org/trac/ticket/3092
1525 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1526 || bm.top_id != new_id) {
1527 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1528 new_pit, new_pos, new_id);
1532 // This function runs "configure" and then rereads lyx.defaults to
1533 // reconfigure the automatic settings.
1534 void GuiApplication::reconfigure(string const & option)
1536 // emit message signal.
1538 current_view_->message(_("Running configure..."));
1540 // Run configure in user lyx directory
1541 string const lock_file = package().getConfigureLockName();
1542 int fd = fileLock(lock_file.c_str());
1543 int const ret = package().reconfigureUserLyXDir(option);
1544 // emit message signal.
1546 current_view_->message(_("Reloading configuration..."));
1547 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1548 // Re-read packages.lst
1549 LaTeXPackages::getAvailable();
1550 fileUnlock(fd, lock_file.c_str());
1553 Alert::information(_("System reconfiguration failed"),
1554 _("The system reconfiguration has failed.\n"
1555 "Default textclass is used but LyX may\n"
1556 "not be able to work properly.\n"
1557 "Please reconfigure again if needed."));
1559 Alert::information(_("System reconfigured"),
1560 _("The system has been reconfigured.\n"
1561 "You need to restart LyX to make use of any\n"
1562 "updated document class specifications."));
1565 void GuiApplication::validateCurrentView()
1567 if (!d->views_.empty() && !current_view_) {
1568 // currently at least one view exists but no view has the focus.
1569 // choose the last view to make it current.
1570 // a view without any open document is preferred.
1571 GuiView * candidate = 0;
1572 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1573 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1574 for (; it != end; ++it) {
1576 if (!candidate->documentBufferView())
1579 setCurrentView(candidate);
1583 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1585 string const argument = to_utf8(cmd.argument());
1586 FuncCode const action = cmd.action();
1588 LYXERR(Debug::ACTION, "cmd: " << cmd);
1590 // we have not done anything wrong yet.
1593 FuncStatus const flag = getStatus(cmd);
1594 if (!flag.enabled()) {
1595 // We cannot use this function here
1596 LYXERR(Debug::ACTION, "action "
1597 << lyxaction.getActionName(action)
1598 << " [" << action << "] is disabled at this location");
1599 dr.setMessage(flag.message());
1601 dr.dispatched(false);
1602 dr.screenUpdate(Update::None);
1603 dr.clearBufferUpdate();
1607 if (cmd.origin() == FuncRequest::LYXSERVER) {
1608 if (current_view_ && current_view_->currentBufferView())
1609 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1610 // we will also need to redraw the screen at the end
1611 dr.screenUpdate(Update::FitCursor);
1614 // Assumes that the action will be dispatched.
1615 dr.dispatched(true);
1617 switch (cmd.action()) {
1619 case LFUN_WINDOW_NEW:
1620 createView(toqstr(cmd.argument()));
1623 case LFUN_WINDOW_CLOSE:
1624 // update bookmark pit of the current buffer before window close
1625 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1626 gotoBookmark(i+1, false, false);
1627 // clear the last opened list, because
1628 // maybe this will end the session
1629 theSession().lastOpened().clear();
1630 // check for valid current_view_
1631 validateCurrentView();
1633 current_view_->closeScheduled();
1637 // quitting is triggered by the gui code
1638 // (leaving the event loop).
1640 current_view_->message(from_utf8(N_("Exiting.")));
1641 if (closeAllViews())
1645 case LFUN_SCREEN_FONT_UPDATE: {
1646 // handle the screen font changes.
1647 d->font_loader_.update();
1648 dr.screenUpdate(Update::Force | Update::FitCursor);
1652 case LFUN_BUFFER_NEW:
1653 validateCurrentView();
1655 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1656 createView(QString(), false); // keep hidden
1657 current_view_->newDocument(to_utf8(cmd.argument()), false);
1658 current_view_->show();
1659 setActiveWindow(current_view_);
1661 current_view_->newDocument(to_utf8(cmd.argument()), false);
1665 case LFUN_BUFFER_NEW_TEMPLATE:
1666 validateCurrentView();
1668 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1670 current_view_->newDocument(to_utf8(cmd.argument()), true);
1671 if (!current_view_->documentBufferView())
1672 current_view_->close();
1674 current_view_->newDocument(to_utf8(cmd.argument()), true);
1678 case LFUN_FILE_OPEN: {
1679 // FIXME: normally the code below is not needed, since getStatus makes sure that
1680 // current_view_ is not null.
1681 validateCurrentView();
1682 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1683 string const fname = to_utf8(cmd.argument());
1684 bool const is_open = FileName::isAbsolute(fname)
1685 && theBufferList().getBuffer(FileName(fname));
1687 || (!lyxrc.open_buffers_in_tabs
1688 && current_view_->documentBufferView() != 0
1690 // We want the ui session to be saved per document and not per
1691 // window number. The filename crc is a good enough identifier.
1692 boost::crc_32_type crc;
1693 crc = for_each(fname.begin(), fname.end(), crc);
1694 createView(crc.checksum());
1695 current_view_->openDocument(fname);
1696 if (!current_view_->documentBufferView())
1697 current_view_->close();
1698 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1699 current_view_->raise();
1700 current_view_->activateWindow();
1701 current_view_->showNormal();
1704 current_view_->openDocument(fname);
1705 if (cmd.origin() == FuncRequest::LYXSERVER) {
1706 current_view_->raise();
1707 current_view_->activateWindow();
1708 current_view_->showNormal();
1714 case LFUN_HELP_OPEN: {
1715 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1716 if (current_view_ == 0)
1718 string const arg = to_utf8(cmd.argument());
1720 current_view_->message(_("Missing argument"));
1723 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1725 fname = i18nLibFileSearch("examples", arg, "lyx");
1727 if (fname.empty()) {
1728 lyxerr << "LyX: unable to find documentation file `"
1729 << arg << "'. Bad installation?" << endl;
1732 current_view_->message(bformat(_("Opening help file %1$s..."),
1733 makeDisplayPath(fname.absFileName())));
1734 Buffer * buf = current_view_->loadDocument(fname, false);
1736 buf->setReadonly(!current_view_->develMode());
1740 case LFUN_SET_COLOR: {
1741 string const lyx_name = cmd.getArg(0);
1742 string const x11_name = cmd.getArg(1);
1743 if (lyx_name.empty() || x11_name.empty()) {
1745 current_view_->message(
1746 _("Syntax: set-color <lyx_name> <x11_name>"));
1751 // FIXME: The graphics cache no longer has a changeDisplay method.
1752 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1753 bool const graphicsbg_changed =
1754 lyx_name == graphicsbg && x11_name != graphicsbg;
1755 if (graphicsbg_changed)
1756 graphics::GCache::get().changeDisplay(true);
1759 if (!lcolor.setColor(lyx_name, x11_name)) {
1761 current_view_->message(
1762 bformat(_("Set-color \"%1$s\" failed "
1763 "- color is undefined or "
1764 "may not be redefined"),
1765 from_utf8(lyx_name)));
1768 // Make sure we don't keep old colors in cache.
1769 d->color_cache_.clear();
1770 // Update the current view
1771 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1775 case LFUN_LYXRC_APPLY: {
1776 // reset active key sequences, since the bindings
1777 // are updated (bug 6064)
1779 LyXRC const lyxrc_orig = lyxrc;
1781 istringstream ss(to_utf8(cmd.argument()));
1782 bool const success = lyxrc.read(ss);
1785 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1786 << "Unable to read lyxrc data"
1791 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1793 // If the request comes from the minibuffer, then we can't reset
1794 // the GUI, since that would destory the minibuffer itself and
1795 // cause a crash, since we are currently in one of the methods of
1796 // GuiCommandBuffer. See bug #8540.
1797 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1800 // FIXME Unfortunately, that leaves a bug here, since we cannot
1801 // reset the GUI in this case. If the changes to lyxrc affected the
1802 // UI, then, nothing would happen. This seems fairly unlikely, but
1803 // it definitely is a bug.
1805 dr.forceBufferUpdate();
1809 case LFUN_COMMAND_PREFIX:
1810 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1815 d->meta_fake_bit = NoModifier;
1816 GuiView * gv = currentView();
1817 if (gv && gv->currentBufferView())
1818 // cancel any selection
1819 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1820 dr.setMessage(from_ascii(N_("Cancel")));
1823 case LFUN_META_PREFIX:
1824 d->meta_fake_bit = AltModifier;
1825 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1828 // --- Menus -----------------------------------------------
1829 case LFUN_RECONFIGURE:
1830 // argument is any additional parameter to the configure.py command
1831 reconfigure(to_utf8(cmd.argument()));
1834 // --- lyxserver commands ----------------------------
1835 case LFUN_SERVER_GET_FILENAME: {
1836 if (current_view_ && current_view_->documentBufferView()) {
1837 docstring const fname = from_utf8(
1838 current_view_->documentBufferView()->buffer().absFileName());
1839 dr.setMessage(fname);
1840 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1842 dr.setMessage(docstring());
1843 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1848 case LFUN_SERVER_NOTIFY: {
1849 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1850 dr.setMessage(dispatch_buffer);
1851 theServer().notifyClient(to_utf8(dispatch_buffer));
1855 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1856 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1862 string rest = split(argument, countstr, ' ');
1863 int const count = convert<int>(countstr);
1864 // an arbitrary number to limit number of iterations
1865 int const max_iter = 10000;
1866 if (count > max_iter) {
1867 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1870 for (int i = 0; i < count; ++i) {
1871 FuncRequest lfun = lyxaction.lookupFunc(rest);
1872 lfun.allowAsync(false);
1879 case LFUN_COMMAND_SEQUENCE: {
1880 // argument contains ';'-terminated commands
1881 string arg = argument;
1882 // FIXME: this LFUN should also work without any view.
1883 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1884 ? &(current_view_->documentBufferView()->buffer()) : 0;
1885 // This handles undo groups automagically
1886 UndoGroupHelper ugh(buffer);
1887 while (!arg.empty()) {
1889 arg = split(arg, first, ';');
1890 FuncRequest func(lyxaction.lookupFunc(first));
1891 func.allowAsync(false);
1892 func.setOrigin(cmd.origin());
1898 case LFUN_BUFFER_FORALL: {
1899 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1900 funcToRun.allowAsync(false);
1902 map<Buffer *, GuiView *> views_lVisible;
1903 map<GuiView *, Buffer *> activeBuffers;
1905 QList<GuiView *> allViews = d->views_.values();
1907 // this for does not modify any buffer. It just collects info on local
1908 // visibility of buffers and on which buffer is active in each view.
1909 Buffer * const last = theBufferList().last();
1910 for(GuiView * view : allViews) {
1911 // all of the buffers might be locally hidden. That is, there is no
1913 if (!view || !view->currentBufferView())
1914 activeBuffers[view] = 0;
1916 activeBuffers[view] = &view->currentBufferView()->buffer();
1918 // find out if each is locally visible or locally hidden.
1919 // we don't use a for loop as the buffer list cycles.
1920 Buffer * b = theBufferList().first();
1922 bool const locallyVisible = view && view->workArea(*b);
1923 if (locallyVisible) {
1924 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1925 // only need to overwrite/add if we don't already know a buffer is globally
1926 // visible or we do know but we would prefer to dispatch LFUN from the
1927 // current view because of cursor position issues.
1928 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1929 views_lVisible[b] = view;
1933 b = theBufferList().next(b);
1937 GuiView * const homeView = currentView();
1938 Buffer * b = theBufferList().first();
1939 Buffer * nextBuf = 0;
1940 int numProcessed = 0;
1943 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1945 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1947 // first change to a view where b is locally visible, preferably current_view_.
1948 GuiView * const vLv = views_lVisible[b];
1950 lyx::dispatch(funcToRun);
1958 // put things back to how they were (if possible).
1959 for (GuiView * view : allViews) {
1960 Buffer * originalBuf = activeBuffers[view];
1961 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1962 if (theBufferList().isLoaded(originalBuf))
1963 view->setBuffer(originalBuf);
1965 homeView->setFocus();
1967 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1971 case LFUN_COMMAND_ALTERNATIVES: {
1972 // argument contains ';'-terminated commands
1973 string arg = argument;
1974 while (!arg.empty()) {
1976 arg = split(arg, first, ';');
1977 FuncRequest func(lyxaction.lookupFunc(first));
1978 func.setOrigin(cmd.origin());
1979 FuncStatus const stat = getStatus(func);
1980 if (stat.enabled()) {
1990 if (theTopLevelCmdDef().lock(argument, func)) {
1991 func.setOrigin(cmd.origin());
1993 theTopLevelCmdDef().release(argument);
1995 if (func.action() == LFUN_UNKNOWN_ACTION) {
1996 // unknown command definition
1997 lyxerr << "Warning: unknown command definition `"
2001 // recursion detected
2002 lyxerr << "Warning: Recursion in the command definition `"
2003 << argument << "' detected"
2010 case LFUN_PREFERENCES_SAVE:
2011 lyxrc.write(support::makeAbsPath("preferences",
2012 package().user_support().absFileName()), false);
2015 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2016 string const fname = addName(addPath(package().user_support().absFileName(),
2017 "templates/"), "defaults.lyx");
2018 Buffer defaults(fname);
2020 istringstream ss(argument);
2025 // We need to make sure that, after we recreat the DocumentClass,
2026 // which we do in readHeader, we apply it to the document itself.
2027 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2028 int const unknown_tokens = defaults.readHeader(lex);
2029 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2031 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2032 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2034 if (unknown_tokens != 0) {
2035 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2036 << unknown_tokens << " unknown token"
2037 << (unknown_tokens == 1 ? "" : "s")
2041 if (defaults.writeFile(FileName(defaults.absFileName())))
2042 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2043 makeDisplayPath(fname)));
2046 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2051 case LFUN_BOOKMARK_GOTO:
2052 // go to bookmark, open unopened file and switch to buffer if necessary
2053 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2054 dr.screenUpdate(Update::Force | Update::FitCursor);
2057 case LFUN_BOOKMARK_CLEAR:
2058 theSession().bookmarks().clear();
2061 case LFUN_DEBUG_LEVEL_SET:
2062 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2065 case LFUN_DIALOG_SHOW: {
2066 string const name = cmd.getArg(0);
2068 if ( name == "aboutlyx"
2070 || name == "texinfo"
2071 || name == "progress"
2072 || name == "compare")
2074 // work around: on Mac OS the application
2075 // is not terminated when closing the last view.
2076 // Create a new one to be able to dispatch the
2077 // LFUN_DIALOG_SHOW to this view.
2078 if (current_view_ == 0)
2084 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2087 current_view_->dispatch(cmd, dr);
2091 if (cmd.origin() == FuncRequest::LYXSERVER)
2092 updateCurrentView(cmd, dr);
2096 docstring GuiApplication::viewStatusMessage()
2098 // When meta-fake key is pressed, show the key sequence so far + "M-".
2099 if (d->meta_fake_bit != NoModifier)
2100 return d->keyseq.print(KeySequence::ForGui) + "M-";
2102 // Else, when a non-complete key sequence is pressed,
2103 // show the available options.
2104 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2105 return d->keyseq.printOptions(true);
2111 void GuiApplication::handleKeyFunc(FuncCode action)
2115 if (d->keyseq.length())
2117 GuiView * gv = currentView();
2118 LASSERT(gv && gv->currentBufferView(), return);
2119 BufferView * bv = gv->currentBufferView();
2120 bv->getIntl().getTransManager().deadkey(
2121 c, get_accent(action).accent, bv->cursor().innerText(),
2123 // Need to clear, in case the minibuffer calls these
2126 // copied verbatim from do_accent_char
2127 bv->cursor().resetAnchor();
2131 //Keep this in sync with GuiApplication::processKeySym below
2132 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2133 KeyModifier state) const
2135 // Do nothing if we have nothing
2136 if (!keysym.isOK() || keysym.isModifier())
2138 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2140 FuncRequest func = seq.addkey(keysym, state);
2141 // When not cancel or meta-fake, do the normal lookup.
2142 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2144 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2146 // Maybe user can only reach the key via holding down shift.
2147 // Let's see. But only if shift is the only modifier
2148 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2149 // If addkey looked up a command and did not find further commands then
2150 // seq has been reset at this point
2151 func = seq.addkey(keysym, NoModifier);
2153 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2154 << seq.print(KeySequence::Portable) << ']');
2155 return func.action() != LFUN_UNKNOWN_ACTION;
2159 //Keep this in sync with GuiApplication::queryKeySym above
2160 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2162 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2164 // Do nothing if we have nothing (JMarc)
2165 if (!keysym.isOK() || keysym.isModifier()) {
2167 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2169 current_view_->restartCaret();
2173 char_type encoded_last_key = keysym.getUCSEncoded();
2175 // Do a one-deep top-level lookup for
2176 // cancel and meta-fake keys. RVDK_PATCH_5
2177 d->cancel_meta_seq.reset();
2179 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2180 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2182 // When not cancel or meta-fake, do the normal lookup.
2183 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2184 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2185 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2186 // remove Caps Lock and Mod2 as a modifiers
2187 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2188 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2191 // Dont remove this unless you know what you are doing.
2192 d->meta_fake_bit = NoModifier;
2194 // Can this happen now ?
2195 if (func.action() == LFUN_NOACTION)
2196 func = FuncRequest(LFUN_COMMAND_PREFIX);
2198 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2199 << d->keyseq.print(KeySequence::Portable) << ']');
2201 // already here we know if it any point in going further
2202 // why not return already here if action == -1 and
2203 // num_bytes == 0? (Lgb)
2205 if (d->keyseq.length() > 1 && current_view_)
2206 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2209 // Maybe user can only reach the key via holding down shift.
2210 // Let's see. But only if shift is the only modifier
2211 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2212 LYXERR(Debug::KEY, "Trying without shift");
2213 // If addkey looked up a command and did not find further commands then
2214 // seq has been reset at this point
2215 func = d->keyseq.addkey(keysym, NoModifier);
2216 LYXERR(Debug::KEY, "Action now " << func.action());
2219 if (func.action() == LFUN_UNKNOWN_ACTION) {
2220 // We didn't match any of the key sequences.
2221 // See if it's normal insertable text not already
2222 // covered by a binding
2223 if (keysym.isText() && d->keyseq.length() == 1) {
2224 // Non-printable characters (such as ASCII control characters)
2225 // must not be inserted (#5704)
2226 if (!isPrintable(encoded_last_key)) {
2227 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2229 current_view_->restartCaret();
2232 // The following modifier check is not needed on Mac.
2233 // The keysym is either not text or it is different
2234 // from the non-modifier keysym. See #9875 for the
2235 // broken alt-modifier effect of having this code active.
2236 #if !defined(Q_OS_MAC)
2237 // If a non-Shift Modifier is used we have a non-bound key sequence
2238 // (such as Alt+j = j). This should be omitted (#5575).
2239 // On Windows, AltModifier and ControlModifier are both
2240 // set when AltGr is pressed. Therefore, in order to not
2241 // break AltGr-bound symbols (see #5575 for details),
2242 // unbound Ctrl+Alt key sequences are allowed.
2243 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2244 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2245 && !(state & AltModifier && state & ControlModifier)
2249 if (current_view_) {
2250 current_view_->message(_("Unknown function."));
2251 current_view_->restartCaret();
2256 // Since all checks above were passed, we now really have text that
2257 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2258 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2260 LYXERR(Debug::KEY, "isText() is true, inserting.");
2261 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2263 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2264 if (current_view_) {
2265 current_view_->message(_("Unknown function."));
2266 current_view_->restartCaret();
2272 if (func.action() == LFUN_SELF_INSERT) {
2273 if (encoded_last_key != 0) {
2274 docstring const arg(1, encoded_last_key);
2275 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2276 FuncRequest::KEYBOARD));
2277 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2280 processFuncRequest(func);
2284 void GuiApplication::processFuncRequest(FuncRequest const & func)
2286 lyx::dispatch(func);
2290 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2292 addToFuncRequestQueue(func);
2293 processFuncRequestQueueAsync();
2297 void GuiApplication::processFuncRequestQueue()
2299 while (!d->func_request_queue_.empty()) {
2300 // take the item from the stack _before_ processing the
2301 // request in order to avoid race conditions from nested
2302 // or parallel requests (see #10406)
2303 FuncRequest const fr(d->func_request_queue_.front());
2304 d->func_request_queue_.pop();
2305 processFuncRequest(fr);
2310 void GuiApplication::processFuncRequestQueueAsync()
2312 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2316 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2318 d->func_request_queue_.push(func);
2322 void GuiApplication::resetGui()
2324 // Set the language defined by the user.
2328 if (!readUIFile(toqstr(lyxrc.ui_file)))
2329 // Gives some error box here.
2332 if (d->global_menubar_)
2333 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2335 QHash<int, GuiView *>::iterator it;
2336 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2339 gv->setLayoutDirection(layoutDirection());
2343 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2347 void GuiApplication::createView(int view_id)
2349 createView(QString(), true, view_id);
2353 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2356 // release the keyboard which might have been grabed by the global
2357 // menubar on Mac to catch shortcuts even without any GuiView.
2358 if (d->global_menubar_)
2359 d->global_menubar_->releaseKeyboard();
2363 while (d->views_.find(id) != d->views_.end())
2366 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2367 GuiView * view = new GuiView(id);
2368 // `view' is the new current_view_. Tell coverity that is is not 0.
2369 LATTEST(current_view_);
2371 d->views_[id] = view;
2375 setActiveWindow(view);
2378 if (!geometry_arg.isEmpty()) {
2379 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2383 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2384 re.indexIn(geometry_arg);
2385 w = re.cap(1).toInt();
2386 h = re.cap(2).toInt();
2387 x = re.cap(3).toInt();
2388 y = re.cap(4).toInt();
2389 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2390 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2391 // Set initial geometry such that we can get the frame size.
2392 view->setGeometry(x, y, w, h);
2393 int framewidth = view->geometry().x() - view->x();
2394 int titleheight = view->geometry().y() - view->y();
2395 // Negative displacements must be interpreted as distances
2396 // from the right or bottom screen borders.
2397 if (sx == '-' || sy == '-') {
2398 QRect rec = QApplication::desktop()->screenGeometry();
2400 x += rec.width() - w - framewidth;
2402 y += rec.height() - h - titleheight;
2403 view->setGeometry(x, y, w, h);
2405 // Make sure that the left and top frame borders are visible.
2406 if (view->x() < 0 || view->y() < 0) {
2411 view->setGeometry(x, y, w, h);
2419 bool GuiApplication::unhide(Buffer * buf)
2423 currentView()->setBuffer(buf, false);
2428 Clipboard & GuiApplication::clipboard()
2430 return d->clipboard_;
2434 Selection & GuiApplication::selection()
2436 return d->selection_;
2440 FontLoader & GuiApplication::fontLoader()
2442 return d->font_loader_;
2446 Toolbars const & GuiApplication::toolbars() const
2448 return d->toolbars_;
2452 Toolbars & GuiApplication::toolbars()
2454 return d->toolbars_;
2458 Menus const & GuiApplication::menus() const
2464 Menus & GuiApplication::menus()
2470 QList<int> GuiApplication::viewIds() const
2472 return d->views_.keys();
2476 ColorCache & GuiApplication::colorCache()
2478 return d->color_cache_;
2482 int GuiApplication::exec()
2484 // asynchronously handle batch commands. This event will be in
2485 // the event queue in front of other asynchronous events. Hence,
2486 // we can assume in the latter that the gui is setup already.
2487 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2489 return QApplication::exec();
2493 void GuiApplication::exit(int status)
2495 QApplication::exit(status);
2499 void GuiApplication::setGuiLanguage()
2503 // install translation file for Qt built-in dialogs
2504 QString const language_name = QString("qt_") + theLocale.name();
2505 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2506 // Short-named translator can be loaded from a long name, but not the
2507 // opposite. Therefore, long name should be used without truncation.
2508 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2509 if (!d->qt_trans_.load(language_name,
2510 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2511 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2514 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2518 switch (theLocale.language()) {
2519 case QLocale::Arabic :
2520 case QLocale::Hebrew :
2521 case QLocale::Persian :
2522 case QLocale::Urdu :
2523 setLayoutDirection(Qt::RightToLeft);
2526 setLayoutDirection(Qt::LeftToRight);
2531 void GuiApplication::execBatchCommands()
2536 if (!readUIFile(toqstr(lyxrc.ui_file)))
2537 // Gives some error box here.
2541 #if QT_VERSION > 0x040600
2542 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2544 #if QT_VERSION > 0x050100
2545 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2547 // Create the global default menubar which is shown for the dialogs
2548 // and if no GuiView is visible.
2549 // This must be done after the session was recovered to know the "last files".
2550 d->global_menubar_ = new QMenuBar(0);
2551 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2554 lyx::execBatchCommands();
2558 QAbstractItemModel * GuiApplication::languageModel()
2560 if (d->language_model_)
2561 return d->language_model_;
2563 QStandardItemModel * lang_model = new QStandardItemModel(this);
2564 lang_model->insertColumns(0, 3);
2565 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2566 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2567 Languages::const_iterator it = lyx::languages.begin();
2568 Languages::const_iterator end = lyx::languages.end();
2569 for (; it != end; ++it) {
2570 int current_row = lang_model->rowCount();
2571 lang_model->insertRows(current_row, 1);
2572 QModelIndex pl_item = lang_model->index(current_row, 0);
2573 QModelIndex sp_item = lang_model->index(current_row, 1);
2574 QModelIndex th_item = lang_model->index(current_row, 2);
2575 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2576 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2577 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2578 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2579 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2580 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2581 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2582 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2583 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2584 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2586 d->language_model_ = new QSortFilterProxyModel(this);
2587 d->language_model_->setSourceModel(lang_model);
2588 d->language_model_->setSortLocaleAware(true);
2589 return d->language_model_;
2593 void GuiApplication::restoreGuiSession()
2595 if (!lyxrc.load_session)
2598 Session & session = theSession();
2599 LastOpenedSection::LastOpened const & lastopened =
2600 session.lastOpened().getfiles();
2602 validateCurrentView();
2604 FileName active_file;
2605 // do not add to the lastfile list since these files are restored from
2606 // last session, and should be already there (regular files), or should
2607 // not be added at all (help files).
2608 for (size_t i = 0; i < lastopened.size(); ++i) {
2609 FileName const & file_name = lastopened[i].file_name;
2610 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2611 && current_view_->documentBufferView() != 0)) {
2612 boost::crc_32_type crc;
2613 string const & fname = file_name.absFileName();
2614 crc = for_each(fname.begin(), fname.end(), crc);
2615 createView(crc.checksum());
2617 current_view_->loadDocument(file_name, false);
2619 if (lastopened[i].active)
2620 active_file = file_name;
2623 // Restore last active buffer
2624 Buffer * buffer = theBufferList().getBuffer(active_file);
2625 if (buffer && current_view_)
2626 current_view_->setBuffer(buffer);
2628 // clear this list to save a few bytes of RAM
2629 session.lastOpened().clear();
2633 QString const GuiApplication::romanFontName()
2636 font.setStyleHint(QFont::Serif);
2637 font.setFamily("serif");
2639 return QFontInfo(font).family();
2643 QString const GuiApplication::sansFontName()
2646 font.setStyleHint(QFont::SansSerif);
2647 font.setFamily("sans");
2649 return QFontInfo(font).family();
2653 QString const GuiApplication::typewriterFontName()
2655 return QFontInfo(typewriterSystemFont()).family();
2660 // We cannot use QFont::fixedPitch() because it doesn't
2661 // return the fact but only if it is requested.
2662 static bool isFixedPitch(const QFont & font) {
2663 const QFontInfo fi(font);
2664 return fi.fixedPitch();
2669 QFont const GuiApplication::typewriterSystemFont()
2671 #if QT_VERSION >= 0x050200
2672 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2674 QFont font("monospace");
2676 if (!isFixedPitch(font)) {
2677 // try to enforce a real monospaced font
2678 font.setStyleHint(QFont::Monospace);
2679 if (!isFixedPitch(font)) {
2680 font.setStyleHint(QFont::TypeWriter);
2681 if (!isFixedPitch(font)) font.setFamily("courier");
2685 // On a Mac the result is too small and it's not practical to
2686 // rely on Qtconfig utility to change the system settings of Qt.
2687 font.setPointSize(12);
2693 void GuiApplication::handleRegularEvents()
2695 ForkedCallsController::handleCompletedProcesses();
2699 bool GuiApplication::event(QEvent * e)
2702 case QEvent::FileOpen: {
2703 // Open a file; this happens only on Mac OS X for now.
2705 // We do this asynchronously because on startup the batch
2706 // commands are not executed here yet and the gui is not ready
2708 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2709 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2710 processFuncRequestAsync(fr);
2715 return QApplication::event(e);
2720 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2723 return QApplication::notify(receiver, event);
2725 catch (ExceptionMessage const & e) {
2727 case ErrorException:
2729 setQuitOnLastWindowClosed(false);
2731 Alert::error(e.title_, e.details_);
2733 // Properly crash in debug mode in order to get a useful backtrace.
2736 // In release mode, try to exit gracefully.
2738 // FIXME: GCC 7 thinks we can fall through here. Can we?
2740 case BufferException: {
2741 if (!current_view_ || !current_view_->documentBufferView())
2743 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2744 docstring details = e.details_ + '\n';
2745 details += buf->emergencyWrite();
2746 theBufferList().release(buf);
2747 details += "\n" + _("The current document was closed.");
2748 Alert::error(e.title_, details);
2751 case WarningException:
2752 Alert::warning(e.title_, e.details_);
2756 catch (exception const & e) {
2757 docstring s = _("LyX has caught an exception, it will now "
2758 "attempt to save all unsaved documents and exit."
2760 s += from_ascii(e.what());
2761 Alert::error(_("Software exception Detected"), s);
2765 docstring s = _("LyX has caught some really weird exception, it will "
2766 "now attempt to save all unsaved documents and exit.");
2767 Alert::error(_("Software exception Detected"), s);
2775 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2777 QColor const & qcol = d->color_cache_.get(col);
2778 if (!qcol.isValid()) {
2784 rgbcol.r = qcol.red();
2785 rgbcol.g = qcol.green();
2786 rgbcol.b = qcol.blue();
2791 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2793 QColor const qcol(lcolor.getX11Name(col).c_str());
2794 if (!qcol.isValid()) {
2800 rgbcol.r = qcol.red();
2801 rgbcol.g = qcol.green();
2802 rgbcol.b = qcol.blue();
2807 string const GuiApplication::hexName(ColorCode col)
2809 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2813 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2815 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2816 d->socket_notifiers_[fd] = sn;
2817 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2821 void GuiApplication::socketDataReceived(int fd)
2823 d->socket_notifiers_[fd]->func_();
2827 void GuiApplication::unregisterSocketCallback(int fd)
2829 d->socket_notifiers_.take(fd)->setEnabled(false);
2833 void GuiApplication::commitData(QSessionManager & sm)
2835 /** The implementation is required to avoid an application exit
2836 ** when session state save is triggered by session manager.
2837 ** The default implementation sends a close event to all
2838 ** visible top level widgets when session managment allows
2840 ** We are changing that to check the state of each buffer in all
2841 ** views and ask the users what to do if buffers are dirty.
2842 ** Furthermore, we save the session state.
2843 ** We do NOT close the views here since the user still can cancel
2844 ** the logout process (see #9277); also, this would hide LyX from
2845 ** an OSes own session handling (application restoration).
2847 #ifdef QT_NO_SESSIONMANAGER
2849 #warning Qt is compiled without session manager
2851 #pragma message("warning: Qt is compiled without session manager")
2855 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2863 void GuiApplication::unregisterView(GuiView * gv)
2865 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2866 d->views_.remove(gv->id());
2867 if (current_view_ == gv)
2873 bool GuiApplication::closeAllViews()
2875 if (d->views_.empty())
2878 // When a view/window was closed before without quitting LyX, there
2879 // are already entries in the lastOpened list.
2880 theSession().lastOpened().clear();
2882 QList<GuiView *> const views = d->views_.values();
2883 for (GuiView * view : views) {
2884 if (!view->closeScheduled())
2893 bool GuiApplication::prepareAllViewsForLogout()
2895 if (d->views_.empty())
2898 QList<GuiView *> const views = d->views_.values();
2899 for (GuiView * view : views) {
2900 if (!view->prepareAllBuffersForLogout())
2908 GuiView & GuiApplication::view(int id) const
2910 LAPPERR(d->views_.contains(id));
2911 return *d->views_.value(id);
2915 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2917 QList<GuiView *> const views = d->views_.values();
2918 for (GuiView * view : views)
2919 view->hideDialog(name, inset);
2923 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2925 Buffer const * buffer_ = 0;
2926 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2927 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2928 if (Buffer const * ptr = (*it)->updateInset(inset))
2935 bool GuiApplication::searchMenu(FuncRequest const & func,
2936 docstring_list & names) const
2938 BufferView * bv = 0;
2940 bv = current_view_->currentBufferView();
2941 return d->menus_.searchMenu(func, names, bv);
2945 bool GuiApplication::hasBufferView() const
2947 return (current_view_ && current_view_->currentBufferView());
2951 // Ensure that a file is read only once (prevents include loops)
2952 static QStringList uifiles;
2953 // store which ui files define Toolbars
2954 static QStringList toolbar_uifiles;
2957 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2968 LexerKeyword uitags[] = {
2969 { "format", ui_format },
2970 { "include", ui_include },
2971 { "menuset", ui_menuset },
2972 { "toolbars", ui_toolbars },
2973 { "toolbarset", ui_toolbarset }
2977 lex.setFile(ui_path);
2979 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2983 if (lyxerr.debugging(Debug::PARSER))
2984 lex.printTable(lyxerr);
2987 // format before introduction of format tag
2988 unsigned int format = 0;
2989 while (lex.isOK()) {
2990 int const status = lex.lex();
2992 // we have to do this check here, outside the switch,
2993 // because otherwise we would start reading include files,
2994 // e.g., if the first tag we hit was an include tag.
2995 if (status == ui_format)
2997 format = lex.getInteger();
3001 // this will trigger unless the first tag we hit is a format
3002 // tag, with the right format.
3003 if (format != LFUN_FORMAT)
3004 return FormatMismatch;
3007 case Lexer::LEX_FEOF:
3012 QString const file = toqstr(lex.getString());
3013 bool const success = readUIFile(file, true);
3015 LYXERR0("Failed to read included file: " << fromqstr(file));
3022 d->menus_.read(lex);
3026 d->toolbars_.readToolbars(lex);
3030 d->toolbars_.readToolbarSettings(lex);
3031 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3035 if (!rtrim(lex.getString()).empty())
3036 lex.printError("LyX::ReadUIFile: "
3037 "Unknown menu tag: `$$Token'");
3039 LYXERR0("Error with status: " << status);
3045 return (error ? ReadError : ReadOK);
3049 bool GuiApplication::readUIFile(QString const & name, bool include)
3051 LYXERR(Debug::INIT, "About to read " << name << "...");
3055 ui_path = libFileSearch("ui", name, "inc");
3056 if (ui_path.empty())
3057 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3059 ui_path = libFileSearch("ui", name, "ui");
3062 if (ui_path.empty()) {
3063 static const QString defaultUIFile = "default";
3064 LYXERR(Debug::INIT, "Could not find " << name);
3066 Alert::warning(_("Could not find UI definition file"),
3067 bformat(_("Error while reading the included file\n%1$s\n"
3068 "Please check your installation."), qstring_to_ucs4(name)));
3071 if (name == defaultUIFile) {
3072 LYXERR(Debug::INIT, "Could not find default UI file!!");
3073 Alert::warning(_("Could not find default UI file"),
3074 _("LyX could not find the default UI file!\n"
3075 "Please check your installation."));
3078 Alert::warning(_("Could not find UI definition file"),
3079 bformat(_("Error while reading the configuration file\n%1$s\n"
3080 "Falling back to default.\n"
3081 "Please look under Tools>Preferences>User Interface and\n"
3082 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3083 return readUIFile(defaultUIFile, false);
3086 QString const uifile = toqstr(ui_path.absFileName());
3087 if (uifiles.contains(uifile)) {
3089 // We are reading again the top uifile so reset the safeguard:
3092 d->toolbars_.reset();
3094 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3095 << "Is this an include loop?");
3099 uifiles.push_back(uifile);
3101 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3103 ReturnValues retval = readUIFile(ui_path);
3105 if (retval == FormatMismatch) {
3106 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3107 TempFile tmp("convertXXXXXX.ui");
3108 FileName const tempfile = tmp.name();
3109 bool const success = prefs2prefs(ui_path, tempfile, true);
3111 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3112 " to format " << LFUN_FORMAT << ".");
3114 retval = readUIFile(tempfile);
3118 if (retval != ReadOK) {
3119 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3127 settings.beginGroup("ui_files");
3128 bool touched = false;
3129 for (int i = 0; i != uifiles.size(); ++i) {
3130 QFileInfo fi(uifiles[i]);
3131 QDateTime const date_value = fi.lastModified();
3132 QString const name_key = QString::number(i);
3133 // if an ui file which defines Toolbars has changed,
3134 // we have to reset the settings
3135 if (toolbar_uifiles.contains(uifiles[i])
3136 && (!settings.contains(name_key)
3137 || settings.value(name_key).toString() != uifiles[i]
3138 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3140 settings.setValue(name_key, uifiles[i]);
3141 settings.setValue(name_key + "/date", date_value);
3144 settings.endGroup();
3146 settings.remove("views");
3152 void GuiApplication::onLastWindowClosed()
3154 if (d->global_menubar_)
3155 d->global_menubar_->grabKeyboard();
3159 void GuiApplication::startLongOperation() {
3160 d->key_checker_.start();
3164 bool GuiApplication::longOperationCancelled() {
3165 return d->key_checker_.pressed();
3169 void GuiApplication::stopLongOperation() {
3170 d->key_checker_.stop();
3174 bool GuiApplication::longOperationStarted() {
3175 return d->key_checker_.started();
3179 ////////////////////////////////////////////////////////////////////////
3181 // X11 specific stuff goes here...
3184 bool GuiApplication::x11EventFilter(XEvent * xev)
3189 switch (xev->type) {
3190 case SelectionRequest: {
3191 if (xev->xselectionrequest.selection != XA_PRIMARY)
3193 LYXERR(Debug::SELECTION, "X requested selection.");
3194 BufferView * bv = current_view_->currentBufferView();
3196 docstring const sel = bv->requestSelection();
3198 d->selection_.put(sel);
3199 // Refresh the selection request timestamp.
3200 // We have to do this by ourselves as Qt seems
3201 // not doing that, maybe because of our
3202 // "persistent selection" implementation
3203 // (see comments in GuiSelection.cpp).
3204 XSelectionEvent nev;
3205 nev.type = SelectionNotify;
3206 nev.display = xev->xselectionrequest.display;
3207 nev.requestor = xev->xselectionrequest.requestor;
3208 nev.selection = xev->xselectionrequest.selection;
3209 nev.target = xev->xselectionrequest.target;
3210 nev.property = 0L; // None
3211 nev.time = CurrentTime;
3212 XSendEvent(QX11Info::display(),
3213 nev.requestor, False, 0,
3214 reinterpret_cast<XEvent *>(&nev));
3220 case SelectionClear: {
3221 if (xev->xselectionclear.selection != XA_PRIMARY)
3223 LYXERR(Debug::SELECTION, "Lost selection.");
3224 BufferView * bv = current_view_->currentBufferView();
3226 bv->clearSelection();
3232 #elif defined(QPA_XCB)
3233 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3234 void * message, long *)
3236 if (!current_view_ || eventType != "xcb_generic_event_t")
3239 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3241 switch (ev->response_type) {
3242 case XCB_SELECTION_REQUEST: {
3243 xcb_selection_request_event_t * srev =
3244 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3245 if (srev->selection != XCB_ATOM_PRIMARY)
3247 LYXERR(Debug::SELECTION, "X requested selection.");
3248 BufferView * bv = current_view_->currentBufferView();
3250 docstring const sel = bv->requestSelection();
3252 d->selection_.put(sel);
3253 #ifdef HAVE_QT5_X11_EXTRAS
3254 // Refresh the selection request timestamp.
3255 // We have to do this by ourselves as Qt seems
3256 // not doing that, maybe because of our
3257 // "persistent selection" implementation
3258 // (see comments in GuiSelection.cpp).
3259 xcb_selection_notify_event_t nev;
3260 nev.response_type = XCB_SELECTION_NOTIFY;
3261 nev.requestor = srev->requestor;
3262 nev.selection = srev->selection;
3263 nev.target = srev->target;
3264 nev.property = XCB_NONE;
3265 nev.time = XCB_CURRENT_TIME;
3266 xcb_connection_t * con = QX11Info::connection();
3267 xcb_send_event(con, 0, srev->requestor,
3268 XCB_EVENT_MASK_NO_EVENT,
3269 reinterpret_cast<char const *>(&nev));
3277 case XCB_SELECTION_CLEAR: {
3278 xcb_selection_clear_event_t * scev =
3279 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3280 if (scev->selection != XCB_ATOM_PRIMARY)
3282 LYXERR(Debug::SELECTION, "Lost selection.");
3283 BufferView * bv = current_view_->currentBufferView();
3285 bv->clearSelection();
3293 } // namespace frontend
3296 void hideDialogs(std::string const & name, Inset * inset)
3299 frontend::guiApp->hideDialogs(name, inset);
3303 ////////////////////////////////////////////////////////////////////
3307 ////////////////////////////////////////////////////////////////////
3309 frontend::FontLoader & theFontLoader()
3311 LAPPERR(frontend::guiApp);
3312 return frontend::guiApp->fontLoader();
3316 frontend::FontMetrics const & theFontMetrics(Font const & f)
3318 return theFontMetrics(f.fontInfo());
3322 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3324 LAPPERR(frontend::guiApp);
3325 return frontend::guiApp->fontLoader().metrics(f);
3329 ////////////////////////////////////////////////////////////////////
3333 ////////////////////////////////////////////////////////////////////
3335 frontend::Clipboard & theClipboard()
3337 LAPPERR(frontend::guiApp);
3338 return frontend::guiApp->clipboard();
3342 frontend::Selection & theSelection()
3344 LAPPERR(frontend::guiApp);
3345 return frontend::guiApp->selection();
3351 #include "moc_GuiApplication.cpp"