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: {
1742 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
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.
1808 case LFUN_COMMAND_PREFIX:
1809 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1814 d->meta_fake_bit = NoModifier;
1815 GuiView * gv = currentView();
1816 if (gv && gv->currentBufferView())
1817 // cancel any selection
1818 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1819 dr.setMessage(from_ascii(N_("Cancel")));
1822 case LFUN_META_PREFIX:
1823 d->meta_fake_bit = AltModifier;
1824 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1827 // --- Menus -----------------------------------------------
1828 case LFUN_RECONFIGURE:
1829 // argument is any additional parameter to the configure.py command
1830 reconfigure(to_utf8(cmd.argument()));
1833 // --- lyxserver commands ----------------------------
1834 case LFUN_SERVER_GET_FILENAME: {
1835 if (current_view_ && current_view_->documentBufferView()) {
1836 docstring const fname = from_utf8(
1837 current_view_->documentBufferView()->buffer().absFileName());
1838 dr.setMessage(fname);
1839 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1841 dr.setMessage(docstring());
1842 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1847 case LFUN_SERVER_NOTIFY: {
1848 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1849 dr.setMessage(dispatch_buffer);
1850 theServer().notifyClient(to_utf8(dispatch_buffer));
1854 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1855 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1861 string rest = split(argument, countstr, ' ');
1862 int const count = convert<int>(countstr);
1863 // an arbitrary number to limit number of iterations
1864 int const max_iter = 10000;
1865 if (count > max_iter) {
1866 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1869 for (int i = 0; i < count; ++i) {
1870 FuncRequest lfun = lyxaction.lookupFunc(rest);
1871 lfun.allowAsync(false);
1878 case LFUN_COMMAND_SEQUENCE: {
1879 // argument contains ';'-terminated commands
1880 string arg = argument;
1881 // FIXME: this LFUN should also work without any view.
1882 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1883 ? &(current_view_->documentBufferView()->buffer()) : 0;
1884 // This handles undo groups automagically
1885 UndoGroupHelper ugh(buffer);
1886 while (!arg.empty()) {
1888 arg = split(arg, first, ';');
1889 FuncRequest func(lyxaction.lookupFunc(first));
1890 func.allowAsync(false);
1891 func.setOrigin(cmd.origin());
1897 case LFUN_BUFFER_FORALL: {
1898 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1899 funcToRun.allowAsync(false);
1901 map<Buffer *, GuiView *> views_lVisible;
1902 map<GuiView *, Buffer *> activeBuffers;
1904 QList<GuiView *> allViews = d->views_.values();
1906 // this for does not modify any buffer. It just collects info on local
1907 // visibility of buffers and on which buffer is active in each view.
1908 Buffer * const last = theBufferList().last();
1909 for(GuiView * view : allViews) {
1910 // all of the buffers might be locally hidden. That is, there is no
1912 if (!view || !view->currentBufferView())
1913 activeBuffers[view] = 0;
1915 activeBuffers[view] = &view->currentBufferView()->buffer();
1917 // find out if each is locally visible or locally hidden.
1918 // we don't use a for loop as the buffer list cycles.
1919 Buffer * b = theBufferList().first();
1921 bool const locallyVisible = view && view->workArea(*b);
1922 if (locallyVisible) {
1923 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1924 // only need to overwrite/add if we don't already know a buffer is globally
1925 // visible or we do know but we would prefer to dispatch LFUN from the
1926 // current view because of cursor position issues.
1927 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1928 views_lVisible[b] = view;
1932 b = theBufferList().next(b);
1936 GuiView * const homeView = currentView();
1937 Buffer * b = theBufferList().first();
1938 Buffer * nextBuf = 0;
1939 int numProcessed = 0;
1942 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1944 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1946 // first change to a view where b is locally visible, preferably current_view_.
1947 GuiView * const vLv = views_lVisible[b];
1949 lyx::dispatch(funcToRun);
1957 // put things back to how they were (if possible).
1958 for (GuiView * view : allViews) {
1959 Buffer * originalBuf = activeBuffers[view];
1960 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1961 if (theBufferList().isLoaded(originalBuf))
1962 view->setBuffer(originalBuf);
1964 homeView->setFocus();
1966 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1970 case LFUN_COMMAND_ALTERNATIVES: {
1971 // argument contains ';'-terminated commands
1972 string arg = argument;
1973 while (!arg.empty()) {
1975 arg = split(arg, first, ';');
1976 FuncRequest func(lyxaction.lookupFunc(first));
1977 func.setOrigin(cmd.origin());
1978 FuncStatus const stat = getStatus(func);
1979 if (stat.enabled()) {
1989 if (theTopLevelCmdDef().lock(argument, func)) {
1990 func.setOrigin(cmd.origin());
1992 theTopLevelCmdDef().release(argument);
1994 if (func.action() == LFUN_UNKNOWN_ACTION) {
1995 // unknown command definition
1996 lyxerr << "Warning: unknown command definition `"
2000 // recursion detected
2001 lyxerr << "Warning: Recursion in the command definition `"
2002 << argument << "' detected"
2009 case LFUN_PREFERENCES_SAVE:
2010 lyxrc.write(support::makeAbsPath("preferences",
2011 package().user_support().absFileName()), false);
2014 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2015 string const fname = addName(addPath(package().user_support().absFileName(),
2016 "templates/"), "defaults.lyx");
2017 Buffer defaults(fname);
2019 istringstream ss(argument);
2024 // We need to make sure that, after we recreat the DocumentClass,
2025 // which we do in readHeader, we apply it to the document itself.
2026 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2027 int const unknown_tokens = defaults.readHeader(lex);
2028 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2030 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2031 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2033 if (unknown_tokens != 0) {
2034 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2035 << unknown_tokens << " unknown token"
2036 << (unknown_tokens == 1 ? "" : "s")
2040 if (defaults.writeFile(FileName(defaults.absFileName())))
2041 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2042 makeDisplayPath(fname)));
2045 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2050 case LFUN_BOOKMARK_GOTO:
2051 // go to bookmark, open unopened file and switch to buffer if necessary
2052 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2053 dr.screenUpdate(Update::Force | Update::FitCursor);
2056 case LFUN_BOOKMARK_CLEAR:
2057 theSession().bookmarks().clear();
2060 case LFUN_DEBUG_LEVEL_SET:
2061 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2064 case LFUN_DIALOG_SHOW: {
2065 string const name = cmd.getArg(0);
2067 if ( name == "aboutlyx"
2069 || name == "texinfo"
2070 || name == "progress"
2071 || name == "compare")
2073 // work around: on Mac OS the application
2074 // is not terminated when closing the last view.
2075 // Create a new one to be able to dispatch the
2076 // LFUN_DIALOG_SHOW to this view.
2077 if (current_view_ == 0)
2083 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2086 current_view_->dispatch(cmd, dr);
2090 if (cmd.origin() == FuncRequest::LYXSERVER)
2091 updateCurrentView(cmd, dr);
2095 docstring GuiApplication::viewStatusMessage()
2097 // When meta-fake key is pressed, show the key sequence so far + "M-".
2098 if (d->meta_fake_bit != NoModifier)
2099 return d->keyseq.print(KeySequence::ForGui) + "M-";
2101 // Else, when a non-complete key sequence is pressed,
2102 // show the available options.
2103 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2104 return d->keyseq.printOptions(true);
2110 void GuiApplication::handleKeyFunc(FuncCode action)
2114 if (d->keyseq.length())
2116 GuiView * gv = currentView();
2117 LASSERT(gv && gv->currentBufferView(), return);
2118 BufferView * bv = gv->currentBufferView();
2119 bv->getIntl().getTransManager().deadkey(
2120 c, get_accent(action).accent, bv->cursor().innerText(),
2122 // Need to clear, in case the minibuffer calls these
2125 // copied verbatim from do_accent_char
2126 bv->cursor().resetAnchor();
2130 //Keep this in sync with GuiApplication::processKeySym below
2131 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2132 KeyModifier state) const
2134 // Do nothing if we have nothing
2135 if (!keysym.isOK() || keysym.isModifier())
2137 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2139 FuncRequest func = seq.addkey(keysym, state);
2140 // When not cancel or meta-fake, do the normal lookup.
2141 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2143 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2145 // Maybe user can only reach the key via holding down shift.
2146 // Let's see. But only if shift is the only modifier
2147 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2148 // If addkey looked up a command and did not find further commands then
2149 // seq has been reset at this point
2150 func = seq.addkey(keysym, NoModifier);
2152 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2153 << seq.print(KeySequence::Portable) << ']');
2154 return func.action() != LFUN_UNKNOWN_ACTION;
2158 //Keep this in sync with GuiApplication::queryKeySym above
2159 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2161 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2163 // Do nothing if we have nothing (JMarc)
2164 if (!keysym.isOK() || keysym.isModifier()) {
2166 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2168 current_view_->restartCaret();
2172 char_type encoded_last_key = keysym.getUCSEncoded();
2174 // Do a one-deep top-level lookup for
2175 // cancel and meta-fake keys. RVDK_PATCH_5
2176 d->cancel_meta_seq.reset();
2178 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2179 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2181 // When not cancel or meta-fake, do the normal lookup.
2182 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2183 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2184 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2185 // remove Caps Lock and Mod2 as a modifiers
2186 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2187 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2190 // Dont remove this unless you know what you are doing.
2191 d->meta_fake_bit = NoModifier;
2193 // Can this happen now ?
2194 if (func.action() == LFUN_NOACTION)
2195 func = FuncRequest(LFUN_COMMAND_PREFIX);
2197 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2198 << d->keyseq.print(KeySequence::Portable) << ']');
2200 // already here we know if it any point in going further
2201 // why not return already here if action == -1 and
2202 // num_bytes == 0? (Lgb)
2204 if (d->keyseq.length() > 1 && current_view_)
2205 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2208 // Maybe user can only reach the key via holding down shift.
2209 // Let's see. But only if shift is the only modifier
2210 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2211 LYXERR(Debug::KEY, "Trying without shift");
2212 // If addkey looked up a command and did not find further commands then
2213 // seq has been reset at this point
2214 func = d->keyseq.addkey(keysym, NoModifier);
2215 LYXERR(Debug::KEY, "Action now " << func.action());
2218 if (func.action() == LFUN_UNKNOWN_ACTION) {
2219 // We didn't match any of the key sequences.
2220 // See if it's normal insertable text not already
2221 // covered by a binding
2222 if (keysym.isText() && d->keyseq.length() == 1) {
2223 // Non-printable characters (such as ASCII control characters)
2224 // must not be inserted (#5704)
2225 if (!isPrintable(encoded_last_key)) {
2226 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2228 current_view_->restartCaret();
2231 // The following modifier check is not needed on Mac.
2232 // The keysym is either not text or it is different
2233 // from the non-modifier keysym. See #9875 for the
2234 // broken alt-modifier effect of having this code active.
2235 #if !defined(Q_OS_MAC)
2236 // If a non-Shift Modifier is used we have a non-bound key sequence
2237 // (such as Alt+j = j). This should be omitted (#5575).
2238 // On Windows, AltModifier and ControlModifier are both
2239 // set when AltGr is pressed. Therefore, in order to not
2240 // break AltGr-bound symbols (see #5575 for details),
2241 // unbound Ctrl+Alt key sequences are allowed.
2242 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2243 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2244 && !(state & AltModifier && state & ControlModifier)
2248 if (current_view_) {
2249 current_view_->message(_("Unknown function."));
2250 current_view_->restartCaret();
2255 // Since all checks above were passed, we now really have text that
2256 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2257 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2259 LYXERR(Debug::KEY, "isText() is true, inserting.");
2260 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2262 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2263 if (current_view_) {
2264 current_view_->message(_("Unknown function."));
2265 current_view_->restartCaret();
2271 if (func.action() == LFUN_SELF_INSERT) {
2272 if (encoded_last_key != 0) {
2273 docstring const arg(1, encoded_last_key);
2274 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2275 FuncRequest::KEYBOARD));
2276 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2279 processFuncRequest(func);
2283 void GuiApplication::processFuncRequest(FuncRequest const & func)
2285 lyx::dispatch(func);
2289 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2291 addToFuncRequestQueue(func);
2292 processFuncRequestQueueAsync();
2296 void GuiApplication::processFuncRequestQueue()
2298 while (!d->func_request_queue_.empty()) {
2299 // take the item from the stack _before_ processing the
2300 // request in order to avoid race conditions from nested
2301 // or parallel requests (see #10406)
2302 FuncRequest const fr(d->func_request_queue_.front());
2303 d->func_request_queue_.pop();
2304 processFuncRequest(fr);
2309 void GuiApplication::processFuncRequestQueueAsync()
2311 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2315 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2317 d->func_request_queue_.push(func);
2321 void GuiApplication::resetGui()
2323 // Set the language defined by the user.
2327 if (!readUIFile(toqstr(lyxrc.ui_file)))
2328 // Gives some error box here.
2331 if (d->global_menubar_)
2332 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2334 QHash<int, GuiView *>::iterator it;
2335 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2338 gv->setLayoutDirection(layoutDirection());
2342 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2346 void GuiApplication::createView(int view_id)
2348 createView(QString(), true, view_id);
2352 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2355 // release the keyboard which might have been grabed by the global
2356 // menubar on Mac to catch shortcuts even without any GuiView.
2357 if (d->global_menubar_)
2358 d->global_menubar_->releaseKeyboard();
2362 while (d->views_.find(id) != d->views_.end())
2365 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2366 GuiView * view = new GuiView(id);
2367 // `view' is the new current_view_. Tell coverity that is is not 0.
2368 LATTEST(current_view_);
2370 d->views_[id] = view;
2374 setActiveWindow(view);
2377 if (!geometry_arg.isEmpty()) {
2378 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2382 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2383 re.indexIn(geometry_arg);
2384 w = re.cap(1).toInt();
2385 h = re.cap(2).toInt();
2386 x = re.cap(3).toInt();
2387 y = re.cap(4).toInt();
2388 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2389 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2390 // Set initial geometry such that we can get the frame size.
2391 view->setGeometry(x, y, w, h);
2392 int framewidth = view->geometry().x() - view->x();
2393 int titleheight = view->geometry().y() - view->y();
2394 // Negative displacements must be interpreted as distances
2395 // from the right or bottom screen borders.
2396 if (sx == '-' || sy == '-') {
2397 QRect rec = QApplication::desktop()->screenGeometry();
2399 x += rec.width() - w - framewidth;
2401 y += rec.height() - h - titleheight;
2402 view->setGeometry(x, y, w, h);
2404 // Make sure that the left and top frame borders are visible.
2405 if (view->x() < 0 || view->y() < 0) {
2410 view->setGeometry(x, y, w, h);
2418 bool GuiApplication::unhide(Buffer * buf)
2422 currentView()->setBuffer(buf, false);
2427 Clipboard & GuiApplication::clipboard()
2429 return d->clipboard_;
2433 Selection & GuiApplication::selection()
2435 return d->selection_;
2439 FontLoader & GuiApplication::fontLoader()
2441 return d->font_loader_;
2445 Toolbars const & GuiApplication::toolbars() const
2447 return d->toolbars_;
2451 Toolbars & GuiApplication::toolbars()
2453 return d->toolbars_;
2457 Menus const & GuiApplication::menus() const
2463 Menus & GuiApplication::menus()
2469 QList<int> GuiApplication::viewIds() const
2471 return d->views_.keys();
2475 ColorCache & GuiApplication::colorCache()
2477 return d->color_cache_;
2481 int GuiApplication::exec()
2483 // asynchronously handle batch commands. This event will be in
2484 // the event queue in front of other asynchronous events. Hence,
2485 // we can assume in the latter that the gui is setup already.
2486 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2488 return QApplication::exec();
2492 void GuiApplication::exit(int status)
2494 QApplication::exit(status);
2498 void GuiApplication::setGuiLanguage()
2502 // install translation file for Qt built-in dialogs
2503 QString const language_name = QString("qt_") + theLocale.name();
2504 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2505 // Short-named translator can be loaded from a long name, but not the
2506 // opposite. Therefore, long name should be used without truncation.
2507 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2508 if (!d->qt_trans_.load(language_name,
2509 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2510 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2513 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2517 switch (theLocale.language()) {
2518 case QLocale::Arabic :
2519 case QLocale::Hebrew :
2520 case QLocale::Persian :
2521 case QLocale::Urdu :
2522 setLayoutDirection(Qt::RightToLeft);
2525 setLayoutDirection(Qt::LeftToRight);
2530 void GuiApplication::execBatchCommands()
2535 if (!readUIFile(toqstr(lyxrc.ui_file)))
2536 // Gives some error box here.
2540 #if QT_VERSION > 0x040600
2541 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2543 #if QT_VERSION > 0x050100
2544 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2546 // Create the global default menubar which is shown for the dialogs
2547 // and if no GuiView is visible.
2548 // This must be done after the session was recovered to know the "last files".
2549 d->global_menubar_ = new QMenuBar(0);
2550 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2553 lyx::execBatchCommands();
2557 QAbstractItemModel * GuiApplication::languageModel()
2559 if (d->language_model_)
2560 return d->language_model_;
2562 QStandardItemModel * lang_model = new QStandardItemModel(this);
2563 lang_model->insertColumns(0, 3);
2564 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2565 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2566 Languages::const_iterator it = lyx::languages.begin();
2567 Languages::const_iterator end = lyx::languages.end();
2568 for (; it != end; ++it) {
2569 int current_row = lang_model->rowCount();
2570 lang_model->insertRows(current_row, 1);
2571 QModelIndex pl_item = lang_model->index(current_row, 0);
2572 QModelIndex sp_item = lang_model->index(current_row, 1);
2573 QModelIndex th_item = lang_model->index(current_row, 2);
2574 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2575 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2576 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2577 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2578 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2579 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2580 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2581 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2582 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2583 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2585 d->language_model_ = new QSortFilterProxyModel(this);
2586 d->language_model_->setSourceModel(lang_model);
2587 d->language_model_->setSortLocaleAware(true);
2588 return d->language_model_;
2592 void GuiApplication::restoreGuiSession()
2594 if (!lyxrc.load_session)
2597 Session & session = theSession();
2598 LastOpenedSection::LastOpened const & lastopened =
2599 session.lastOpened().getfiles();
2601 validateCurrentView();
2603 FileName active_file;
2604 // do not add to the lastfile list since these files are restored from
2605 // last session, and should be already there (regular files), or should
2606 // not be added at all (help files).
2607 for (size_t i = 0; i < lastopened.size(); ++i) {
2608 FileName const & file_name = lastopened[i].file_name;
2609 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2610 && current_view_->documentBufferView() != 0)) {
2611 boost::crc_32_type crc;
2612 string const & fname = file_name.absFileName();
2613 crc = for_each(fname.begin(), fname.end(), crc);
2614 createView(crc.checksum());
2616 current_view_->loadDocument(file_name, false);
2618 if (lastopened[i].active)
2619 active_file = file_name;
2622 // Restore last active buffer
2623 Buffer * buffer = theBufferList().getBuffer(active_file);
2624 if (buffer && current_view_)
2625 current_view_->setBuffer(buffer);
2627 // clear this list to save a few bytes of RAM
2628 session.lastOpened().clear();
2632 QString const GuiApplication::romanFontName()
2635 font.setStyleHint(QFont::Serif);
2636 font.setFamily("serif");
2638 return QFontInfo(font).family();
2642 QString const GuiApplication::sansFontName()
2645 font.setStyleHint(QFont::SansSerif);
2646 font.setFamily("sans");
2648 return QFontInfo(font).family();
2652 QString const GuiApplication::typewriterFontName()
2654 return QFontInfo(typewriterSystemFont()).family();
2659 // We cannot use QFont::fixedPitch() because it doesn't
2660 // return the fact but only if it is requested.
2661 static bool isFixedPitch(const QFont & font) {
2662 const QFontInfo fi(font);
2663 return fi.fixedPitch();
2668 QFont const GuiApplication::typewriterSystemFont()
2670 #if QT_VERSION >= 0x050200
2671 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2673 QFont font("monospace");
2675 if (!isFixedPitch(font)) {
2676 // try to enforce a real monospaced font
2677 font.setStyleHint(QFont::Monospace);
2678 if (!isFixedPitch(font)) {
2679 font.setStyleHint(QFont::TypeWriter);
2680 if (!isFixedPitch(font)) font.setFamily("courier");
2684 // On a Mac the result is too small and it's not practical to
2685 // rely on Qtconfig utility to change the system settings of Qt.
2686 font.setPointSize(12);
2692 void GuiApplication::handleRegularEvents()
2694 ForkedCallsController::handleCompletedProcesses();
2698 bool GuiApplication::event(QEvent * e)
2701 case QEvent::FileOpen: {
2702 // Open a file; this happens only on Mac OS X for now.
2704 // We do this asynchronously because on startup the batch
2705 // commands are not executed here yet and the gui is not ready
2707 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2708 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2709 processFuncRequestAsync(fr);
2714 return QApplication::event(e);
2719 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2722 return QApplication::notify(receiver, event);
2724 catch (ExceptionMessage const & e) {
2726 case ErrorException:
2728 setQuitOnLastWindowClosed(false);
2730 Alert::error(e.title_, e.details_);
2732 // Properly crash in debug mode in order to get a useful backtrace.
2735 // In release mode, try to exit gracefully.
2737 // FIXME: GCC 7 thinks we can fall through here. Can we?
2739 case BufferException: {
2740 if (!current_view_ || !current_view_->documentBufferView())
2742 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2743 docstring details = e.details_ + '\n';
2744 details += buf->emergencyWrite();
2745 theBufferList().release(buf);
2746 details += "\n" + _("The current document was closed.");
2747 Alert::error(e.title_, details);
2750 case WarningException:
2751 Alert::warning(e.title_, e.details_);
2755 catch (exception const & e) {
2756 docstring s = _("LyX has caught an exception, it will now "
2757 "attempt to save all unsaved documents and exit."
2759 s += from_ascii(e.what());
2760 Alert::error(_("Software exception Detected"), s);
2764 docstring s = _("LyX has caught some really weird exception, it will "
2765 "now attempt to save all unsaved documents and exit.");
2766 Alert::error(_("Software exception Detected"), s);
2774 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2776 QColor const & qcol = d->color_cache_.get(col);
2777 if (!qcol.isValid()) {
2783 rgbcol.r = qcol.red();
2784 rgbcol.g = qcol.green();
2785 rgbcol.b = qcol.blue();
2790 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2792 QColor const qcol(lcolor.getX11Name(col).c_str());
2793 if (!qcol.isValid()) {
2799 rgbcol.r = qcol.red();
2800 rgbcol.g = qcol.green();
2801 rgbcol.b = qcol.blue();
2806 string const GuiApplication::hexName(ColorCode col)
2808 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2812 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2814 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2815 d->socket_notifiers_[fd] = sn;
2816 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2820 void GuiApplication::socketDataReceived(int fd)
2822 d->socket_notifiers_[fd]->func_();
2826 void GuiApplication::unregisterSocketCallback(int fd)
2828 d->socket_notifiers_.take(fd)->setEnabled(false);
2832 void GuiApplication::commitData(QSessionManager & sm)
2834 /** The implementation is required to avoid an application exit
2835 ** when session state save is triggered by session manager.
2836 ** The default implementation sends a close event to all
2837 ** visible top level widgets when session managment allows
2839 ** We are changing that to check the state of each buffer in all
2840 ** views and ask the users what to do if buffers are dirty.
2841 ** Furthermore, we save the session state.
2842 ** We do NOT close the views here since the user still can cancel
2843 ** the logout process (see #9277); also, this would hide LyX from
2844 ** an OSes own session handling (application restoration).
2846 #ifdef QT_NO_SESSIONMANAGER
2848 #warning Qt is compiled without session manager
2850 #pragma message("warning: Qt is compiled without session manager")
2854 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2862 void GuiApplication::unregisterView(GuiView * gv)
2864 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2865 d->views_.remove(gv->id());
2866 if (current_view_ == gv)
2872 bool GuiApplication::closeAllViews()
2874 if (d->views_.empty())
2877 // When a view/window was closed before without quitting LyX, there
2878 // are already entries in the lastOpened list.
2879 theSession().lastOpened().clear();
2881 QList<GuiView *> const views = d->views_.values();
2882 for (GuiView * view : views) {
2883 if (!view->closeScheduled())
2892 bool GuiApplication::prepareAllViewsForLogout()
2894 if (d->views_.empty())
2897 QList<GuiView *> const views = d->views_.values();
2898 for (GuiView * view : views) {
2899 if (!view->prepareAllBuffersForLogout())
2907 GuiView & GuiApplication::view(int id) const
2909 LAPPERR(d->views_.contains(id));
2910 return *d->views_.value(id);
2914 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2916 QList<GuiView *> const views = d->views_.values();
2917 for (GuiView * view : views)
2918 view->hideDialog(name, inset);
2922 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2924 Buffer const * buffer_ = 0;
2925 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2926 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2927 if (Buffer const * ptr = (*it)->updateInset(inset))
2934 bool GuiApplication::searchMenu(FuncRequest const & func,
2935 docstring_list & names) const
2937 return d->menus_.searchMenu(func, names);
2941 // Ensure that a file is read only once (prevents include loops)
2942 static QStringList uifiles;
2943 // store which ui files define Toolbars
2944 static QStringList toolbar_uifiles;
2947 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2958 LexerKeyword uitags[] = {
2959 { "format", ui_format },
2960 { "include", ui_include },
2961 { "menuset", ui_menuset },
2962 { "toolbars", ui_toolbars },
2963 { "toolbarset", ui_toolbarset }
2967 lex.setFile(ui_path);
2969 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2973 if (lyxerr.debugging(Debug::PARSER))
2974 lex.printTable(lyxerr);
2977 // format before introduction of format tag
2978 unsigned int format = 0;
2979 while (lex.isOK()) {
2980 int const status = lex.lex();
2982 // we have to do this check here, outside the switch,
2983 // because otherwise we would start reading include files,
2984 // e.g., if the first tag we hit was an include tag.
2985 if (status == ui_format)
2987 format = lex.getInteger();
2991 // this will trigger unless the first tag we hit is a format
2992 // tag, with the right format.
2993 if (format != LFUN_FORMAT)
2994 return FormatMismatch;
2997 case Lexer::LEX_FEOF:
3002 QString const file = toqstr(lex.getString());
3003 bool const success = readUIFile(file, true);
3005 LYXERR0("Failed to read included file: " << fromqstr(file));
3012 d->menus_.read(lex);
3016 d->toolbars_.readToolbars(lex);
3020 d->toolbars_.readToolbarSettings(lex);
3021 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3025 if (!rtrim(lex.getString()).empty())
3026 lex.printError("LyX::ReadUIFile: "
3027 "Unknown menu tag: `$$Token'");
3029 LYXERR0("Error with status: " << status);
3035 return (error ? ReadError : ReadOK);
3039 bool GuiApplication::readUIFile(QString const & name, bool include)
3041 LYXERR(Debug::INIT, "About to read " << name << "...");
3045 ui_path = libFileSearch("ui", name, "inc");
3046 if (ui_path.empty())
3047 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3049 ui_path = libFileSearch("ui", name, "ui");
3052 if (ui_path.empty()) {
3053 static const QString defaultUIFile = "default";
3054 LYXERR(Debug::INIT, "Could not find " << name);
3056 Alert::warning(_("Could not find UI definition file"),
3057 bformat(_("Error while reading the included file\n%1$s\n"
3058 "Please check your installation."), qstring_to_ucs4(name)));
3061 if (name == defaultUIFile) {
3062 LYXERR(Debug::INIT, "Could not find default UI file!!");
3063 Alert::warning(_("Could not find default UI file"),
3064 _("LyX could not find the default UI file!\n"
3065 "Please check your installation."));
3068 Alert::warning(_("Could not find UI definition file"),
3069 bformat(_("Error while reading the configuration file\n%1$s\n"
3070 "Falling back to default.\n"
3071 "Please look under Tools>Preferences>User Interface and\n"
3072 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3073 return readUIFile(defaultUIFile, false);
3076 QString const uifile = toqstr(ui_path.absFileName());
3077 if (uifiles.contains(uifile)) {
3079 // We are reading again the top uifile so reset the safeguard:
3082 d->toolbars_.reset();
3084 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3085 << "Is this an include loop?");
3089 uifiles.push_back(uifile);
3091 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3093 ReturnValues retval = readUIFile(ui_path);
3095 if (retval == FormatMismatch) {
3096 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3097 TempFile tmp("convertXXXXXX.ui");
3098 FileName const tempfile = tmp.name();
3099 bool const success = prefs2prefs(ui_path, tempfile, true);
3101 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3102 " to format " << LFUN_FORMAT << ".");
3104 retval = readUIFile(tempfile);
3108 if (retval != ReadOK) {
3109 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3117 settings.beginGroup("ui_files");
3118 bool touched = false;
3119 for (int i = 0; i != uifiles.size(); ++i) {
3120 QFileInfo fi(uifiles[i]);
3121 QDateTime const date_value = fi.lastModified();
3122 QString const name_key = QString::number(i);
3123 // if an ui file which defines Toolbars has changed,
3124 // we have to reset the settings
3125 if (toolbar_uifiles.contains(uifiles[i])
3126 && (!settings.contains(name_key)
3127 || settings.value(name_key).toString() != uifiles[i]
3128 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3130 settings.setValue(name_key, uifiles[i]);
3131 settings.setValue(name_key + "/date", date_value);
3134 settings.endGroup();
3136 settings.remove("views");
3142 void GuiApplication::onLastWindowClosed()
3144 if (d->global_menubar_)
3145 d->global_menubar_->grabKeyboard();
3149 void GuiApplication::startLongOperation() {
3150 d->key_checker_.start();
3154 bool GuiApplication::longOperationCancelled() {
3155 return d->key_checker_.pressed();
3159 void GuiApplication::stopLongOperation() {
3160 d->key_checker_.stop();
3164 bool GuiApplication::longOperationStarted() {
3165 return d->key_checker_.started();
3169 ////////////////////////////////////////////////////////////////////////
3171 // X11 specific stuff goes here...
3174 bool GuiApplication::x11EventFilter(XEvent * xev)
3179 switch (xev->type) {
3180 case SelectionRequest: {
3181 if (xev->xselectionrequest.selection != XA_PRIMARY)
3183 LYXERR(Debug::SELECTION, "X requested selection.");
3184 BufferView * bv = current_view_->currentBufferView();
3186 docstring const sel = bv->requestSelection();
3188 d->selection_.put(sel);
3189 // Refresh the selection request timestamp.
3190 // We have to do this by ourselves as Qt seems
3191 // not doing that, maybe because of our
3192 // "persistent selection" implementation
3193 // (see comments in GuiSelection.cpp).
3194 XSelectionEvent nev;
3195 nev.type = SelectionNotify;
3196 nev.display = xev->xselectionrequest.display;
3197 nev.requestor = xev->xselectionrequest.requestor;
3198 nev.selection = xev->xselectionrequest.selection;
3199 nev.target = xev->xselectionrequest.target;
3200 nev.property = 0L; // None
3201 nev.time = CurrentTime;
3202 XSendEvent(QX11Info::display(),
3203 nev.requestor, False, 0,
3204 reinterpret_cast<XEvent *>(&nev));
3210 case SelectionClear: {
3211 if (xev->xselectionclear.selection != XA_PRIMARY)
3213 LYXERR(Debug::SELECTION, "Lost selection.");
3214 BufferView * bv = current_view_->currentBufferView();
3216 bv->clearSelection();
3222 #elif defined(QPA_XCB)
3223 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3224 void * message, long *)
3226 if (!current_view_ || eventType != "xcb_generic_event_t")
3229 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3231 switch (ev->response_type) {
3232 case XCB_SELECTION_REQUEST: {
3233 xcb_selection_request_event_t * srev =
3234 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3235 if (srev->selection != XCB_ATOM_PRIMARY)
3237 LYXERR(Debug::SELECTION, "X requested selection.");
3238 BufferView * bv = current_view_->currentBufferView();
3240 docstring const sel = bv->requestSelection();
3242 d->selection_.put(sel);
3243 #ifdef HAVE_QT5_X11_EXTRAS
3244 // Refresh the selection request timestamp.
3245 // We have to do this by ourselves as Qt seems
3246 // not doing that, maybe because of our
3247 // "persistent selection" implementation
3248 // (see comments in GuiSelection.cpp).
3249 xcb_selection_notify_event_t nev;
3250 nev.response_type = XCB_SELECTION_NOTIFY;
3251 nev.requestor = srev->requestor;
3252 nev.selection = srev->selection;
3253 nev.target = srev->target;
3254 nev.property = XCB_NONE;
3255 nev.time = XCB_CURRENT_TIME;
3256 xcb_connection_t * con = QX11Info::connection();
3257 xcb_send_event(con, 0, srev->requestor,
3258 XCB_EVENT_MASK_NO_EVENT,
3259 reinterpret_cast<char const *>(&nev));
3267 case XCB_SELECTION_CLEAR: {
3268 xcb_selection_clear_event_t * scev =
3269 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3270 if (scev->selection != XCB_ATOM_PRIMARY)
3272 LYXERR(Debug::SELECTION, "Lost selection.");
3273 BufferView * bv = current_view_->currentBufferView();
3275 bv->clearSelection();
3283 } // namespace frontend
3286 void hideDialogs(std::string const & name, Inset * inset)
3289 frontend::guiApp->hideDialogs(name, inset);
3293 ////////////////////////////////////////////////////////////////////
3297 ////////////////////////////////////////////////////////////////////
3299 frontend::FontLoader & theFontLoader()
3301 LAPPERR(frontend::guiApp);
3302 return frontend::guiApp->fontLoader();
3306 frontend::FontMetrics const & theFontMetrics(Font const & f)
3308 return theFontMetrics(f.fontInfo());
3312 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3314 LAPPERR(frontend::guiApp);
3315 return frontend::guiApp->fontLoader().metrics(f);
3319 ////////////////////////////////////////////////////////////////////
3323 ////////////////////////////////////////////////////////////////////
3325 frontend::Clipboard & theClipboard()
3327 LAPPERR(frontend::guiApp);
3328 return frontend::guiApp->clipboard();
3332 frontend::Selection & theSelection()
3334 LAPPERR(frontend::guiApp);
3335 return frontend::guiApp->selection();
3341 #include "moc_GuiApplication.cpp"