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>
106 #include <QSessionManager>
108 #include <QSocketNotifier>
109 #include <QSortFilterProxyModel>
110 #include <QStandardItemModel>
112 #include <QTranslator>
113 #include <QThreadPool>
117 #include <X11/Xatom.h>
118 #include <X11/Xlib.h>
122 #elif defined(QPA_XCB)
124 #ifdef HAVE_QT5_X11_EXTRAS
125 #include <QtX11Extras/QX11Info>
129 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
130 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
131 #if (QT_VERSION < 0x050000)
132 #include <QWindowsMime>
133 #define QWINDOWSMIME QWindowsMime
136 #define QWINDOWSMIME QWinMime
146 #include <QMacPasteboardMime>
149 #include <boost/crc.hpp>
156 using namespace lyx::support;
159 static void initializeResources()
161 static bool initialized = false;
163 Q_INIT_RESOURCE(Resources);
171 frontend::Application * createApplication(int & argc, char * argv[])
173 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
174 // prune -geometry argument(s) by shifting
175 // the following ones 2 places down.
176 for (int i = 0 ; i < argc ; ++i) {
177 if (strcmp(argv[i], "-geometry") == 0) {
178 int const remove = (i+1) < argc ? 2 : 1;
180 for (int j = i; j < argc; ++j)
181 argv[j] = argv[j + remove];
187 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
188 // On Windows, allow bringing the LyX window to top
189 AllowSetForegroundWindow(ASFW_ANY);
192 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
193 // I'd rather do that in the constructor, but I do not think that
194 // the palette is accessible there.
195 guiApp->colorCache().setPalette(guiApp->palette());
204 if (lyxrc.gui_language == "auto") {
205 theLocale = QLocale::system();
206 code = fromqstr(theLocale.name());
208 Language const * l = languages.getLanguage(lyxrc.gui_language);
209 code = l ? l->code() : "C";
210 theLocale = QLocale(toqstr(code));
212 // Qt tries to outsmart us and transforms en_US to C.
213 Messages::guiLanguage((code == "C") ? "en_US" : code);
214 QLocale::setDefault(theLocale);
215 setlocale(LC_NUMERIC, "C");
222 /// Return the list of loadable formats.
223 vector<string> loadableImageFormats()
227 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
229 LYXERR(Debug::GRAPHICS,
230 "\nThe image loader can load the following directly:\n");
232 if (qt_formats.empty())
233 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
235 bool jpeg_found = false;
236 bool jpg_found = false;
237 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
239 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
241 string ext = ascii_lowercase((const char *) *it);
249 else if (ext == "jpg") {
254 else if (lyxrc.use_converter_cache &&
255 (ext == "svg" || ext == "svgz") &&
256 theConverters().isReachable("svg", "png"))
257 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
258 // the SVG as in the output. However we require that the converter
259 // cache is enabled since this is expensive. We also require that
260 // an explicit svg->png converter is defined, since the default
261 // converter could produce bad quality as well. This assumes that
262 // png can always be loaded.
271 ////////////////////////////////////////////////////////////////////////
273 // Icon loading support code
275 ////////////////////////////////////////////////////////////////////////
285 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
287 return lhs.key < rhs.key;
293 CompareKey(QString const & name) : name_(name) {}
294 bool operator()(ImgMap const & other) const { return other.key == name_; }
300 // this must be sorted alphabetically
301 // Upper case comes before lower case
302 // Please don't change the formatting, this list is parsed by
303 // development/tools/generate_symbols_images.py.
304 ImgMap sorted_img_map[] = {
305 { "Arrownot", "arrownot2"},
306 { "Arrowvert", "arrowvert2"},
307 { "Bowtie", "bowtie2" },
309 { "Bumpeq", "bumpeq2" },
310 { "CIRCLE", "circle3" },
312 { "CheckedBox", "checkedbox2" },
313 { "Circle", "circle2" },
314 { "Colonapprox", "colonapprox2" },
315 { "Coloneq", "coloneq2" },
316 { "Coloneqq", "coloneqq2" },
317 { "Colonsim", "colonsim2" },
319 { "DOWNarrow", "downarrow3" },
320 { "Delta", "delta2" },
321 { "Diamond", "diamond2" },
322 { "Doteq", "doteq2" },
323 { "Downarrow", "downarrow2" },
324 { "Eqcolon", "eqcolon2" },
325 { "Eqqcolon", "eqqcolon2" },
326 { "Gamma", "gamma2" },
328 { "LEFTCIRCLE", "leftcircle3" },
329 { "LEFTarrow", "leftarrow3" },
330 { "LEFTcircle", "leftcircle4" },
332 { "Lambda", "lambda2" },
334 { "Leftarrow", "leftarrow2" },
335 { "Leftcircle", "leftcircle2" },
336 { "Leftrightarrow", "leftrightarrow2" },
337 { "Longarrownot", "longarrownot2"},
338 { "Longleftarrow", "longleftarrow2" },
339 { "Longleftrightarrow", "longleftrightarrow2" },
340 { "Longmapsfrom", "longmapsfrom2"},
341 { "Longmapsto", "longmapsto2"},
342 { "Longrightarrow", "longrightarrow2" },
343 { "Mapsfrom", "mapsfrom2"},
344 { "Mapsfromchar", "mapsfromchar2"},
345 { "Mapsto", "mapsto2"},
346 { "Mapstochar", "mapstochar2"},
347 { "Omega", "omega2" },
352 { "RIGHTCIRCLE", "rightcircle3" },
353 { "RIGHTarrow", "rightarrow3" },
354 { "RIGHTcircle", "rightcircle4" },
356 { "Rightarrow", "rightarrow2" },
357 { "Rightcircle", "rightcircle2" },
358 { "Sigma", "sigma2" },
359 { "Square", "square2" },
360 { "Subset", "subset2" },
361 { "Supset", "supset2" },
362 { "Theta", "theta2" },
363 { "Thorn", "thorn2" },
364 { "UParrow", "uparrow3" },
365 { "Uparrow", "uparrow2" },
366 { "Updownarrow", "updownarrow2" },
367 { "Upsilon", "upsilon2" },
368 { "Vdash", "vdash3" },
373 { "lVert", "vert2" },
375 { "nLeftarrow", "nleftarrow2" },
376 { "nLeftrightarrow", "nleftrightarrow2" },
377 { "nRightarrow", "nrightarrow2" },
378 { "nVDash", "nvdash3" },
379 { "nVdash", "nvdash4" },
380 { "nvDash", "nvdash2" },
381 { "rVert", "vert2" },
383 { "textrm \\AA", "textrm_AA"},
384 { "textrm \\O", "textrm_O"},
385 { "vDash", "vdash2" },
386 { "varDelta", "vardelta2" },
387 { "varGamma", "vargamma2" },
388 { "varLambda", "varlambda2" },
389 { "varOmega", "varomega2" },
390 { "varPhi", "varphi2" },
391 { "varPi", "varpi2" },
392 { "varPsi", "varpsi2" },
393 { "varSigma", "varsigma2" },
394 { "varTheta", "vartheta2" },
395 { "varUpsilon", "varupsilon2" },
396 { "varXi", "varxi2" }
400 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
402 // This list specifies which system's theme icon is related to which lyx
403 // command. It was based on:
404 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
405 // this must be sorted alphabetically
406 // Upper case comes before lower case
407 ImgMap sorted_theme_icon_map[] = {
408 { "bookmark-goto 0", "go-jump" },
409 { "buffer-new", "document-new" },
410 { "buffer-write", "document-save" },
411 { "buffer-write-as", "document-save-as" },
412 { "buffer-zoom-in", "zoom-in" },
413 { "buffer-zoom-out", "zoom-out" },
414 { "copy", "edit-copy" },
415 { "cut", "edit-cut" },
416 { "depth-decrement", "format-indent-less" },
417 { "depth-increment", "format-indent-more" },
418 { "dialog-show spellchecker", "tools-check-spelling" },
419 { "dialog-show-new-inset graphics", "insert-image" },
420 { "dialog-toggle findreplaceadv", "edit-find-replace" },
421 { "file-open", "document-open" },
422 { "font-bold", "format-text-bold" },
423 { "font-ital", "format-text-italic" },
424 { "font-strikeout", "format-text-strikethrough" },
425 { "font-underline", "format-text-underline" },
426 { "lyx-quit", "application-exit" },
427 { "paste", "edit-paste" },
428 { "redo", "edit-redo" },
429 { "undo", "edit-undo" },
430 { "window-close", "window-close" },
431 { "window-new", "window-new" }
434 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
437 QString findImg(QString const & name)
439 ImgMap const * const begin = sorted_img_map;
440 ImgMap const * const end = begin + nr_sorted_img_map;
441 LATTEST(sorted(begin, end));
443 ImgMap const * const it = find_if(begin, end, CompareKey(name));
447 img_name = it->value;
450 img_name.replace('_', "underscore");
451 img_name.replace(' ', '_');
453 // This way we can have "math-delim { }" on the toolbar.
454 img_name.replace('(', "lparen");
455 img_name.replace(')', "rparen");
456 img_name.replace('[', "lbracket");
457 img_name.replace(']', "rbracket");
458 img_name.replace('{', "lbrace");
459 img_name.replace('}', "rbrace");
460 img_name.replace('|', "bars");
461 img_name.replace(',', "thinspace");
462 img_name.replace(':', "mediumspace");
463 img_name.replace(';', "thickspace");
464 img_name.replace('!', "negthinspace");
467 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
468 << "Looking for math icon called \"" << img_name << '"');
475 QString themeIconName(QString const & action)
477 ImgMap const * const begin = sorted_theme_icon_map;
478 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
479 LASSERT(sorted(begin, end), /**/);
481 ImgMap const * const it = find_if(begin, end, CompareKey(action));
489 QString iconName(FuncRequest const & f, bool unknown)
491 initializeResources();
495 switch (f.action()) {
496 case LFUN_MATH_INSERT:
497 if (!f.argument().empty()) {
499 name1 = findImg(toqstr(f.argument()).mid(1));
502 case LFUN_MATH_DELIM:
503 case LFUN_MATH_BIGDELIM:
505 name1 = findImg(toqstr(f.argument()));
509 name1 = toqstr(f.argument());
511 case LFUN_COMMAND_ALTERNATIVES: {
512 // use the first of the alternative commands
514 docstring dummy = split(f.argument(), firstcom, ';');
515 name1 = toqstr(firstcom);
516 name1.replace(' ', '_');
520 name2 = toqstr(lyxaction.getActionName(f.action()));
523 if (!f.argument().empty()) {
524 name1 = name2 + ' ' + toqstr(f.argument());
525 name1.replace(' ', '_');
526 name1.replace('\\', "backslash");
530 QStringList imagedirs;
531 imagedirs << "images/" << "images/ipa/";
532 search_mode mode = theGuiApp()->imageSearchMode();
533 for (int i = 0; i < imagedirs.size(); ++i) {
534 QString imagedir = imagedirs.at(i) + path;
535 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
537 return toqstr(fname.absFileName());
539 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
541 return toqstr(fname.absFileName());
544 path = ":/images/" + path;
547 LYXERR0("Directory " << path << " not found in resource!");
550 if (res.exists(name1 + ".svgz"))
551 return path + name1 + ".svgz";
552 else if (res.exists(name1 + ".png"))
553 return path + name1 + ".png";
555 if (res.exists(name2 + ".svgz"))
556 return path + name2 + ".svgz";
557 else if (res.exists(name2 + ".png"))
558 return path + name2 + ".png";
560 LYXERR(Debug::GUI, "Cannot find icon with filename "
561 << "\"" << name1 << ".{svgz,png}\""
563 << "\"" << name2 << ".{svgz,png}\""
565 << lyxaction.getActionName(f.action())
566 << '(' << to_utf8(f.argument()) << ")\"");
569 QString imagedir = "images/";
570 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
572 return toqstr(fname.absFileName());
573 return QString(":/images/unknown.svgz");
580 bool getPixmap(QPixmap & pixmap, QString const & path)
582 return pixmap.load(path);
586 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
588 QString imagedir = path;
589 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
590 QString fpath = toqstr(fname.absFileName());
591 QPixmap pixmap = QPixmap();
593 if (getPixmap(pixmap, fpath)) {
597 QStringList exts = ext.split(",");
598 fpath = ":/" + path + name + ".";
599 for (int i = 0; i < exts.size(); ++i) {
600 if (getPixmap(pixmap, fpath + exts.at(i))) {
605 bool const list = ext.contains(",");
606 LYXERR0("Cannot load pixmap \""
607 << path << name << "." << (list ? "{" : "") << ext
608 << (list ? "}" : "") << "\", please verify resource system!");
614 QIcon getIcon(FuncRequest const & f, bool unknown)
616 #if (QT_VERSION >= 0x040600)
617 if (lyxrc.use_system_theme_icons) {
618 // use the icons from system theme that are available
619 QString action = toqstr(lyxaction.getActionName(f.action()));
620 if (!f.argument().empty())
621 action += " " + toqstr(f.argument());
622 QString const theme_icon = themeIconName(action);
623 if (QIcon::hasThemeIcon(theme_icon)) {
624 QIcon const thmicn = QIcon::fromTheme(theme_icon);
625 if (!thmicn.isNull())
631 QString icon = iconName(f, unknown);
635 //LYXERR(Debug::GUI, "Found icon: " << icon);
636 QPixmap pixmap = QPixmap();
637 if (!getPixmap(pixmap,icon)) {
638 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
642 return QIcon(pixmap);
646 ////////////////////////////////////////////////////////////////////////
648 // LyX server support code.
650 ////////////////////////////////////////////////////////////////////////
652 class SocketNotifier : public QSocketNotifier
655 /// connect a connection notification from the LyXServerSocket
656 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
657 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
661 /// The callback function
662 Application::SocketCallback func_;
666 class GuiTranslator : public QTranslator
669 GuiTranslator(QObject * parent = nullptr)
670 : QTranslator(parent)
673 virtual QString translate(const char * /* context */,
674 const char *sourceText,
675 #if QT_VERSION >= 0x050000
676 const char * /* disambiguation */ = 0, int /* n */ = -1) const
678 const char * /*comment*/ = 0) const
681 // Here we declare the strings that need to be translated from Qt own GUI
682 // This is needed to include these strings to po files
688 // Already in po: "Cancel", "&Cancel"
689 _("Apply"); // Already in po: "&Apply"
690 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
692 docstring s = getGuiMessages().getIfFound(sourceText);
693 // This test should eventually be removed when translations are updated
695 LYXERR(Debug::LOCALE, "Missing translation for `"
696 << string(sourceText) << "'");
702 ////////////////////////////////////////////////////////////////////////
704 // Mac specific stuff goes here...
706 ////////////////////////////////////////////////////////////////////////
709 // QMacPasteboardMimeGraphics can only be compiled on Mac.
711 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
714 QMacPasteboardMimeGraphics()
715 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
718 QString convertorName() { return "Graphics"; }
720 QString flavorFor(QString const & mime)
722 LYXERR(Debug::ACTION, "flavorFor " << mime);
723 if (mime == pdfMimeType())
724 return QLatin1String("com.adobe.pdf");
728 QString mimeFor(QString flav)
730 LYXERR(Debug::ACTION, "mimeFor " << flav);
731 if (flav == QLatin1String("com.adobe.pdf"))
732 return pdfMimeType();
736 bool canConvert(QString const & mime, QString flav)
738 return mimeFor(flav) == mime;
741 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
745 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
749 QList<QByteArray> convertFromMime(QString const & /*mime*/,
750 QVariant data, QString /*flav*/)
752 QList<QByteArray> ret;
753 ret.append(data.toByteArray());
759 ///////////////////////////////////////////////////////////////
761 // You can find more platform specific stuff at the end of this file...
763 ///////////////////////////////////////////////////////////////
765 ////////////////////////////////////////////////////////////////////////
766 // Windows specific stuff goes here...
768 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
769 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
770 // QWindowsMimeMetafile can only be compiled on Windows.
772 static FORMATETC cfFromMime(QString const & mimetype)
775 if (mimetype == emfMimeType()) {
776 formatetc.cfFormat = CF_ENHMETAFILE;
777 formatetc.tymed = TYMED_ENHMF;
778 } else if (mimetype == wmfMimeType()) {
779 formatetc.cfFormat = CF_METAFILEPICT;
780 formatetc.tymed = TYMED_MFPICT;
783 formatetc.dwAspect = DVASPECT_CONTENT;
784 formatetc.lindex = -1;
789 class QWindowsMimeMetafile : public QWINDOWSMIME {
791 QWindowsMimeMetafile() {}
793 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
794 QMimeData const * /*mimedata*/) const
799 bool canConvertToMime(QString const & mimetype,
800 IDataObject * pDataObj) const
802 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
804 FORMATETC formatetc = cfFromMime(mimetype);
805 return pDataObj->QueryGetData(&formatetc) == S_OK;
808 bool convertFromMime(FORMATETC const & /*formatetc*/,
809 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
814 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
815 QVariant::Type /*preferredType*/) const
818 if (!canConvertToMime(mimetype, pDataObj))
821 FORMATETC formatetc = cfFromMime(mimetype);
823 if (pDataObj->GetData(&formatetc, &s) != S_OK)
827 if (s.tymed == TYMED_ENHMF) {
828 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
829 data.resize(dataSize);
830 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
831 (LPBYTE)data.data());
832 } else if (s.tymed == TYMED_MFPICT) {
833 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
834 data.resize(dataSize);
835 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
836 (LPBYTE)data.data());
839 ReleaseStgMedium(&s);
845 QVector<FORMATETC> formatsForMime(QString const & mimetype,
846 QMimeData const * /*mimedata*/) const
848 QVector<FORMATETC> formats;
849 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
850 formats += cfFromMime(mimetype);
854 QString mimeForFormat(FORMATETC const & formatetc) const
856 switch (formatetc.cfFormat) {
858 return emfMimeType();
859 case CF_METAFILEPICT:
860 return wmfMimeType();
870 /// Allows to check whether ESC was pressed during a long operation
871 class KeyChecker : public QObject {
876 KeyChecker() : pressed_(false), started_(false) {}
879 QCoreApplication::instance()->installEventFilter(this);
884 QCoreApplication::instance()->removeEventFilter(this);
888 QCoreApplication::processEvents();
891 bool started() const {
894 bool eventFilter(QObject *obj, QEvent *event) {
895 LYXERR(Debug::ACTION, "Event Type: " << event->type());
896 switch (event->type()) {
900 case QEvent::UpdateRequest:
901 case QEvent::CursorChange:
902 case QEvent::ActionChanged:
903 case QEvent::EnabledChange:
904 case QEvent::SockAct:
907 case QEvent::ToolTipChange:
908 case QEvent::LayoutRequest:
909 case QEvent::MetaCall:
910 return QObject::eventFilter(obj, event);
912 // FIXME Blocking all these events is a bad idea.
913 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
914 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
922 ////////////////////////////////////////////////////////////////////////
923 // GuiApplication::Private definition and implementation.
924 ////////////////////////////////////////////////////////////////////////
926 struct GuiApplication::Private
928 Private(): language_model_(0), meta_fake_bit(NoModifier),
931 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
932 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
933 /// WMF Mime handler for Windows clipboard.
934 wmf_mime_ = new QWindowsMimeMetafile;
937 initKeySequences(&theTopLevelKeymap());
940 void initKeySequences(KeyMap * kb)
942 keyseq = KeySequence(kb, kb);
943 cancel_meta_seq = KeySequence(kb, kb);
947 QSortFilterProxyModel * language_model_;
949 GuiClipboard clipboard_;
951 GuiSelection selection_;
953 FontLoader font_loader_;
955 ColorCache color_cache_;
956 /// the built-in Qt translation mechanism
957 QTranslator qt_trans_;
958 /// LyX gettext-based translation for Qt elements
959 GuiTranslator gui_trans_;
961 QHash<int, SocketNotifier *> socket_notifiers_;
965 /// The global instance
968 /// this timer is used for any regular events one wants to
969 /// perform. at present it is used to check if forked processes
971 QTimer general_timer_;
973 /// delayed FuncRequests
974 std::queue<FuncRequest> func_request_queue_;
979 KeySequence cancel_meta_seq;
981 KeyModifier meta_fake_bit;
983 /// The result of last dispatch action
984 DispatchResult dispatch_result_;
986 /// Multiple views container.
988 * Warning: This must not be a smart pointer as the destruction of the
989 * object is handled by Qt when the view is closed
990 * \sa Qt::WA_DeleteOnClose attribute.
992 QHash<int, GuiView *> views_;
994 /// Only used on mac.
995 QMenuBar * global_menubar_;
998 /// Linkback mime handler for MacOSX.
999 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1002 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1003 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1004 /// WMF Mime handler for Windows clipboard.
1005 QWindowsMimeMetafile * wmf_mime_;
1009 /// Allows to check whether ESC was pressed during a long operation
1010 KeyChecker key_checker_;
1014 GuiApplication * guiApp;
1016 GuiApplication::~GuiApplication()
1019 closeAllLinkBackLinks();
1025 GuiApplication::GuiApplication(int & argc, char ** argv)
1026 : QApplication(argc, argv), current_view_(0),
1027 d(new GuiApplication::Private)
1029 QString app_name = "LyX";
1030 QCoreApplication::setOrganizationName(app_name);
1031 QCoreApplication::setOrganizationDomain("lyx.org");
1032 QCoreApplication::setApplicationName(lyx_package);
1033 #if QT_VERSION >= 0x050000
1034 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1037 qsrand(QDateTime::currentDateTime().toTime_t());
1039 // Install LyX translator for missing Qt translations
1040 installTranslator(&d->gui_trans_);
1041 // Install Qt native translator for GUI elements.
1042 installTranslator(&d->qt_trans_);
1045 // Enable reception of XCB events.
1046 installNativeEventFilter(this);
1049 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1050 // lyxrc setting for this in order to let the application stay resident.
1051 // But then we need some kind of dock icon, at least on Windows.
1053 if (lyxrc.quit_on_last_window_closed)
1054 setQuitOnLastWindowClosed(false);
1057 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1058 // seems to be the default case for applications like LyX.
1059 setQuitOnLastWindowClosed(false);
1064 #if defined(Q_WS_X11) || defined(QPA_XCB)
1065 // doubleClickInterval() is 400 ms on X11 which is just too long.
1066 // On Windows and Mac OS X, the operating system's value is used.
1067 // On Microsoft Windows, calling this function sets the double
1068 // click interval for all applications. So we don't!
1069 QApplication::setDoubleClickInterval(300);
1072 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1074 // needs to be done before reading lyxrc
1076 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1080 // Initialize RC Fonts
1081 if (lyxrc.roman_font_name.empty())
1082 lyxrc.roman_font_name = fromqstr(romanFontName());
1084 if (lyxrc.sans_font_name.empty())
1085 lyxrc.sans_font_name = fromqstr(sansFontName());
1087 if (lyxrc.typewriter_font_name.empty())
1088 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1090 d->general_timer_.setInterval(500);
1091 connect(&d->general_timer_, SIGNAL(timeout()),
1092 this, SLOT(handleRegularEvents()));
1093 d->general_timer_.start();
1095 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1096 // This is clearly not enough in a time where we use threads for
1097 // document preview and/or export. 20 should be OK.
1098 QThreadPool::globalInstance()->setMaxThreadCount(20);
1100 // make sure tooltips are formatted
1101 installEventFilter(new ToolTipFormatter(this));
1105 GuiApplication * theGuiApp()
1107 return dynamic_cast<GuiApplication *>(theApp());
1111 double GuiApplication::pixelRatio() const
1113 #if QT_VERSION >= 0x050000
1114 return qt_scale_factor * devicePixelRatio();
1121 void GuiApplication::clearSession()
1128 docstring Application::iconName(FuncRequest const & f, bool unknown)
1130 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1134 docstring Application::mathIcon(docstring const & c)
1136 return qstring_to_ucs4(findImg(toqstr(c)));
1140 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1144 BufferView * bv = 0;
1145 BufferView * doc_bv = 0;
1147 if (cmd.action() == LFUN_NOACTION) {
1148 status.message(from_utf8(N_("Nothing to do")));
1149 status.setEnabled(false);
1152 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1153 status.setUnknown(true);
1154 status.message(from_utf8(N_("Unknown action")));
1155 status.setEnabled(false);
1158 // Does the GuiApplication know something?
1159 else if (getStatus(cmd, status)) { }
1161 // If we do not have a GuiView, then other functions are disabled
1162 else if (!current_view_)
1163 status.setEnabled(false);
1165 // Does the GuiView know something?
1166 else if (current_view_->getStatus(cmd, status)) { }
1168 // In LyX/Mac, when a dialog is open, the menus of the
1169 // application can still be accessed without giving focus to
1170 // the main window. In this case, we want to disable the menu
1171 // entries that are buffer or view-related.
1172 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1174 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1175 status.setEnabled(false);
1178 // If we do not have a BufferView, then other functions are disabled
1179 else if (!(bv = current_view_->currentBufferView()))
1180 status.setEnabled(false);
1182 // Does the current BufferView know something?
1183 else if (bv->getStatus(cmd, status)) { }
1185 // Does the current Buffer know something?
1186 else if (bv->buffer().getStatus(cmd, status)) { }
1188 // If we do not have a document BufferView, different from the
1189 // current BufferView, then other functions are disabled
1190 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1191 status.setEnabled(false);
1193 // Does the document Buffer know something?
1194 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1197 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1198 status.message(from_utf8(N_("Command not handled")));
1199 status.setEnabled(false);
1202 // the default error message if we disable the command
1203 if (!status.enabled() && status.message().empty())
1204 status.message(from_utf8(N_("Command disabled")));
1210 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1212 // I would really like to avoid having this switch and rather try to
1213 // encode this in the function itself.
1214 // -- And I'd rather let an inset decide which LFUNs it is willing
1215 // to handle (Andre')
1217 switch (cmd.action()) {
1219 // This could be used for the no-GUI version. The GUI version is handled in
1220 // GuiView::getStatus(). See above.
1222 case LFUN_BUFFER_WRITE:
1223 case LFUN_BUFFER_WRITE_AS: {
1224 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1225 enable = b && (b->isUnnamed() || !b->isClean());
1230 case LFUN_BOOKMARK_GOTO: {
1231 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1232 enable = theSession().bookmarks().isValid(num);
1236 case LFUN_BOOKMARK_CLEAR:
1237 enable = theSession().bookmarks().hasValid();
1240 // this one is difficult to get right. As a half-baked
1241 // solution, we consider only the first action of the sequence
1242 case LFUN_COMMAND_SEQUENCE: {
1243 // argument contains ';'-terminated commands
1244 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1245 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1246 func.setOrigin(cmd.origin());
1247 flag = getStatus(func);
1251 // we want to check if at least one of these is enabled
1252 case LFUN_COMMAND_ALTERNATIVES: {
1253 // argument contains ';'-terminated commands
1254 string arg = to_utf8(cmd.argument());
1255 while (!arg.empty()) {
1257 arg = split(arg, first, ';');
1258 FuncRequest func(lyxaction.lookupFunc(first));
1259 func.setOrigin(cmd.origin());
1260 flag = getStatus(func);
1261 // if this one is enabled, the whole thing is
1270 string name = to_utf8(cmd.argument());
1271 if (theTopLevelCmdDef().lock(name, func)) {
1272 func.setOrigin(cmd.origin());
1273 flag = getStatus(func);
1274 theTopLevelCmdDef().release(name);
1276 // catch recursion or unknown command
1277 // definition. all operations until the
1278 // recursion or unknown command definition
1279 // occurs are performed, so set the state to
1286 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1288 case LFUN_PREFERENCES_SAVE:
1289 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1290 case LFUN_DEBUG_LEVEL_SET:
1291 // these are handled in our dispatch()
1294 case LFUN_WINDOW_CLOSE:
1295 enable = d->views_.size() > 0;
1298 case LFUN_BUFFER_NEW:
1299 case LFUN_BUFFER_NEW_TEMPLATE:
1300 case LFUN_FILE_OPEN:
1301 case LFUN_HELP_OPEN:
1302 case LFUN_SCREEN_FONT_UPDATE:
1303 case LFUN_SET_COLOR:
1304 case LFUN_WINDOW_NEW:
1306 case LFUN_LYXRC_APPLY:
1307 case LFUN_COMMAND_PREFIX:
1309 case LFUN_META_PREFIX:
1310 case LFUN_RECONFIGURE:
1311 case LFUN_SERVER_GET_FILENAME:
1312 case LFUN_SERVER_NOTIFY:
1316 case LFUN_BUFFER_FORALL: {
1317 if (theBufferList().empty()) {
1318 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1319 flag.setEnabled(false);
1323 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1324 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1325 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1326 flag.setEnabled(false);
1331 case LFUN_DIALOG_SHOW: {
1332 string const name = cmd.getArg(0);
1333 return name == "aboutlyx"
1335 || name == "texinfo"
1336 || name == "progress"
1337 || name == "compare";
1345 flag.setEnabled(false);
1349 /// make a post-dispatch status message
1350 static docstring makeDispatchMessage(docstring const & msg,
1351 FuncRequest const & cmd)
1353 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1354 || cmd.origin() == FuncRequest::TOOLBAR
1355 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1357 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1358 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1362 docstring dispatch_msg = msg;
1363 if (!dispatch_msg.empty())
1364 dispatch_msg += ' ';
1366 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1368 bool argsadded = false;
1370 if (!cmd.argument().empty()) {
1371 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1372 comname += ' ' + cmd.argument();
1376 docstring const shortcuts = theTopLevelKeymap().
1377 printBindings(cmd, KeySequence::ForGui);
1379 if (!shortcuts.empty())
1380 comname += ": " + shortcuts;
1381 else if (!argsadded && !cmd.argument().empty())
1382 comname += ' ' + cmd.argument();
1384 if (!comname.empty()) {
1385 comname = rtrim(comname);
1386 dispatch_msg += '(' + rtrim(comname) + ')';
1388 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1389 return dispatch_msg;
1393 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1397 Buffer * buffer = 0;
1398 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1399 //setCurrentView(cmd.view_origin); //does not work
1401 dr.setMessage(_("Wrong focus!"));
1402 d->dispatch_result_ = dr;
1403 return d->dispatch_result_;
1405 if (current_view_ && current_view_->currentBufferView()) {
1406 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1407 buffer = ¤t_view_->currentBufferView()->buffer();
1410 dr.screenUpdate(Update::FitCursor);
1412 // This handles undo groups automagically
1413 UndoGroupHelper ugh(buffer);
1415 // redraw the screen at the end (first of the two drawing steps).
1416 // This is done unless explicitly requested otherwise.
1417 // This code is kept inside the undo group because updateBuffer
1418 // can create undo actions (see #11292)
1419 updateCurrentView(cmd, dr);
1422 d->dispatch_result_ = dr;
1423 return d->dispatch_result_;
1427 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1432 BufferView * bv = current_view_->currentBufferView();
1434 if (dr.needBufferUpdate()) {
1435 bv->cursor().clearBufferUpdate();
1436 bv->buffer().updateBuffer();
1437 } else if (dr.needChangesUpdate()) {
1438 // updateBuffer() already updates the change-tracking presence flag
1439 bv->buffer().updateChangesPresent();
1441 // BufferView::update() updates the ViewMetricsInfo and
1442 // also initializes the position cache for all insets in
1443 // (at least partially) visible top-level paragraphs.
1444 // We will redraw the screen only if needed.
1445 bv->processUpdateFlags(dr.screenUpdate());
1447 // Do we have a selection?
1448 theSelection().haveSelection(bv->cursor().selection());
1451 current_view_->restartCaret();
1453 if (dr.needMessageUpdate()) {
1454 // Some messages may already be translated, so we cannot use _()
1455 current_view_->message(makeDispatchMessage(
1456 translateIfPossible(dr.message()), cmd));
1461 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1462 bool switchToBuffer)
1464 if (!theSession().bookmarks().isValid(idx))
1466 BookmarksSection::Bookmark const & bm =
1467 theSession().bookmarks().bookmark(idx);
1468 LASSERT(!bm.filename.empty(), return);
1469 string const file = bm.filename.absFileName();
1470 // if the file is not opened, open it.
1471 if (!theBufferList().exists(bm.filename)) {
1473 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1477 // open may fail, so we need to test it again
1478 if (!theBufferList().exists(bm.filename))
1481 // bm can be changed when saving
1482 BookmarksSection::Bookmark tmp = bm;
1484 // Special case idx == 0 used for back-from-back jump navigation
1486 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1488 // if the current buffer is not that one, switch to it.
1489 BufferView * doc_bv = current_view_ ?
1490 current_view_->documentBufferView() : 0;
1491 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1492 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1493 if (switchToBuffer) {
1494 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1497 doc_bv = current_view_->documentBufferView();
1502 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1503 if (!doc_bv || !doc_bv->moveToPosition(
1504 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1507 Cursor & cur = doc_bv->cursor();
1508 if (old && cur != *old)
1509 notifyCursorLeavesOrEnters(*old, cur);
1515 // Cursor jump succeeded!
1516 pit_type new_pit = cur.pit();
1517 pos_type new_pos = cur.pos();
1518 int new_id = cur.paragraph().id();
1520 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1521 // see http://www.lyx.org/trac/ticket/3092
1522 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1523 || bm.top_id != new_id) {
1524 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1525 new_pit, new_pos, new_id);
1529 // This function runs "configure" and then rereads lyx.defaults to
1530 // reconfigure the automatic settings.
1531 void GuiApplication::reconfigure(string const & option)
1533 // emit message signal.
1535 current_view_->message(_("Running configure..."));
1537 // Run configure in user lyx directory
1538 string const lock_file = package().getConfigureLockName();
1539 int fd = fileLock(lock_file.c_str());
1540 int const ret = package().reconfigureUserLyXDir(option);
1541 // emit message signal.
1543 current_view_->message(_("Reloading configuration..."));
1544 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1545 // Re-read packages.lst
1546 LaTeXPackages::getAvailable();
1547 fileUnlock(fd, lock_file.c_str());
1550 Alert::information(_("System reconfiguration failed"),
1551 _("The system reconfiguration has failed.\n"
1552 "Default textclass is used but LyX may\n"
1553 "not be able to work properly.\n"
1554 "Please reconfigure again if needed."));
1556 Alert::information(_("System reconfigured"),
1557 _("The system has been reconfigured.\n"
1558 "You need to restart LyX to make use of any\n"
1559 "updated document class specifications."));
1562 void GuiApplication::validateCurrentView()
1564 if (!d->views_.empty() && !current_view_) {
1565 // currently at least one view exists but no view has the focus.
1566 // choose the last view to make it current.
1567 // a view without any open document is preferred.
1568 GuiView * candidate = 0;
1569 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1570 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1571 for (; it != end; ++it) {
1573 if (!candidate->documentBufferView())
1576 setCurrentView(candidate);
1580 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1582 string const argument = to_utf8(cmd.argument());
1583 FuncCode const action = cmd.action();
1585 LYXERR(Debug::ACTION, "cmd: " << cmd);
1587 // we have not done anything wrong yet.
1590 FuncStatus const flag = getStatus(cmd);
1591 if (!flag.enabled()) {
1592 // We cannot use this function here
1593 LYXERR(Debug::ACTION, "action "
1594 << lyxaction.getActionName(action)
1595 << " [" << action << "] is disabled at this location");
1596 dr.setMessage(flag.message());
1598 dr.dispatched(false);
1599 dr.screenUpdate(Update::None);
1600 dr.clearBufferUpdate();
1604 if (cmd.origin() == FuncRequest::LYXSERVER) {
1605 if (current_view_ && current_view_->currentBufferView())
1606 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1607 // we will also need to redraw the screen at the end
1608 dr.screenUpdate(Update::FitCursor);
1611 // Assumes that the action will be dispatched.
1612 dr.dispatched(true);
1614 switch (cmd.action()) {
1616 case LFUN_WINDOW_NEW:
1617 createView(toqstr(cmd.argument()));
1620 case LFUN_WINDOW_CLOSE:
1621 // update bookmark pit of the current buffer before window close
1622 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1623 gotoBookmark(i+1, false, false);
1624 // clear the last opened list, because
1625 // maybe this will end the session
1626 theSession().lastOpened().clear();
1627 // check for valid current_view_
1628 validateCurrentView();
1630 current_view_->closeScheduled();
1634 // quitting is triggered by the gui code
1635 // (leaving the event loop).
1637 current_view_->message(from_utf8(N_("Exiting.")));
1638 if (closeAllViews())
1642 case LFUN_SCREEN_FONT_UPDATE: {
1643 // handle the screen font changes.
1644 d->font_loader_.update();
1645 dr.screenUpdate(Update::Force | Update::FitCursor);
1649 case LFUN_BUFFER_NEW:
1650 validateCurrentView();
1652 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1653 createView(QString(), false); // keep hidden
1654 current_view_->newDocument(to_utf8(cmd.argument()), false);
1655 current_view_->show();
1656 setActiveWindow(current_view_);
1658 current_view_->newDocument(to_utf8(cmd.argument()), false);
1662 case LFUN_BUFFER_NEW_TEMPLATE:
1663 validateCurrentView();
1665 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1667 current_view_->newDocument(to_utf8(cmd.argument()), true);
1668 if (!current_view_->documentBufferView())
1669 current_view_->close();
1671 current_view_->newDocument(to_utf8(cmd.argument()), true);
1675 case LFUN_FILE_OPEN: {
1676 // FIXME: normally the code below is not needed, since getStatus makes sure that
1677 // current_view_ is not null.
1678 validateCurrentView();
1679 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1680 string const fname = to_utf8(cmd.argument());
1681 bool const is_open = FileName::isAbsolute(fname)
1682 && theBufferList().getBuffer(FileName(fname));
1684 || (!lyxrc.open_buffers_in_tabs
1685 && current_view_->documentBufferView() != 0
1687 // We want the ui session to be saved per document and not per
1688 // window number. The filename crc is a good enough identifier.
1689 boost::crc_32_type crc;
1690 crc = for_each(fname.begin(), fname.end(), crc);
1691 createView(crc.checksum());
1692 current_view_->openDocument(fname);
1693 if (!current_view_->documentBufferView())
1694 current_view_->close();
1695 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1696 current_view_->raise();
1697 current_view_->activateWindow();
1698 current_view_->showNormal();
1701 current_view_->openDocument(fname);
1702 if (cmd.origin() == FuncRequest::LYXSERVER) {
1703 current_view_->raise();
1704 current_view_->activateWindow();
1705 current_view_->showNormal();
1711 case LFUN_HELP_OPEN: {
1712 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1713 if (current_view_ == 0)
1715 string const arg = to_utf8(cmd.argument());
1717 current_view_->message(_("Missing argument"));
1720 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1722 fname = i18nLibFileSearch("examples", arg, "lyx");
1724 if (fname.empty()) {
1725 lyxerr << "LyX: unable to find documentation file `"
1726 << arg << "'. Bad installation?" << endl;
1729 current_view_->message(bformat(_("Opening help file %1$s..."),
1730 makeDisplayPath(fname.absFileName())));
1731 Buffer * buf = current_view_->loadDocument(fname, false);
1733 buf->setReadonly(!current_view_->develMode());
1737 case LFUN_SET_COLOR: {
1738 string const lyx_name = cmd.getArg(0);
1739 string const x11_name = cmd.getArg(1);
1740 if (lyx_name.empty() || x11_name.empty()) {
1742 current_view_->message(
1743 _("Syntax: set-color <lyx_name> <x11_name>"));
1748 // FIXME: The graphics cache no longer has a changeDisplay method.
1749 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1750 bool const graphicsbg_changed =
1751 lyx_name == graphicsbg && x11_name != graphicsbg;
1752 if (graphicsbg_changed)
1753 graphics::GCache::get().changeDisplay(true);
1756 if (!lcolor.setColor(lyx_name, x11_name)) {
1758 current_view_->message(
1759 bformat(_("Set-color \"%1$s\" failed "
1760 "- color is undefined or "
1761 "may not be redefined"),
1762 from_utf8(lyx_name)));
1765 // Make sure we don't keep old colors in cache.
1766 d->color_cache_.clear();
1767 // Update the current view
1768 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1772 case LFUN_LYXRC_APPLY: {
1773 // reset active key sequences, since the bindings
1774 // are updated (bug 6064)
1776 LyXRC const lyxrc_orig = lyxrc;
1778 istringstream ss(to_utf8(cmd.argument()));
1779 bool const success = lyxrc.read(ss);
1782 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1783 << "Unable to read lyxrc data"
1788 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1790 // If the request comes from the minibuffer, then we can't reset
1791 // the GUI, since that would destory the minibuffer itself and
1792 // cause a crash, since we are currently in one of the methods of
1793 // GuiCommandBuffer. See bug #8540.
1794 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1797 // FIXME Unfortunately, that leaves a bug here, since we cannot
1798 // reset the GUI in this case. If the changes to lyxrc affected the
1799 // UI, then, nothing would happen. This seems fairly unlikely, but
1800 // it definitely is a bug.
1802 dr.forceBufferUpdate();
1806 case LFUN_COMMAND_PREFIX:
1807 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1812 d->meta_fake_bit = NoModifier;
1813 GuiView * gv = currentView();
1814 if (gv && gv->currentBufferView())
1815 // cancel any selection
1816 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1817 dr.setMessage(from_ascii(N_("Cancel")));
1820 case LFUN_META_PREFIX:
1821 d->meta_fake_bit = AltModifier;
1822 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1825 // --- Menus -----------------------------------------------
1826 case LFUN_RECONFIGURE:
1827 // argument is any additional parameter to the configure.py command
1828 reconfigure(to_utf8(cmd.argument()));
1831 // --- lyxserver commands ----------------------------
1832 case LFUN_SERVER_GET_FILENAME: {
1833 if (current_view_ && current_view_->documentBufferView()) {
1834 docstring const fname = from_utf8(
1835 current_view_->documentBufferView()->buffer().absFileName());
1836 dr.setMessage(fname);
1837 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1839 dr.setMessage(docstring());
1840 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1845 case LFUN_SERVER_NOTIFY: {
1846 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1847 dr.setMessage(dispatch_buffer);
1848 theServer().notifyClient(to_utf8(dispatch_buffer));
1852 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1853 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1859 string rest = split(argument, countstr, ' ');
1860 int const count = convert<int>(countstr);
1861 // an arbitrary number to limit number of iterations
1862 int const max_iter = 10000;
1863 if (count > max_iter) {
1864 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1867 for (int i = 0; i < count; ++i) {
1868 FuncRequest lfun = lyxaction.lookupFunc(rest);
1869 lfun.allowAsync(false);
1876 case LFUN_COMMAND_SEQUENCE: {
1877 // argument contains ';'-terminated commands
1878 string arg = argument;
1879 // FIXME: this LFUN should also work without any view.
1880 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1881 ? &(current_view_->documentBufferView()->buffer()) : 0;
1882 // This handles undo groups automagically
1883 UndoGroupHelper ugh(buffer);
1884 while (!arg.empty()) {
1886 arg = split(arg, first, ';');
1887 FuncRequest func(lyxaction.lookupFunc(first));
1888 func.allowAsync(false);
1889 func.setOrigin(cmd.origin());
1895 case LFUN_BUFFER_FORALL: {
1896 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1897 funcToRun.allowAsync(false);
1899 map<Buffer *, GuiView *> views_lVisible;
1900 map<GuiView *, Buffer *> activeBuffers;
1902 QList<GuiView *> allViews = d->views_.values();
1904 // this for does not modify any buffer. It just collects info on local
1905 // visibility of buffers and on which buffer is active in each view.
1906 Buffer * const last = theBufferList().last();
1907 for(GuiView * view : allViews) {
1908 // all of the buffers might be locally hidden. That is, there is no
1910 if (!view || !view->currentBufferView())
1911 activeBuffers[view] = 0;
1913 activeBuffers[view] = &view->currentBufferView()->buffer();
1915 // find out if each is locally visible or locally hidden.
1916 // we don't use a for loop as the buffer list cycles.
1917 Buffer * b = theBufferList().first();
1919 bool const locallyVisible = view && view->workArea(*b);
1920 if (locallyVisible) {
1921 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1922 // only need to overwrite/add if we don't already know a buffer is globally
1923 // visible or we do know but we would prefer to dispatch LFUN from the
1924 // current view because of cursor position issues.
1925 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1926 views_lVisible[b] = view;
1930 b = theBufferList().next(b);
1934 GuiView * const homeView = currentView();
1935 Buffer * b = theBufferList().first();
1936 Buffer * nextBuf = 0;
1937 int numProcessed = 0;
1940 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1942 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1944 // first change to a view where b is locally visible, preferably current_view_.
1945 GuiView * const vLv = views_lVisible[b];
1947 lyx::dispatch(funcToRun);
1955 // put things back to how they were (if possible).
1956 for (GuiView * view : allViews) {
1957 Buffer * originalBuf = activeBuffers[view];
1958 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1959 if (theBufferList().isLoaded(originalBuf))
1960 view->setBuffer(originalBuf);
1962 homeView->setFocus();
1964 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1968 case LFUN_COMMAND_ALTERNATIVES: {
1969 // argument contains ';'-terminated commands
1970 string arg = argument;
1971 while (!arg.empty()) {
1973 arg = split(arg, first, ';');
1974 FuncRequest func(lyxaction.lookupFunc(first));
1975 func.setOrigin(cmd.origin());
1976 FuncStatus const stat = getStatus(func);
1977 if (stat.enabled()) {
1987 if (theTopLevelCmdDef().lock(argument, func)) {
1988 func.setOrigin(cmd.origin());
1990 theTopLevelCmdDef().release(argument);
1992 if (func.action() == LFUN_UNKNOWN_ACTION) {
1993 // unknown command definition
1994 lyxerr << "Warning: unknown command definition `"
1998 // recursion detected
1999 lyxerr << "Warning: Recursion in the command definition `"
2000 << argument << "' detected"
2007 case LFUN_PREFERENCES_SAVE:
2008 lyxrc.write(support::makeAbsPath("preferences",
2009 package().user_support().absFileName()), false);
2012 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2013 string const fname = addName(addPath(package().user_support().absFileName(),
2014 "templates/"), "defaults.lyx");
2015 Buffer defaults(fname);
2017 istringstream ss(argument);
2022 // We need to make sure that, after we recreat the DocumentClass,
2023 // which we do in readHeader, we apply it to the document itself.
2024 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2025 int const unknown_tokens = defaults.readHeader(lex);
2026 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2028 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2029 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2031 if (unknown_tokens != 0) {
2032 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2033 << unknown_tokens << " unknown token"
2034 << (unknown_tokens == 1 ? "" : "s")
2038 if (defaults.writeFile(FileName(defaults.absFileName())))
2039 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2040 makeDisplayPath(fname)));
2043 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2048 case LFUN_BOOKMARK_GOTO:
2049 // go to bookmark, open unopened file and switch to buffer if necessary
2050 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2051 dr.screenUpdate(Update::Force | Update::FitCursor);
2054 case LFUN_BOOKMARK_CLEAR:
2055 theSession().bookmarks().clear();
2058 case LFUN_DEBUG_LEVEL_SET:
2059 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2062 case LFUN_DIALOG_SHOW: {
2063 string const name = cmd.getArg(0);
2065 if ( name == "aboutlyx"
2067 || name == "texinfo"
2068 || name == "progress"
2069 || name == "compare")
2071 // work around: on Mac OS the application
2072 // is not terminated when closing the last view.
2073 // Create a new one to be able to dispatch the
2074 // LFUN_DIALOG_SHOW to this view.
2075 if (current_view_ == 0)
2081 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2084 current_view_->dispatch(cmd, dr);
2088 if (cmd.origin() == FuncRequest::LYXSERVER)
2089 updateCurrentView(cmd, dr);
2093 docstring GuiApplication::viewStatusMessage()
2095 // When meta-fake key is pressed, show the key sequence so far + "M-".
2096 if (d->meta_fake_bit != NoModifier)
2097 return d->keyseq.print(KeySequence::ForGui) + "M-";
2099 // Else, when a non-complete key sequence is pressed,
2100 // show the available options.
2101 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2102 return d->keyseq.printOptions(true);
2108 void GuiApplication::handleKeyFunc(FuncCode action)
2112 if (d->keyseq.length())
2114 GuiView * gv = currentView();
2115 LASSERT(gv && gv->currentBufferView(), return);
2116 BufferView * bv = gv->currentBufferView();
2117 bv->getIntl().getTransManager().deadkey(
2118 c, get_accent(action).accent, bv->cursor().innerText(),
2120 // Need to clear, in case the minibuffer calls these
2123 // copied verbatim from do_accent_char
2124 bv->cursor().resetAnchor();
2128 //Keep this in sync with GuiApplication::processKeySym below
2129 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2130 KeyModifier state) const
2132 // Do nothing if we have nothing
2133 if (!keysym.isOK() || keysym.isModifier())
2135 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2137 FuncRequest func = seq.addkey(keysym, state);
2138 // When not cancel or meta-fake, do the normal lookup.
2139 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2141 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2143 // Maybe user can only reach the key via holding down shift.
2144 // Let's see. But only if shift is the only modifier
2145 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2146 // If addkey looked up a command and did not find further commands then
2147 // seq has been reset at this point
2148 func = seq.addkey(keysym, NoModifier);
2150 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2151 << seq.print(KeySequence::Portable) << ']');
2152 return func.action() != LFUN_UNKNOWN_ACTION;
2156 //Keep this in sync with GuiApplication::queryKeySym above
2157 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2159 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2161 // Do nothing if we have nothing (JMarc)
2162 if (!keysym.isOK() || keysym.isModifier()) {
2164 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2166 current_view_->restartCaret();
2170 char_type encoded_last_key = keysym.getUCSEncoded();
2172 // Do a one-deep top-level lookup for
2173 // cancel and meta-fake keys. RVDK_PATCH_5
2174 d->cancel_meta_seq.reset();
2176 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2177 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2179 // When not cancel or meta-fake, do the normal lookup.
2180 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2181 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2182 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2183 // remove Caps Lock and Mod2 as a modifiers
2184 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2185 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2188 // Dont remove this unless you know what you are doing.
2189 d->meta_fake_bit = NoModifier;
2191 // Can this happen now ?
2192 if (func.action() == LFUN_NOACTION)
2193 func = FuncRequest(LFUN_COMMAND_PREFIX);
2195 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2196 << d->keyseq.print(KeySequence::Portable) << ']');
2198 // already here we know if it any point in going further
2199 // why not return already here if action == -1 and
2200 // num_bytes == 0? (Lgb)
2202 if (d->keyseq.length() > 1 && current_view_)
2203 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2206 // Maybe user can only reach the key via holding down shift.
2207 // Let's see. But only if shift is the only modifier
2208 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2209 LYXERR(Debug::KEY, "Trying without shift");
2210 // If addkey looked up a command and did not find further commands then
2211 // seq has been reset at this point
2212 func = d->keyseq.addkey(keysym, NoModifier);
2213 LYXERR(Debug::KEY, "Action now " << func.action());
2216 if (func.action() == LFUN_UNKNOWN_ACTION) {
2217 // We didn't match any of the key sequences.
2218 // See if it's normal insertable text not already
2219 // covered by a binding
2220 if (keysym.isText() && d->keyseq.length() == 1) {
2221 // Non-printable characters (such as ASCII control characters)
2222 // must not be inserted (#5704)
2223 if (!isPrintable(encoded_last_key)) {
2224 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2226 current_view_->restartCaret();
2229 // The following modifier check is not needed on Mac.
2230 // The keysym is either not text or it is different
2231 // from the non-modifier keysym. See #9875 for the
2232 // broken alt-modifier effect of having this code active.
2233 #if !defined(Q_OS_MAC)
2234 // If a non-Shift Modifier is used we have a non-bound key sequence
2235 // (such as Alt+j = j). This should be omitted (#5575).
2236 // On Windows, AltModifier and ControlModifier are both
2237 // set when AltGr is pressed. Therefore, in order to not
2238 // break AltGr-bound symbols (see #5575 for details),
2239 // unbound Ctrl+Alt key sequences are allowed.
2240 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2241 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2242 && !(state & AltModifier && state & ControlModifier)
2246 if (current_view_) {
2247 current_view_->message(_("Unknown function."));
2248 current_view_->restartCaret();
2253 // Since all checks above were passed, we now really have text that
2254 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2255 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2257 LYXERR(Debug::KEY, "isText() is true, inserting.");
2258 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2260 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2261 if (current_view_) {
2262 current_view_->message(_("Unknown function."));
2263 current_view_->restartCaret();
2269 if (func.action() == LFUN_SELF_INSERT) {
2270 if (encoded_last_key != 0) {
2271 docstring const arg(1, encoded_last_key);
2272 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2273 FuncRequest::KEYBOARD));
2274 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2277 processFuncRequest(func);
2281 void GuiApplication::processFuncRequest(FuncRequest const & func)
2283 lyx::dispatch(func);
2287 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2289 addToFuncRequestQueue(func);
2290 processFuncRequestQueueAsync();
2294 void GuiApplication::processFuncRequestQueue()
2296 while (!d->func_request_queue_.empty()) {
2297 // take the item from the stack _before_ processing the
2298 // request in order to avoid race conditions from nested
2299 // or parallel requests (see #10406)
2300 FuncRequest const fr(d->func_request_queue_.front());
2301 d->func_request_queue_.pop();
2302 processFuncRequest(fr);
2307 void GuiApplication::processFuncRequestQueueAsync()
2309 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2313 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2315 d->func_request_queue_.push(func);
2319 void GuiApplication::resetGui()
2321 // Set the language defined by the user.
2325 if (!readUIFile(toqstr(lyxrc.ui_file)))
2326 // Gives some error box here.
2329 if (d->global_menubar_)
2330 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2332 QHash<int, GuiView *>::iterator it;
2333 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2336 gv->setLayoutDirection(layoutDirection());
2340 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2344 void GuiApplication::createView(int view_id)
2346 createView(QString(), true, view_id);
2350 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2353 // release the keyboard which might have been grabed by the global
2354 // menubar on Mac to catch shortcuts even without any GuiView.
2355 if (d->global_menubar_)
2356 d->global_menubar_->releaseKeyboard();
2360 while (d->views_.find(id) != d->views_.end())
2363 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2364 GuiView * view = new GuiView(id);
2365 // `view' is the new current_view_. Tell coverity that is is not 0.
2366 LATTEST(current_view_);
2368 d->views_[id] = view;
2372 setActiveWindow(view);
2375 if (!geometry_arg.isEmpty()) {
2376 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2380 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2381 re.indexIn(geometry_arg);
2382 w = re.cap(1).toInt();
2383 h = re.cap(2).toInt();
2384 x = re.cap(3).toInt();
2385 y = re.cap(4).toInt();
2386 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2387 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2388 // Set initial geometry such that we can get the frame size.
2389 view->setGeometry(x, y, w, h);
2390 int framewidth = view->geometry().x() - view->x();
2391 int titleheight = view->geometry().y() - view->y();
2392 // Negative displacements must be interpreted as distances
2393 // from the right or bottom screen borders.
2394 if (sx == '-' || sy == '-') {
2395 QRect rec = QApplication::desktop()->screenGeometry();
2397 x += rec.width() - w - framewidth;
2399 y += rec.height() - h - titleheight;
2400 view->setGeometry(x, y, w, h);
2402 // Make sure that the left and top frame borders are visible.
2403 if (view->x() < 0 || view->y() < 0) {
2408 view->setGeometry(x, y, w, h);
2416 bool GuiApplication::unhide(Buffer * buf)
2420 currentView()->setBuffer(buf, false);
2425 Clipboard & GuiApplication::clipboard()
2427 return d->clipboard_;
2431 Selection & GuiApplication::selection()
2433 return d->selection_;
2437 FontLoader & GuiApplication::fontLoader()
2439 return d->font_loader_;
2443 Toolbars const & GuiApplication::toolbars() const
2445 return d->toolbars_;
2449 Toolbars & GuiApplication::toolbars()
2451 return d->toolbars_;
2455 Menus const & GuiApplication::menus() const
2461 Menus & GuiApplication::menus()
2467 QList<int> GuiApplication::viewIds() const
2469 return d->views_.keys();
2473 ColorCache & GuiApplication::colorCache()
2475 return d->color_cache_;
2479 int GuiApplication::exec()
2481 // asynchronously handle batch commands. This event will be in
2482 // the event queue in front of other asynchronous events. Hence,
2483 // we can assume in the latter that the gui is setup already.
2484 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2486 return QApplication::exec();
2490 void GuiApplication::exit(int status)
2492 QApplication::exit(status);
2496 void GuiApplication::setGuiLanguage()
2500 // install translation file for Qt built-in dialogs
2501 QString const language_name = QString("qt_") + theLocale.name();
2502 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2503 // Short-named translator can be loaded from a long name, but not the
2504 // opposite. Therefore, long name should be used without truncation.
2505 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2506 if (!d->qt_trans_.load(language_name,
2507 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2508 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2511 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2515 switch (theLocale.language()) {
2516 case QLocale::Arabic :
2517 case QLocale::Hebrew :
2518 case QLocale::Persian :
2519 case QLocale::Urdu :
2520 setLayoutDirection(Qt::RightToLeft);
2523 setLayoutDirection(Qt::LeftToRight);
2528 void GuiApplication::execBatchCommands()
2533 if (!readUIFile(toqstr(lyxrc.ui_file)))
2534 // Gives some error box here.
2538 #if QT_VERSION > 0x040600
2539 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2541 #if QT_VERSION > 0x050100
2542 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2544 // Create the global default menubar which is shown for the dialogs
2545 // and if no GuiView is visible.
2546 // This must be done after the session was recovered to know the "last files".
2547 d->global_menubar_ = new QMenuBar(0);
2548 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2551 lyx::execBatchCommands();
2555 QAbstractItemModel * GuiApplication::languageModel()
2557 if (d->language_model_)
2558 return d->language_model_;
2560 QStandardItemModel * lang_model = new QStandardItemModel(this);
2561 lang_model->insertColumns(0, 3);
2562 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2563 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2564 Languages::const_iterator it = lyx::languages.begin();
2565 Languages::const_iterator end = lyx::languages.end();
2566 for (; it != end; ++it) {
2567 int current_row = lang_model->rowCount();
2568 lang_model->insertRows(current_row, 1);
2569 QModelIndex pl_item = lang_model->index(current_row, 0);
2570 QModelIndex sp_item = lang_model->index(current_row, 1);
2571 QModelIndex th_item = lang_model->index(current_row, 2);
2572 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2573 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2574 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2575 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2576 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2577 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2578 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2579 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2580 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2581 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2583 d->language_model_ = new QSortFilterProxyModel(this);
2584 d->language_model_->setSourceModel(lang_model);
2585 d->language_model_->setSortLocaleAware(true);
2586 return d->language_model_;
2590 void GuiApplication::restoreGuiSession()
2592 if (!lyxrc.load_session)
2595 Session & session = theSession();
2596 LastOpenedSection::LastOpened const & lastopened =
2597 session.lastOpened().getfiles();
2599 validateCurrentView();
2601 FileName active_file;
2602 // do not add to the lastfile list since these files are restored from
2603 // last session, and should be already there (regular files), or should
2604 // not be added at all (help files).
2605 for (size_t i = 0; i < lastopened.size(); ++i) {
2606 FileName const & file_name = lastopened[i].file_name;
2607 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2608 && current_view_->documentBufferView() != 0)) {
2609 boost::crc_32_type crc;
2610 string const & fname = file_name.absFileName();
2611 crc = for_each(fname.begin(), fname.end(), crc);
2612 createView(crc.checksum());
2614 current_view_->loadDocument(file_name, false);
2616 if (lastopened[i].active)
2617 active_file = file_name;
2620 // Restore last active buffer
2621 Buffer * buffer = theBufferList().getBuffer(active_file);
2622 if (buffer && current_view_)
2623 current_view_->setBuffer(buffer);
2625 // clear this list to save a few bytes of RAM
2626 session.lastOpened().clear();
2630 QString const GuiApplication::romanFontName()
2633 font.setStyleHint(QFont::Serif);
2634 font.setFamily("serif");
2636 return QFontInfo(font).family();
2640 QString const GuiApplication::sansFontName()
2643 font.setStyleHint(QFont::SansSerif);
2644 font.setFamily("sans");
2646 return QFontInfo(font).family();
2650 QString const GuiApplication::typewriterFontName()
2652 return QFontInfo(typewriterSystemFont()).family();
2657 // We cannot use QFont::fixedPitch() because it doesn't
2658 // return the fact but only if it is requested.
2659 static bool isFixedPitch(const QFont & font) {
2660 const QFontInfo fi(font);
2661 return fi.fixedPitch();
2666 QFont const GuiApplication::typewriterSystemFont()
2668 #if QT_VERSION >= 0x050200
2669 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2671 QFont font("monospace");
2673 if (!isFixedPitch(font)) {
2674 // try to enforce a real monospaced font
2675 font.setStyleHint(QFont::Monospace);
2676 if (!isFixedPitch(font)) {
2677 font.setStyleHint(QFont::TypeWriter);
2678 if (!isFixedPitch(font)) font.setFamily("courier");
2682 // On a Mac the result is too small and it's not practical to
2683 // rely on Qtconfig utility to change the system settings of Qt.
2684 font.setPointSize(12);
2690 void GuiApplication::handleRegularEvents()
2692 ForkedCallsController::handleCompletedProcesses();
2696 bool GuiApplication::event(QEvent * e)
2699 case QEvent::FileOpen: {
2700 // Open a file; this happens only on Mac OS X for now.
2702 // We do this asynchronously because on startup the batch
2703 // commands are not executed here yet and the gui is not ready
2705 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2706 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2707 processFuncRequestAsync(fr);
2712 return QApplication::event(e);
2717 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2720 return QApplication::notify(receiver, event);
2722 catch (ExceptionMessage const & e) {
2724 case ErrorException:
2726 setQuitOnLastWindowClosed(false);
2728 Alert::error(e.title_, e.details_);
2730 // Properly crash in debug mode in order to get a useful backtrace.
2733 // In release mode, try to exit gracefully.
2735 // FIXME: GCC 7 thinks we can fall through here. Can we?
2737 case BufferException: {
2738 if (!current_view_ || !current_view_->documentBufferView())
2740 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2741 docstring details = e.details_ + '\n';
2742 details += buf->emergencyWrite();
2743 theBufferList().release(buf);
2744 details += "\n" + _("The current document was closed.");
2745 Alert::error(e.title_, details);
2748 case WarningException:
2749 Alert::warning(e.title_, e.details_);
2753 catch (exception const & e) {
2754 docstring s = _("LyX has caught an exception, it will now "
2755 "attempt to save all unsaved documents and exit."
2757 s += from_ascii(e.what());
2758 Alert::error(_("Software exception Detected"), s);
2762 docstring s = _("LyX has caught some really weird exception, it will "
2763 "now attempt to save all unsaved documents and exit.");
2764 Alert::error(_("Software exception Detected"), s);
2772 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2774 QColor const & qcol = d->color_cache_.get(col);
2775 if (!qcol.isValid()) {
2781 rgbcol.r = qcol.red();
2782 rgbcol.g = qcol.green();
2783 rgbcol.b = qcol.blue();
2788 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2790 QColor const qcol(lcolor.getX11Name(col).c_str());
2791 if (!qcol.isValid()) {
2797 rgbcol.r = qcol.red();
2798 rgbcol.g = qcol.green();
2799 rgbcol.b = qcol.blue();
2804 string const GuiApplication::hexName(ColorCode col)
2806 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2810 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2812 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2813 d->socket_notifiers_[fd] = sn;
2814 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2818 void GuiApplication::socketDataReceived(int fd)
2820 d->socket_notifiers_[fd]->func_();
2824 void GuiApplication::unregisterSocketCallback(int fd)
2826 d->socket_notifiers_.take(fd)->setEnabled(false);
2830 void GuiApplication::commitData(QSessionManager & sm)
2832 /** The implementation is required to avoid an application exit
2833 ** when session state save is triggered by session manager.
2834 ** The default implementation sends a close event to all
2835 ** visible top level widgets when session managment allows
2837 ** We are changing that to check the state of each buffer in all
2838 ** views and ask the users what to do if buffers are dirty.
2839 ** Furthermore, we save the session state.
2840 ** We do NOT close the views here since the user still can cancel
2841 ** the logout process (see #9277); also, this would hide LyX from
2842 ** an OSes own session handling (application restoration).
2844 #ifdef QT_NO_SESSIONMANAGER
2846 #warning Qt is compiled without session manager
2848 #pragma message("warning: Qt is compiled without session manager")
2852 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2860 void GuiApplication::unregisterView(GuiView * gv)
2862 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2863 d->views_.remove(gv->id());
2864 if (current_view_ == gv)
2870 bool GuiApplication::closeAllViews()
2872 if (d->views_.empty())
2875 // When a view/window was closed before without quitting LyX, there
2876 // are already entries in the lastOpened list.
2877 theSession().lastOpened().clear();
2879 QList<GuiView *> const views = d->views_.values();
2880 for (GuiView * view : views) {
2881 if (!view->closeScheduled())
2890 bool GuiApplication::prepareAllViewsForLogout()
2892 if (d->views_.empty())
2895 QList<GuiView *> const views = d->views_.values();
2896 for (GuiView * view : views) {
2897 if (!view->prepareAllBuffersForLogout())
2905 GuiView & GuiApplication::view(int id) const
2907 LAPPERR(d->views_.contains(id));
2908 return *d->views_.value(id);
2912 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2914 QList<GuiView *> const views = d->views_.values();
2915 for (GuiView * view : views)
2916 view->hideDialog(name, inset);
2920 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2922 Buffer const * buffer_ = 0;
2923 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2924 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2925 if (Buffer const * ptr = (*it)->updateInset(inset))
2932 bool GuiApplication::searchMenu(FuncRequest const & func,
2933 docstring_list & names) const
2935 BufferView * bv = 0;
2937 bv = current_view_->currentBufferView();
2938 return d->menus_.searchMenu(func, names, bv);
2942 bool GuiApplication::hasBufferView() const
2944 return (current_view_ && current_view_->currentBufferView());
2948 // Ensure that a file is read only once (prevents include loops)
2949 static QStringList uifiles;
2950 // store which ui files define Toolbars
2951 static QStringList toolbar_uifiles;
2954 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2965 LexerKeyword uitags[] = {
2966 { "format", ui_format },
2967 { "include", ui_include },
2968 { "menuset", ui_menuset },
2969 { "toolbars", ui_toolbars },
2970 { "toolbarset", ui_toolbarset }
2974 lex.setFile(ui_path);
2976 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2980 if (lyxerr.debugging(Debug::PARSER))
2981 lex.printTable(lyxerr);
2984 // format before introduction of format tag
2985 unsigned int format = 0;
2986 while (lex.isOK()) {
2987 int const status = lex.lex();
2989 // we have to do this check here, outside the switch,
2990 // because otherwise we would start reading include files,
2991 // e.g., if the first tag we hit was an include tag.
2992 if (status == ui_format)
2994 format = lex.getInteger();
2998 // this will trigger unless the first tag we hit is a format
2999 // tag, with the right format.
3000 if (format != LFUN_FORMAT)
3001 return FormatMismatch;
3004 case Lexer::LEX_FEOF:
3009 QString const file = toqstr(lex.getString());
3010 bool const success = readUIFile(file, true);
3012 LYXERR0("Failed to read included file: " << fromqstr(file));
3019 d->menus_.read(lex);
3023 d->toolbars_.readToolbars(lex);
3027 d->toolbars_.readToolbarSettings(lex);
3028 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3032 if (!rtrim(lex.getString()).empty())
3033 lex.printError("LyX::ReadUIFile: "
3034 "Unknown menu tag: `$$Token'");
3036 LYXERR0("Error with status: " << status);
3042 return (error ? ReadError : ReadOK);
3046 bool GuiApplication::readUIFile(QString const & name, bool include)
3048 LYXERR(Debug::INIT, "About to read " << name << "...");
3052 ui_path = libFileSearch("ui", name, "inc");
3053 if (ui_path.empty())
3054 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3056 ui_path = libFileSearch("ui", name, "ui");
3059 if (ui_path.empty()) {
3060 static const QString defaultUIFile = "default";
3061 LYXERR(Debug::INIT, "Could not find " << name);
3063 Alert::warning(_("Could not find UI definition file"),
3064 bformat(_("Error while reading the included file\n%1$s\n"
3065 "Please check your installation."), qstring_to_ucs4(name)));
3068 if (name == defaultUIFile) {
3069 LYXERR(Debug::INIT, "Could not find default UI file!!");
3070 Alert::warning(_("Could not find default UI file"),
3071 _("LyX could not find the default UI file!\n"
3072 "Please check your installation."));
3075 Alert::warning(_("Could not find UI definition file"),
3076 bformat(_("Error while reading the configuration file\n%1$s\n"
3077 "Falling back to default.\n"
3078 "Please look under Tools>Preferences>User Interface and\n"
3079 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3080 return readUIFile(defaultUIFile, false);
3083 QString const uifile = toqstr(ui_path.absFileName());
3084 if (uifiles.contains(uifile)) {
3086 // We are reading again the top uifile so reset the safeguard:
3089 d->toolbars_.reset();
3091 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3092 << "Is this an include loop?");
3096 uifiles.push_back(uifile);
3098 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3100 ReturnValues retval = readUIFile(ui_path);
3102 if (retval == FormatMismatch) {
3103 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3104 TempFile tmp("convertXXXXXX.ui");
3105 FileName const tempfile = tmp.name();
3106 bool const success = prefs2prefs(ui_path, tempfile, true);
3108 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3109 " to format " << LFUN_FORMAT << ".");
3111 retval = readUIFile(tempfile);
3115 if (retval != ReadOK) {
3116 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3124 settings.beginGroup("ui_files");
3125 bool touched = false;
3126 for (int i = 0; i != uifiles.size(); ++i) {
3127 QFileInfo fi(uifiles[i]);
3128 QDateTime const date_value = fi.lastModified();
3129 QString const name_key = QString::number(i);
3130 // if an ui file which defines Toolbars has changed,
3131 // we have to reset the settings
3132 if (toolbar_uifiles.contains(uifiles[i])
3133 && (!settings.contains(name_key)
3134 || settings.value(name_key).toString() != uifiles[i]
3135 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3137 settings.setValue(name_key, uifiles[i]);
3138 settings.setValue(name_key + "/date", date_value);
3141 settings.endGroup();
3143 settings.remove("views");
3149 void GuiApplication::onLastWindowClosed()
3151 if (d->global_menubar_)
3152 d->global_menubar_->grabKeyboard();
3156 void GuiApplication::startLongOperation() {
3157 d->key_checker_.start();
3161 bool GuiApplication::longOperationCancelled() {
3162 return d->key_checker_.pressed();
3166 void GuiApplication::stopLongOperation() {
3167 d->key_checker_.stop();
3171 bool GuiApplication::longOperationStarted() {
3172 return d->key_checker_.started();
3176 ////////////////////////////////////////////////////////////////////////
3178 // X11 specific stuff goes here...
3181 bool GuiApplication::x11EventFilter(XEvent * xev)
3186 switch (xev->type) {
3187 case SelectionRequest: {
3188 if (xev->xselectionrequest.selection != XA_PRIMARY)
3190 LYXERR(Debug::SELECTION, "X requested selection.");
3191 BufferView * bv = current_view_->currentBufferView();
3193 docstring const sel = bv->requestSelection();
3195 d->selection_.put(sel);
3196 // Refresh the selection request timestamp.
3197 // We have to do this by ourselves as Qt seems
3198 // not doing that, maybe because of our
3199 // "persistent selection" implementation
3200 // (see comments in GuiSelection.cpp).
3201 XSelectionEvent nev;
3202 nev.type = SelectionNotify;
3203 nev.display = xev->xselectionrequest.display;
3204 nev.requestor = xev->xselectionrequest.requestor;
3205 nev.selection = xev->xselectionrequest.selection;
3206 nev.target = xev->xselectionrequest.target;
3207 nev.property = 0L; // None
3208 nev.time = CurrentTime;
3209 XSendEvent(QX11Info::display(),
3210 nev.requestor, False, 0,
3211 reinterpret_cast<XEvent *>(&nev));
3217 case SelectionClear: {
3218 if (xev->xselectionclear.selection != XA_PRIMARY)
3220 LYXERR(Debug::SELECTION, "Lost selection.");
3221 BufferView * bv = current_view_->currentBufferView();
3223 bv->clearSelection();
3229 #elif defined(QPA_XCB)
3230 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3231 void * message, long *)
3233 if (!current_view_ || eventType != "xcb_generic_event_t")
3236 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3238 switch (ev->response_type) {
3239 case XCB_SELECTION_REQUEST: {
3240 xcb_selection_request_event_t * srev =
3241 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3242 if (srev->selection != XCB_ATOM_PRIMARY)
3244 LYXERR(Debug::SELECTION, "X requested selection.");
3245 BufferView * bv = current_view_->currentBufferView();
3247 docstring const sel = bv->requestSelection();
3249 d->selection_.put(sel);
3250 #ifdef HAVE_QT5_X11_EXTRAS
3251 // Refresh the selection request timestamp.
3252 // We have to do this by ourselves as Qt seems
3253 // not doing that, maybe because of our
3254 // "persistent selection" implementation
3255 // (see comments in GuiSelection.cpp).
3256 xcb_selection_notify_event_t nev;
3257 nev.response_type = XCB_SELECTION_NOTIFY;
3258 nev.requestor = srev->requestor;
3259 nev.selection = srev->selection;
3260 nev.target = srev->target;
3261 nev.property = XCB_NONE;
3262 nev.time = XCB_CURRENT_TIME;
3263 xcb_connection_t * con = QX11Info::connection();
3264 xcb_send_event(con, 0, srev->requestor,
3265 XCB_EVENT_MASK_NO_EVENT,
3266 reinterpret_cast<char const *>(&nev));
3274 case XCB_SELECTION_CLEAR: {
3275 xcb_selection_clear_event_t * scev =
3276 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3277 if (scev->selection != XCB_ATOM_PRIMARY)
3279 LYXERR(Debug::SELECTION, "Lost selection.");
3280 BufferView * bv = current_view_->currentBufferView();
3282 bv->clearSelection();
3290 } // namespace frontend
3293 void hideDialogs(std::string const & name, Inset * inset)
3296 frontend::guiApp->hideDialogs(name, inset);
3300 ////////////////////////////////////////////////////////////////////
3304 ////////////////////////////////////////////////////////////////////
3306 frontend::FontLoader & theFontLoader()
3308 LAPPERR(frontend::guiApp);
3309 return frontend::guiApp->fontLoader();
3313 frontend::FontMetrics const & theFontMetrics(Font const & f)
3315 return theFontMetrics(f.fontInfo());
3319 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3321 LAPPERR(frontend::guiApp);
3322 return frontend::guiApp->fontLoader().metrics(f);
3326 ////////////////////////////////////////////////////////////////////
3330 ////////////////////////////////////////////////////////////////////
3332 frontend::Clipboard & theClipboard()
3334 LAPPERR(frontend::guiApp);
3335 return frontend::guiApp->clipboard();
3339 frontend::Selection & theSelection()
3341 LAPPERR(frontend::guiApp);
3342 return frontend::guiApp->selection();
3348 #include "moc_GuiApplication.cpp"