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);
1417 // redraw the screen at the end (first of the two drawing steps).
1418 // This is done unless explicitly requested otherwise
1419 updateCurrentView(cmd, dr);
1420 d->dispatch_result_ = dr;
1421 return d->dispatch_result_;
1425 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1430 BufferView * bv = current_view_->currentBufferView();
1432 if (dr.needBufferUpdate()) {
1433 bv->cursor().clearBufferUpdate();
1434 bv->buffer().updateBuffer();
1435 } else if (dr.needChangesUpdate()) {
1436 // updateBuffer() already updates the change-tracking presence flag
1437 bv->buffer().updateChangesPresent();
1439 // BufferView::update() updates the ViewMetricsInfo and
1440 // also initializes the position cache for all insets in
1441 // (at least partially) visible top-level paragraphs.
1442 // We will redraw the screen only if needed.
1443 bv->processUpdateFlags(dr.screenUpdate());
1445 // Do we have a selection?
1446 theSelection().haveSelection(bv->cursor().selection());
1449 current_view_->restartCaret();
1451 if (dr.needMessageUpdate()) {
1452 // Some messages may already be translated, so we cannot use _()
1453 current_view_->message(makeDispatchMessage(
1454 translateIfPossible(dr.message()), cmd));
1459 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1460 bool switchToBuffer)
1462 if (!theSession().bookmarks().isValid(idx))
1464 BookmarksSection::Bookmark const & bm =
1465 theSession().bookmarks().bookmark(idx);
1466 LASSERT(!bm.filename.empty(), return);
1467 string const file = bm.filename.absFileName();
1468 // if the file is not opened, open it.
1469 if (!theBufferList().exists(bm.filename)) {
1471 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1475 // open may fail, so we need to test it again
1476 if (!theBufferList().exists(bm.filename))
1479 // bm can be changed when saving
1480 BookmarksSection::Bookmark tmp = bm;
1482 // Special case idx == 0 used for back-from-back jump navigation
1484 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1486 // if the current buffer is not that one, switch to it.
1487 BufferView * doc_bv = current_view_ ?
1488 current_view_->documentBufferView() : 0;
1489 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1490 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1491 if (switchToBuffer) {
1492 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1495 doc_bv = current_view_->documentBufferView();
1500 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1501 if (!doc_bv || !doc_bv->moveToPosition(
1502 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1505 Cursor & cur = doc_bv->cursor();
1506 if (old && cur != *old)
1507 notifyCursorLeavesOrEnters(*old, cur);
1513 // Cursor jump succeeded!
1514 pit_type new_pit = cur.pit();
1515 pos_type new_pos = cur.pos();
1516 int new_id = cur.paragraph().id();
1518 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1519 // see http://www.lyx.org/trac/ticket/3092
1520 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1521 || bm.top_id != new_id) {
1522 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1523 new_pit, new_pos, new_id);
1527 // This function runs "configure" and then rereads lyx.defaults to
1528 // reconfigure the automatic settings.
1529 void GuiApplication::reconfigure(string const & option)
1531 // emit message signal.
1533 current_view_->message(_("Running configure..."));
1535 // Run configure in user lyx directory
1536 string const lock_file = package().getConfigureLockName();
1537 int fd = fileLock(lock_file.c_str());
1538 int const ret = package().reconfigureUserLyXDir(option);
1539 // emit message signal.
1541 current_view_->message(_("Reloading configuration..."));
1542 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1543 // Re-read packages.lst
1544 LaTeXPackages::getAvailable();
1545 fileUnlock(fd, lock_file.c_str());
1548 Alert::information(_("System reconfiguration failed"),
1549 _("The system reconfiguration has failed.\n"
1550 "Default textclass is used but LyX may\n"
1551 "not be able to work properly.\n"
1552 "Please reconfigure again if needed."));
1554 Alert::information(_("System reconfigured"),
1555 _("The system has been reconfigured.\n"
1556 "You need to restart LyX to make use of any\n"
1557 "updated document class specifications."));
1560 void GuiApplication::validateCurrentView()
1562 if (!d->views_.empty() && !current_view_) {
1563 // currently at least one view exists but no view has the focus.
1564 // choose the last view to make it current.
1565 // a view without any open document is preferred.
1566 GuiView * candidate = 0;
1567 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1568 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1569 for (; it != end; ++it) {
1571 if (!candidate->documentBufferView())
1574 setCurrentView(candidate);
1578 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1580 string const argument = to_utf8(cmd.argument());
1581 FuncCode const action = cmd.action();
1583 LYXERR(Debug::ACTION, "cmd: " << cmd);
1585 // we have not done anything wrong yet.
1588 FuncStatus const flag = getStatus(cmd);
1589 if (!flag.enabled()) {
1590 // We cannot use this function here
1591 LYXERR(Debug::ACTION, "action "
1592 << lyxaction.getActionName(action)
1593 << " [" << action << "] is disabled at this location");
1594 dr.setMessage(flag.message());
1596 dr.dispatched(false);
1597 dr.screenUpdate(Update::None);
1598 dr.clearBufferUpdate();
1602 if (cmd.origin() == FuncRequest::LYXSERVER) {
1603 if (current_view_ && current_view_->currentBufferView())
1604 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1605 // we will also need to redraw the screen at the end
1606 dr.screenUpdate(Update::FitCursor);
1609 // Assumes that the action will be dispatched.
1610 dr.dispatched(true);
1612 switch (cmd.action()) {
1614 case LFUN_WINDOW_NEW:
1615 createView(toqstr(cmd.argument()));
1618 case LFUN_WINDOW_CLOSE:
1619 // update bookmark pit of the current buffer before window close
1620 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1621 gotoBookmark(i+1, false, false);
1622 // clear the last opened list, because
1623 // maybe this will end the session
1624 theSession().lastOpened().clear();
1625 // check for valid current_view_
1626 validateCurrentView();
1628 current_view_->closeScheduled();
1632 // quitting is triggered by the gui code
1633 // (leaving the event loop).
1635 current_view_->message(from_utf8(N_("Exiting.")));
1636 if (closeAllViews())
1640 case LFUN_SCREEN_FONT_UPDATE: {
1641 // handle the screen font changes.
1642 d->font_loader_.update();
1643 dr.screenUpdate(Update::Force | Update::FitCursor);
1647 case LFUN_BUFFER_NEW:
1648 validateCurrentView();
1650 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1651 createView(QString(), false); // keep hidden
1652 current_view_->newDocument(to_utf8(cmd.argument()), false);
1653 current_view_->show();
1654 setActiveWindow(current_view_);
1656 current_view_->newDocument(to_utf8(cmd.argument()), false);
1660 case LFUN_BUFFER_NEW_TEMPLATE:
1661 validateCurrentView();
1663 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1665 current_view_->newDocument(to_utf8(cmd.argument()), true);
1666 if (!current_view_->documentBufferView())
1667 current_view_->close();
1669 current_view_->newDocument(to_utf8(cmd.argument()), true);
1673 case LFUN_FILE_OPEN: {
1674 // FIXME: normally the code below is not needed, since getStatus makes sure that
1675 // current_view_ is not null.
1676 validateCurrentView();
1677 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1678 string const fname = to_utf8(cmd.argument());
1679 bool const is_open = FileName::isAbsolute(fname)
1680 && theBufferList().getBuffer(FileName(fname));
1682 || (!lyxrc.open_buffers_in_tabs
1683 && current_view_->documentBufferView() != 0
1685 // We want the ui session to be saved per document and not per
1686 // window number. The filename crc is a good enough identifier.
1687 boost::crc_32_type crc;
1688 crc = for_each(fname.begin(), fname.end(), crc);
1689 createView(crc.checksum());
1690 current_view_->openDocument(fname);
1691 if (!current_view_->documentBufferView())
1692 current_view_->close();
1693 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1694 current_view_->raise();
1695 current_view_->activateWindow();
1696 current_view_->showNormal();
1699 current_view_->openDocument(fname);
1700 if (cmd.origin() == FuncRequest::LYXSERVER) {
1701 current_view_->raise();
1702 current_view_->activateWindow();
1703 current_view_->showNormal();
1709 case LFUN_HELP_OPEN: {
1710 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1711 if (current_view_ == 0)
1713 string const arg = to_utf8(cmd.argument());
1715 current_view_->message(_("Missing argument"));
1718 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1720 fname = i18nLibFileSearch("examples", arg, "lyx");
1722 if (fname.empty()) {
1723 lyxerr << "LyX: unable to find documentation file `"
1724 << arg << "'. Bad installation?" << endl;
1727 current_view_->message(bformat(_("Opening help file %1$s..."),
1728 makeDisplayPath(fname.absFileName())));
1729 Buffer * buf = current_view_->loadDocument(fname, false);
1731 buf->setReadonly(!current_view_->develMode());
1735 case LFUN_SET_COLOR: {
1736 string const lyx_name = cmd.getArg(0);
1737 string const x11_name = cmd.getArg(1);
1738 if (lyx_name.empty() || x11_name.empty()) {
1740 current_view_->message(
1741 _("Syntax: set-color <lyx_name> <x11_name>"));
1746 // FIXME: The graphics cache no longer has a changeDisplay method.
1747 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1748 bool const graphicsbg_changed =
1749 lyx_name == graphicsbg && x11_name != graphicsbg;
1750 if (graphicsbg_changed)
1751 graphics::GCache::get().changeDisplay(true);
1754 if (!lcolor.setColor(lyx_name, x11_name)) {
1756 current_view_->message(
1757 bformat(_("Set-color \"%1$s\" failed "
1758 "- color is undefined or "
1759 "may not be redefined"),
1760 from_utf8(lyx_name)));
1763 // Make sure we don't keep old colors in cache.
1764 d->color_cache_.clear();
1765 // Update the current view
1766 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1770 case LFUN_LYXRC_APPLY: {
1771 // reset active key sequences, since the bindings
1772 // are updated (bug 6064)
1774 LyXRC const lyxrc_orig = lyxrc;
1776 istringstream ss(to_utf8(cmd.argument()));
1777 bool const success = lyxrc.read(ss);
1780 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1781 << "Unable to read lyxrc data"
1786 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1788 // If the request comes from the minibuffer, then we can't reset
1789 // the GUI, since that would destory the minibuffer itself and
1790 // cause a crash, since we are currently in one of the methods of
1791 // GuiCommandBuffer. See bug #8540.
1792 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1795 // FIXME Unfortunately, that leaves a bug here, since we cannot
1796 // reset the GUI in this case. If the changes to lyxrc affected the
1797 // UI, then, nothing would happen. This seems fairly unlikely, but
1798 // it definitely is a bug.
1800 dr.forceBufferUpdate();
1804 case LFUN_COMMAND_PREFIX:
1805 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1810 d->meta_fake_bit = NoModifier;
1811 GuiView * gv = currentView();
1812 if (gv && gv->currentBufferView())
1813 // cancel any selection
1814 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1815 dr.setMessage(from_ascii(N_("Cancel")));
1818 case LFUN_META_PREFIX:
1819 d->meta_fake_bit = AltModifier;
1820 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1823 // --- Menus -----------------------------------------------
1824 case LFUN_RECONFIGURE:
1825 // argument is any additional parameter to the configure.py command
1826 reconfigure(to_utf8(cmd.argument()));
1829 // --- lyxserver commands ----------------------------
1830 case LFUN_SERVER_GET_FILENAME: {
1831 if (current_view_ && current_view_->documentBufferView()) {
1832 docstring const fname = from_utf8(
1833 current_view_->documentBufferView()->buffer().absFileName());
1834 dr.setMessage(fname);
1835 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1837 dr.setMessage(docstring());
1838 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1843 case LFUN_SERVER_NOTIFY: {
1844 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1845 dr.setMessage(dispatch_buffer);
1846 theServer().notifyClient(to_utf8(dispatch_buffer));
1850 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1851 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1857 string rest = split(argument, countstr, ' ');
1858 int const count = convert<int>(countstr);
1859 // an arbitrary number to limit number of iterations
1860 int const max_iter = 10000;
1861 if (count > max_iter) {
1862 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1865 for (int i = 0; i < count; ++i) {
1866 FuncRequest lfun = lyxaction.lookupFunc(rest);
1867 lfun.allowAsync(false);
1874 case LFUN_COMMAND_SEQUENCE: {
1875 // argument contains ';'-terminated commands
1876 string arg = argument;
1877 // FIXME: this LFUN should also work without any view.
1878 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1879 ? &(current_view_->documentBufferView()->buffer()) : 0;
1880 // This handles undo groups automagically
1881 UndoGroupHelper ugh(buffer);
1882 while (!arg.empty()) {
1884 arg = split(arg, first, ';');
1885 FuncRequest func(lyxaction.lookupFunc(first));
1886 func.allowAsync(false);
1887 func.setOrigin(cmd.origin());
1893 case LFUN_BUFFER_FORALL: {
1894 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1895 funcToRun.allowAsync(false);
1897 map<Buffer *, GuiView *> views_lVisible;
1898 map<GuiView *, Buffer *> activeBuffers;
1900 QList<GuiView *> allViews = d->views_.values();
1902 // this for does not modify any buffer. It just collects info on local
1903 // visibility of buffers and on which buffer is active in each view.
1904 Buffer * const last = theBufferList().last();
1905 for(GuiView * view : allViews) {
1906 // all of the buffers might be locally hidden. That is, there is no
1908 if (!view || !view->currentBufferView())
1909 activeBuffers[view] = 0;
1911 activeBuffers[view] = &view->currentBufferView()->buffer();
1913 // find out if each is locally visible or locally hidden.
1914 // we don't use a for loop as the buffer list cycles.
1915 Buffer * b = theBufferList().first();
1917 bool const locallyVisible = view && view->workArea(*b);
1918 if (locallyVisible) {
1919 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1920 // only need to overwrite/add if we don't already know a buffer is globally
1921 // visible or we do know but we would prefer to dispatch LFUN from the
1922 // current view because of cursor position issues.
1923 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1924 views_lVisible[b] = view;
1928 b = theBufferList().next(b);
1932 GuiView * const homeView = currentView();
1933 Buffer * b = theBufferList().first();
1934 Buffer * nextBuf = 0;
1935 int numProcessed = 0;
1938 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1940 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1942 // first change to a view where b is locally visible, preferably current_view_.
1943 GuiView * const vLv = views_lVisible[b];
1945 lyx::dispatch(funcToRun);
1953 // put things back to how they were (if possible).
1954 for (GuiView * view : allViews) {
1955 Buffer * originalBuf = activeBuffers[view];
1956 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1957 if (theBufferList().isLoaded(originalBuf))
1958 view->setBuffer(originalBuf);
1960 homeView->setFocus();
1962 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1966 case LFUN_COMMAND_ALTERNATIVES: {
1967 // argument contains ';'-terminated commands
1968 string arg = argument;
1969 while (!arg.empty()) {
1971 arg = split(arg, first, ';');
1972 FuncRequest func(lyxaction.lookupFunc(first));
1973 func.setOrigin(cmd.origin());
1974 FuncStatus const stat = getStatus(func);
1975 if (stat.enabled()) {
1985 if (theTopLevelCmdDef().lock(argument, func)) {
1986 func.setOrigin(cmd.origin());
1988 theTopLevelCmdDef().release(argument);
1990 if (func.action() == LFUN_UNKNOWN_ACTION) {
1991 // unknown command definition
1992 lyxerr << "Warning: unknown command definition `"
1996 // recursion detected
1997 lyxerr << "Warning: Recursion in the command definition `"
1998 << argument << "' detected"
2005 case LFUN_PREFERENCES_SAVE:
2006 lyxrc.write(support::makeAbsPath("preferences",
2007 package().user_support().absFileName()), false);
2010 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2011 string const fname = addName(addPath(package().user_support().absFileName(),
2012 "templates/"), "defaults.lyx");
2013 Buffer defaults(fname);
2015 istringstream ss(argument);
2020 // We need to make sure that, after we recreat the DocumentClass,
2021 // which we do in readHeader, we apply it to the document itself.
2022 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2023 int const unknown_tokens = defaults.readHeader(lex);
2024 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2026 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2027 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2029 if (unknown_tokens != 0) {
2030 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2031 << unknown_tokens << " unknown token"
2032 << (unknown_tokens == 1 ? "" : "s")
2036 if (defaults.writeFile(FileName(defaults.absFileName())))
2037 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2038 makeDisplayPath(fname)));
2041 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2046 case LFUN_BOOKMARK_GOTO:
2047 // go to bookmark, open unopened file and switch to buffer if necessary
2048 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2049 dr.screenUpdate(Update::Force | Update::FitCursor);
2052 case LFUN_BOOKMARK_CLEAR:
2053 theSession().bookmarks().clear();
2056 case LFUN_DEBUG_LEVEL_SET:
2057 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2060 case LFUN_DIALOG_SHOW: {
2061 string const name = cmd.getArg(0);
2063 if ( name == "aboutlyx"
2065 || name == "texinfo"
2066 || name == "progress"
2067 || name == "compare")
2069 // work around: on Mac OS the application
2070 // is not terminated when closing the last view.
2071 // Create a new one to be able to dispatch the
2072 // LFUN_DIALOG_SHOW to this view.
2073 if (current_view_ == 0)
2079 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2082 current_view_->dispatch(cmd, dr);
2086 if (cmd.origin() == FuncRequest::LYXSERVER)
2087 updateCurrentView(cmd, dr);
2091 docstring GuiApplication::viewStatusMessage()
2093 // When meta-fake key is pressed, show the key sequence so far + "M-".
2094 if (d->meta_fake_bit != NoModifier)
2095 return d->keyseq.print(KeySequence::ForGui) + "M-";
2097 // Else, when a non-complete key sequence is pressed,
2098 // show the available options.
2099 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2100 return d->keyseq.printOptions(true);
2106 void GuiApplication::handleKeyFunc(FuncCode action)
2110 if (d->keyseq.length())
2112 GuiView * gv = currentView();
2113 LASSERT(gv && gv->currentBufferView(), return);
2114 BufferView * bv = gv->currentBufferView();
2115 bv->getIntl().getTransManager().deadkey(
2116 c, get_accent(action).accent, bv->cursor().innerText(),
2118 // Need to clear, in case the minibuffer calls these
2121 // copied verbatim from do_accent_char
2122 bv->cursor().resetAnchor();
2126 //Keep this in sync with GuiApplication::processKeySym below
2127 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2128 KeyModifier state) const
2130 // Do nothing if we have nothing
2131 if (!keysym.isOK() || keysym.isModifier())
2133 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2135 FuncRequest func = seq.addkey(keysym, state);
2136 // When not cancel or meta-fake, do the normal lookup.
2137 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2139 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2141 // Maybe user can only reach the key via holding down shift.
2142 // Let's see. But only if shift is the only modifier
2143 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2144 // If addkey looked up a command and did not find further commands then
2145 // seq has been reset at this point
2146 func = seq.addkey(keysym, NoModifier);
2148 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2149 << seq.print(KeySequence::Portable) << ']');
2150 return func.action() != LFUN_UNKNOWN_ACTION;
2154 //Keep this in sync with GuiApplication::queryKeySym above
2155 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2157 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2159 // Do nothing if we have nothing (JMarc)
2160 if (!keysym.isOK() || keysym.isModifier()) {
2162 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2164 current_view_->restartCaret();
2168 char_type encoded_last_key = keysym.getUCSEncoded();
2170 // Do a one-deep top-level lookup for
2171 // cancel and meta-fake keys. RVDK_PATCH_5
2172 d->cancel_meta_seq.reset();
2174 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2175 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2177 // When not cancel or meta-fake, do the normal lookup.
2178 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2179 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2180 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2181 // remove Caps Lock and Mod2 as a modifiers
2182 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2183 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2186 // Dont remove this unless you know what you are doing.
2187 d->meta_fake_bit = NoModifier;
2189 // Can this happen now ?
2190 if (func.action() == LFUN_NOACTION)
2191 func = FuncRequest(LFUN_COMMAND_PREFIX);
2193 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2194 << d->keyseq.print(KeySequence::Portable) << ']');
2196 // already here we know if it any point in going further
2197 // why not return already here if action == -1 and
2198 // num_bytes == 0? (Lgb)
2200 if (d->keyseq.length() > 1 && current_view_)
2201 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2204 // Maybe user can only reach the key via holding down shift.
2205 // Let's see. But only if shift is the only modifier
2206 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2207 LYXERR(Debug::KEY, "Trying without shift");
2208 // If addkey looked up a command and did not find further commands then
2209 // seq has been reset at this point
2210 func = d->keyseq.addkey(keysym, NoModifier);
2211 LYXERR(Debug::KEY, "Action now " << func.action());
2214 if (func.action() == LFUN_UNKNOWN_ACTION) {
2215 // We didn't match any of the key sequences.
2216 // See if it's normal insertable text not already
2217 // covered by a binding
2218 if (keysym.isText() && d->keyseq.length() == 1) {
2219 // Non-printable characters (such as ASCII control characters)
2220 // must not be inserted (#5704)
2221 if (!isPrintable(encoded_last_key)) {
2222 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2224 current_view_->restartCaret();
2227 // The following modifier check is not needed on Mac.
2228 // The keysym is either not text or it is different
2229 // from the non-modifier keysym. See #9875 for the
2230 // broken alt-modifier effect of having this code active.
2231 #if !defined(Q_OS_MAC)
2232 // If a non-Shift Modifier is used we have a non-bound key sequence
2233 // (such as Alt+j = j). This should be omitted (#5575).
2234 // On Windows, AltModifier and ControlModifier are both
2235 // set when AltGr is pressed. Therefore, in order to not
2236 // break AltGr-bound symbols (see #5575 for details),
2237 // unbound Ctrl+Alt key sequences are allowed.
2238 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2239 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2240 && !(state & AltModifier && state & ControlModifier)
2244 if (current_view_) {
2245 current_view_->message(_("Unknown function."));
2246 current_view_->restartCaret();
2251 // Since all checks above were passed, we now really have text that
2252 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2253 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2255 LYXERR(Debug::KEY, "isText() is true, inserting.");
2256 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2258 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2259 if (current_view_) {
2260 current_view_->message(_("Unknown function."));
2261 current_view_->restartCaret();
2267 if (func.action() == LFUN_SELF_INSERT) {
2268 if (encoded_last_key != 0) {
2269 docstring const arg(1, encoded_last_key);
2270 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2271 FuncRequest::KEYBOARD));
2272 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2275 processFuncRequest(func);
2279 void GuiApplication::processFuncRequest(FuncRequest const & func)
2281 lyx::dispatch(func);
2285 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2287 addToFuncRequestQueue(func);
2288 processFuncRequestQueueAsync();
2292 void GuiApplication::processFuncRequestQueue()
2294 while (!d->func_request_queue_.empty()) {
2295 // take the item from the stack _before_ processing the
2296 // request in order to avoid race conditions from nested
2297 // or parallel requests (see #10406)
2298 FuncRequest const fr(d->func_request_queue_.front());
2299 d->func_request_queue_.pop();
2300 processFuncRequest(fr);
2305 void GuiApplication::processFuncRequestQueueAsync()
2307 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2311 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2313 d->func_request_queue_.push(func);
2317 void GuiApplication::resetGui()
2319 // Set the language defined by the user.
2323 if (!readUIFile(toqstr(lyxrc.ui_file)))
2324 // Gives some error box here.
2327 if (d->global_menubar_)
2328 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2330 QHash<int, GuiView *>::iterator it;
2331 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2334 gv->setLayoutDirection(layoutDirection());
2338 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2342 void GuiApplication::createView(int view_id)
2344 createView(QString(), true, view_id);
2348 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2351 // release the keyboard which might have been grabed by the global
2352 // menubar on Mac to catch shortcuts even without any GuiView.
2353 if (d->global_menubar_)
2354 d->global_menubar_->releaseKeyboard();
2358 while (d->views_.find(id) != d->views_.end())
2361 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2362 GuiView * view = new GuiView(id);
2363 // `view' is the new current_view_. Tell coverity that is is not 0.
2364 LATTEST(current_view_);
2366 d->views_[id] = view;
2370 setActiveWindow(view);
2373 if (!geometry_arg.isEmpty()) {
2374 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2378 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2379 re.indexIn(geometry_arg);
2380 w = re.cap(1).toInt();
2381 h = re.cap(2).toInt();
2382 x = re.cap(3).toInt();
2383 y = re.cap(4).toInt();
2384 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2385 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2386 // Set initial geometry such that we can get the frame size.
2387 view->setGeometry(x, y, w, h);
2388 int framewidth = view->geometry().x() - view->x();
2389 int titleheight = view->geometry().y() - view->y();
2390 // Negative displacements must be interpreted as distances
2391 // from the right or bottom screen borders.
2392 if (sx == '-' || sy == '-') {
2393 QRect rec = QApplication::desktop()->screenGeometry();
2395 x += rec.width() - w - framewidth;
2397 y += rec.height() - h - titleheight;
2398 view->setGeometry(x, y, w, h);
2400 // Make sure that the left and top frame borders are visible.
2401 if (view->x() < 0 || view->y() < 0) {
2406 view->setGeometry(x, y, w, h);
2414 bool GuiApplication::unhide(Buffer * buf)
2418 currentView()->setBuffer(buf, false);
2423 Clipboard & GuiApplication::clipboard()
2425 return d->clipboard_;
2429 Selection & GuiApplication::selection()
2431 return d->selection_;
2435 FontLoader & GuiApplication::fontLoader()
2437 return d->font_loader_;
2441 Toolbars const & GuiApplication::toolbars() const
2443 return d->toolbars_;
2447 Toolbars & GuiApplication::toolbars()
2449 return d->toolbars_;
2453 Menus const & GuiApplication::menus() const
2459 Menus & GuiApplication::menus()
2465 QList<int> GuiApplication::viewIds() const
2467 return d->views_.keys();
2471 ColorCache & GuiApplication::colorCache()
2473 return d->color_cache_;
2477 int GuiApplication::exec()
2479 // asynchronously handle batch commands. This event will be in
2480 // the event queue in front of other asynchronous events. Hence,
2481 // we can assume in the latter that the gui is setup already.
2482 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2484 return QApplication::exec();
2488 void GuiApplication::exit(int status)
2490 QApplication::exit(status);
2494 void GuiApplication::setGuiLanguage()
2498 // install translation file for Qt built-in dialogs
2499 QString const language_name = QString("qt_") + theLocale.name();
2500 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2501 // Short-named translator can be loaded from a long name, but not the
2502 // opposite. Therefore, long name should be used without truncation.
2503 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2504 if (!d->qt_trans_.load(language_name,
2505 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2506 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2509 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2513 switch (theLocale.language()) {
2514 case QLocale::Arabic :
2515 case QLocale::Hebrew :
2516 case QLocale::Persian :
2517 case QLocale::Urdu :
2518 setLayoutDirection(Qt::RightToLeft);
2521 setLayoutDirection(Qt::LeftToRight);
2526 void GuiApplication::execBatchCommands()
2531 if (!readUIFile(toqstr(lyxrc.ui_file)))
2532 // Gives some error box here.
2536 #if QT_VERSION > 0x040600
2537 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2539 #if QT_VERSION > 0x050100
2540 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2542 // Create the global default menubar which is shown for the dialogs
2543 // and if no GuiView is visible.
2544 // This must be done after the session was recovered to know the "last files".
2545 d->global_menubar_ = new QMenuBar(0);
2546 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2549 lyx::execBatchCommands();
2553 QAbstractItemModel * GuiApplication::languageModel()
2555 if (d->language_model_)
2556 return d->language_model_;
2558 QStandardItemModel * lang_model = new QStandardItemModel(this);
2559 lang_model->insertColumns(0, 3);
2560 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2561 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2562 Languages::const_iterator it = lyx::languages.begin();
2563 Languages::const_iterator end = lyx::languages.end();
2564 for (; it != end; ++it) {
2565 int current_row = lang_model->rowCount();
2566 lang_model->insertRows(current_row, 1);
2567 QModelIndex pl_item = lang_model->index(current_row, 0);
2568 QModelIndex sp_item = lang_model->index(current_row, 1);
2569 QModelIndex th_item = lang_model->index(current_row, 2);
2570 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2571 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2572 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2573 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2574 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2575 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2576 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2577 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2578 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2579 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2581 d->language_model_ = new QSortFilterProxyModel(this);
2582 d->language_model_->setSourceModel(lang_model);
2583 d->language_model_->setSortLocaleAware(true);
2584 return d->language_model_;
2588 void GuiApplication::restoreGuiSession()
2590 if (!lyxrc.load_session)
2593 Session & session = theSession();
2594 LastOpenedSection::LastOpened const & lastopened =
2595 session.lastOpened().getfiles();
2597 validateCurrentView();
2599 FileName active_file;
2600 // do not add to the lastfile list since these files are restored from
2601 // last session, and should be already there (regular files), or should
2602 // not be added at all (help files).
2603 for (size_t i = 0; i < lastopened.size(); ++i) {
2604 FileName const & file_name = lastopened[i].file_name;
2605 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2606 && current_view_->documentBufferView() != 0)) {
2607 boost::crc_32_type crc;
2608 string const & fname = file_name.absFileName();
2609 crc = for_each(fname.begin(), fname.end(), crc);
2610 createView(crc.checksum());
2612 current_view_->loadDocument(file_name, false);
2614 if (lastopened[i].active)
2615 active_file = file_name;
2618 // Restore last active buffer
2619 Buffer * buffer = theBufferList().getBuffer(active_file);
2620 if (buffer && current_view_)
2621 current_view_->setBuffer(buffer);
2623 // clear this list to save a few bytes of RAM
2624 session.lastOpened().clear();
2628 QString const GuiApplication::romanFontName()
2631 font.setStyleHint(QFont::Serif);
2632 font.setFamily("serif");
2634 return QFontInfo(font).family();
2638 QString const GuiApplication::sansFontName()
2641 font.setStyleHint(QFont::SansSerif);
2642 font.setFamily("sans");
2644 return QFontInfo(font).family();
2648 QString const GuiApplication::typewriterFontName()
2650 return QFontInfo(typewriterSystemFont()).family();
2655 // We cannot use QFont::fixedPitch() because it doesn't
2656 // return the fact but only if it is requested.
2657 static bool isFixedPitch(const QFont & font) {
2658 const QFontInfo fi(font);
2659 return fi.fixedPitch();
2664 QFont const GuiApplication::typewriterSystemFont()
2666 #if QT_VERSION >= 0x050200
2667 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2669 QFont font("monospace");
2671 if (!isFixedPitch(font)) {
2672 // try to enforce a real monospaced font
2673 font.setStyleHint(QFont::Monospace);
2674 if (!isFixedPitch(font)) {
2675 font.setStyleHint(QFont::TypeWriter);
2676 if (!isFixedPitch(font)) font.setFamily("courier");
2680 // On a Mac the result is too small and it's not practical to
2681 // rely on Qtconfig utility to change the system settings of Qt.
2682 font.setPointSize(12);
2688 void GuiApplication::handleRegularEvents()
2690 ForkedCallsController::handleCompletedProcesses();
2694 bool GuiApplication::event(QEvent * e)
2697 case QEvent::FileOpen: {
2698 // Open a file; this happens only on Mac OS X for now.
2700 // We do this asynchronously because on startup the batch
2701 // commands are not executed here yet and the gui is not ready
2703 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2704 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2705 processFuncRequestAsync(fr);
2710 return QApplication::event(e);
2715 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2718 return QApplication::notify(receiver, event);
2720 catch (ExceptionMessage const & e) {
2722 case ErrorException:
2724 setQuitOnLastWindowClosed(false);
2726 Alert::error(e.title_, e.details_);
2728 // Properly crash in debug mode in order to get a useful backtrace.
2731 // In release mode, try to exit gracefully.
2733 // FIXME: GCC 7 thinks we can fall through here. Can we?
2735 case BufferException: {
2736 if (!current_view_ || !current_view_->documentBufferView())
2738 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2739 docstring details = e.details_ + '\n';
2740 details += buf->emergencyWrite();
2741 theBufferList().release(buf);
2742 details += "\n" + _("The current document was closed.");
2743 Alert::error(e.title_, details);
2746 case WarningException:
2747 Alert::warning(e.title_, e.details_);
2751 catch (exception const & e) {
2752 docstring s = _("LyX has caught an exception, it will now "
2753 "attempt to save all unsaved documents and exit."
2755 s += from_ascii(e.what());
2756 Alert::error(_("Software exception Detected"), s);
2760 docstring s = _("LyX has caught some really weird exception, it will "
2761 "now attempt to save all unsaved documents and exit.");
2762 Alert::error(_("Software exception Detected"), s);
2770 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2772 QColor const & qcol = d->color_cache_.get(col);
2773 if (!qcol.isValid()) {
2779 rgbcol.r = qcol.red();
2780 rgbcol.g = qcol.green();
2781 rgbcol.b = qcol.blue();
2786 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2788 QColor const qcol(lcolor.getX11Name(col).c_str());
2789 if (!qcol.isValid()) {
2795 rgbcol.r = qcol.red();
2796 rgbcol.g = qcol.green();
2797 rgbcol.b = qcol.blue();
2802 string const GuiApplication::hexName(ColorCode col)
2804 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2808 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2810 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2811 d->socket_notifiers_[fd] = sn;
2812 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2816 void GuiApplication::socketDataReceived(int fd)
2818 d->socket_notifiers_[fd]->func_();
2822 void GuiApplication::unregisterSocketCallback(int fd)
2824 d->socket_notifiers_.take(fd)->setEnabled(false);
2828 void GuiApplication::commitData(QSessionManager & sm)
2830 /** The implementation is required to avoid an application exit
2831 ** when session state save is triggered by session manager.
2832 ** The default implementation sends a close event to all
2833 ** visible top level widgets when session managment allows
2835 ** We are changing that to check the state of each buffer in all
2836 ** views and ask the users what to do if buffers are dirty.
2837 ** Furthermore, we save the session state.
2838 ** We do NOT close the views here since the user still can cancel
2839 ** the logout process (see #9277); also, this would hide LyX from
2840 ** an OSes own session handling (application restoration).
2842 #ifdef QT_NO_SESSIONMANAGER
2844 #warning Qt is compiled without session manager
2846 #pragma message("warning: Qt is compiled without session manager")
2850 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2858 void GuiApplication::unregisterView(GuiView * gv)
2860 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2861 d->views_.remove(gv->id());
2862 if (current_view_ == gv)
2868 bool GuiApplication::closeAllViews()
2870 if (d->views_.empty())
2873 // When a view/window was closed before without quitting LyX, there
2874 // are already entries in the lastOpened list.
2875 theSession().lastOpened().clear();
2877 QList<GuiView *> const views = d->views_.values();
2878 for (GuiView * view : views) {
2879 if (!view->closeScheduled())
2888 bool GuiApplication::prepareAllViewsForLogout()
2890 if (d->views_.empty())
2893 QList<GuiView *> const views = d->views_.values();
2894 for (GuiView * view : views) {
2895 if (!view->prepareAllBuffersForLogout())
2903 GuiView & GuiApplication::view(int id) const
2905 LAPPERR(d->views_.contains(id));
2906 return *d->views_.value(id);
2910 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2912 QList<GuiView *> const views = d->views_.values();
2913 for (GuiView * view : views)
2914 view->hideDialog(name, inset);
2918 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2920 Buffer const * buffer_ = 0;
2921 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2922 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2923 if (Buffer const * ptr = (*it)->updateInset(inset))
2930 bool GuiApplication::searchMenu(FuncRequest const & func,
2931 docstring_list & names) const
2933 BufferView * bv = 0;
2935 bv = current_view_->currentBufferView();
2936 return d->menus_.searchMenu(func, names, bv);
2940 bool GuiApplication::hasBufferView() const
2942 return (current_view_ && current_view_->currentBufferView());
2946 // Ensure that a file is read only once (prevents include loops)
2947 static QStringList uifiles;
2948 // store which ui files define Toolbars
2949 static QStringList toolbar_uifiles;
2952 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2963 LexerKeyword uitags[] = {
2964 { "format", ui_format },
2965 { "include", ui_include },
2966 { "menuset", ui_menuset },
2967 { "toolbars", ui_toolbars },
2968 { "toolbarset", ui_toolbarset }
2972 lex.setFile(ui_path);
2974 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2978 if (lyxerr.debugging(Debug::PARSER))
2979 lex.printTable(lyxerr);
2982 // format before introduction of format tag
2983 unsigned int format = 0;
2984 while (lex.isOK()) {
2985 int const status = lex.lex();
2987 // we have to do this check here, outside the switch,
2988 // because otherwise we would start reading include files,
2989 // e.g., if the first tag we hit was an include tag.
2990 if (status == ui_format)
2992 format = lex.getInteger();
2996 // this will trigger unless the first tag we hit is a format
2997 // tag, with the right format.
2998 if (format != LFUN_FORMAT)
2999 return FormatMismatch;
3002 case Lexer::LEX_FEOF:
3007 QString const file = toqstr(lex.getString());
3008 bool const success = readUIFile(file, true);
3010 LYXERR0("Failed to read included file: " << fromqstr(file));
3017 d->menus_.read(lex);
3021 d->toolbars_.readToolbars(lex);
3025 d->toolbars_.readToolbarSettings(lex);
3026 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3030 if (!rtrim(lex.getString()).empty())
3031 lex.printError("LyX::ReadUIFile: "
3032 "Unknown menu tag: `$$Token'");
3034 LYXERR0("Error with status: " << status);
3040 return (error ? ReadError : ReadOK);
3044 bool GuiApplication::readUIFile(QString const & name, bool include)
3046 LYXERR(Debug::INIT, "About to read " << name << "...");
3050 ui_path = libFileSearch("ui", name, "inc");
3051 if (ui_path.empty())
3052 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3054 ui_path = libFileSearch("ui", name, "ui");
3057 if (ui_path.empty()) {
3058 static const QString defaultUIFile = "default";
3059 LYXERR(Debug::INIT, "Could not find " << name);
3061 Alert::warning(_("Could not find UI definition file"),
3062 bformat(_("Error while reading the included file\n%1$s\n"
3063 "Please check your installation."), qstring_to_ucs4(name)));
3066 if (name == defaultUIFile) {
3067 LYXERR(Debug::INIT, "Could not find default UI file!!");
3068 Alert::warning(_("Could not find default UI file"),
3069 _("LyX could not find the default UI file!\n"
3070 "Please check your installation."));
3073 Alert::warning(_("Could not find UI definition file"),
3074 bformat(_("Error while reading the configuration file\n%1$s\n"
3075 "Falling back to default.\n"
3076 "Please look under Tools>Preferences>User Interface and\n"
3077 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3078 return readUIFile(defaultUIFile, false);
3081 QString const uifile = toqstr(ui_path.absFileName());
3082 if (uifiles.contains(uifile)) {
3084 // We are reading again the top uifile so reset the safeguard:
3087 d->toolbars_.reset();
3089 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3090 << "Is this an include loop?");
3094 uifiles.push_back(uifile);
3096 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3098 ReturnValues retval = readUIFile(ui_path);
3100 if (retval == FormatMismatch) {
3101 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3102 TempFile tmp("convertXXXXXX.ui");
3103 FileName const tempfile = tmp.name();
3104 bool const success = prefs2prefs(ui_path, tempfile, true);
3106 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3107 " to format " << LFUN_FORMAT << ".");
3109 retval = readUIFile(tempfile);
3113 if (retval != ReadOK) {
3114 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3122 settings.beginGroup("ui_files");
3123 bool touched = false;
3124 for (int i = 0; i != uifiles.size(); ++i) {
3125 QFileInfo fi(uifiles[i]);
3126 QDateTime const date_value = fi.lastModified();
3127 QString const name_key = QString::number(i);
3128 // if an ui file which defines Toolbars has changed,
3129 // we have to reset the settings
3130 if (toolbar_uifiles.contains(uifiles[i])
3131 && (!settings.contains(name_key)
3132 || settings.value(name_key).toString() != uifiles[i]
3133 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3135 settings.setValue(name_key, uifiles[i]);
3136 settings.setValue(name_key + "/date", date_value);
3139 settings.endGroup();
3141 settings.remove("views");
3147 void GuiApplication::onLastWindowClosed()
3149 if (d->global_menubar_)
3150 d->global_menubar_->grabKeyboard();
3154 void GuiApplication::startLongOperation() {
3155 d->key_checker_.start();
3159 bool GuiApplication::longOperationCancelled() {
3160 return d->key_checker_.pressed();
3164 void GuiApplication::stopLongOperation() {
3165 d->key_checker_.stop();
3169 bool GuiApplication::longOperationStarted() {
3170 return d->key_checker_.started();
3174 ////////////////////////////////////////////////////////////////////////
3176 // X11 specific stuff goes here...
3179 bool GuiApplication::x11EventFilter(XEvent * xev)
3184 switch (xev->type) {
3185 case SelectionRequest: {
3186 if (xev->xselectionrequest.selection != XA_PRIMARY)
3188 LYXERR(Debug::SELECTION, "X requested selection.");
3189 BufferView * bv = current_view_->currentBufferView();
3191 docstring const sel = bv->requestSelection();
3193 d->selection_.put(sel);
3194 // Refresh the selection request timestamp.
3195 // We have to do this by ourselves as Qt seems
3196 // not doing that, maybe because of our
3197 // "persistent selection" implementation
3198 // (see comments in GuiSelection.cpp).
3199 XSelectionEvent nev;
3200 nev.type = SelectionNotify;
3201 nev.display = xev->xselectionrequest.display;
3202 nev.requestor = xev->xselectionrequest.requestor;
3203 nev.selection = xev->xselectionrequest.selection;
3204 nev.target = xev->xselectionrequest.target;
3205 nev.property = 0L; // None
3206 nev.time = CurrentTime;
3207 XSendEvent(QX11Info::display(),
3208 nev.requestor, False, 0,
3209 reinterpret_cast<XEvent *>(&nev));
3215 case SelectionClear: {
3216 if (xev->xselectionclear.selection != XA_PRIMARY)
3218 LYXERR(Debug::SELECTION, "Lost selection.");
3219 BufferView * bv = current_view_->currentBufferView();
3221 bv->clearSelection();
3227 #elif defined(QPA_XCB)
3228 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3229 void * message, long *)
3231 if (!current_view_ || eventType != "xcb_generic_event_t")
3234 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3236 switch (ev->response_type) {
3237 case XCB_SELECTION_REQUEST: {
3238 xcb_selection_request_event_t * srev =
3239 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3240 if (srev->selection != XCB_ATOM_PRIMARY)
3242 LYXERR(Debug::SELECTION, "X requested selection.");
3243 BufferView * bv = current_view_->currentBufferView();
3245 docstring const sel = bv->requestSelection();
3247 d->selection_.put(sel);
3248 #ifdef HAVE_QT5_X11_EXTRAS
3249 // Refresh the selection request timestamp.
3250 // We have to do this by ourselves as Qt seems
3251 // not doing that, maybe because of our
3252 // "persistent selection" implementation
3253 // (see comments in GuiSelection.cpp).
3254 xcb_selection_notify_event_t nev;
3255 nev.response_type = XCB_SELECTION_NOTIFY;
3256 nev.requestor = srev->requestor;
3257 nev.selection = srev->selection;
3258 nev.target = srev->target;
3259 nev.property = XCB_NONE;
3260 nev.time = XCB_CURRENT_TIME;
3261 xcb_connection_t * con = QX11Info::connection();
3262 xcb_send_event(con, 0, srev->requestor,
3263 XCB_EVENT_MASK_NO_EVENT,
3264 reinterpret_cast<char const *>(&nev));
3272 case XCB_SELECTION_CLEAR: {
3273 xcb_selection_clear_event_t * scev =
3274 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3275 if (scev->selection != XCB_ATOM_PRIMARY)
3277 LYXERR(Debug::SELECTION, "Lost selection.");
3278 BufferView * bv = current_view_->currentBufferView();
3280 bv->clearSelection();
3288 } // namespace frontend
3291 void hideDialogs(std::string const & name, Inset * inset)
3294 frontend::guiApp->hideDialogs(name, inset);
3298 ////////////////////////////////////////////////////////////////////
3302 ////////////////////////////////////////////////////////////////////
3304 frontend::FontLoader & theFontLoader()
3306 LAPPERR(frontend::guiApp);
3307 return frontend::guiApp->fontLoader();
3311 frontend::FontMetrics const & theFontMetrics(Font const & f)
3313 return theFontMetrics(f.fontInfo());
3317 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3319 LAPPERR(frontend::guiApp);
3320 return frontend::guiApp->fontLoader().metrics(f);
3324 ////////////////////////////////////////////////////////////////////
3328 ////////////////////////////////////////////////////////////////////
3330 frontend::Clipboard & theClipboard()
3332 LAPPERR(frontend::guiApp);
3333 return frontend::guiApp->clipboard();
3337 frontend::Selection & theSelection()
3339 LAPPERR(frontend::guiApp);
3340 return frontend::guiApp->selection();
3346 #include "moc_GuiApplication.cpp"