2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ToolTipFormatter.h"
18 #include "ColorCache.h"
20 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferParams.h"
36 #include "BufferView.h"
39 #include "Converter.h"
40 #include "CutAndPaste.h"
41 #include "ErrorList.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.h"
45 #include "GuiWorkArea.h"
49 #include "LaTeXPackages.h"
52 #include "LyXAction.h"
54 #include "Paragraph.h"
57 #include "SpellChecker.h"
58 #include "Thesaurus.h"
61 #include "insets/InsetText.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/FileName.h"
67 #include "support/filetools.h"
68 #include "support/ForkedCalls.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/lstrings.h"
72 #include "support/lyxalgo.h" // sorted
73 #include "support/textutils.h"
74 #include "support/Messages.h"
75 #include "support/os.h"
76 #include "support/Package.h"
77 #include "support/TempFile.h"
80 #include "support/AppleScript.h"
81 #include "support/linkback/LinkBackProxy.h"
88 #include <QDesktopWidget>
91 #include <QFileOpenEvent>
93 #include <QFontDatabase>
96 #include <QImageReader>
99 #include <QLibraryInfo>
105 #include <QPixmapCache>
107 #include <QSessionManager>
109 #include <QSocketNotifier>
110 #include <QSortFilterProxyModel>
111 #include <QStandardItemModel>
113 #include <QTranslator>
114 #include <QThreadPool>
118 #include <X11/Xatom.h>
119 #include <X11/Xlib.h>
123 #elif defined(QPA_XCB)
125 #ifdef HAVE_QT5_X11_EXTRAS
126 #include <QtX11Extras/QX11Info>
130 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
131 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
132 #if (QT_VERSION < 0x050000)
133 #include <QWindowsMime>
134 #define QWINDOWSMIME QWindowsMime
137 #define QWINDOWSMIME QWinMime
147 #include <QMacPasteboardMime>
150 #include <boost/crc.hpp>
157 using namespace lyx::support;
160 static void initializeResources()
162 static bool initialized = false;
164 Q_INIT_RESOURCE(Resources);
172 frontend::Application * createApplication(int & argc, char * argv[])
174 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
175 // prune -geometry argument(s) by shifting
176 // the following ones 2 places down.
177 for (int i = 0 ; i < argc ; ++i) {
178 if (strcmp(argv[i], "-geometry") == 0) {
179 int const remove = (i+1) < argc ? 2 : 1;
181 for (int j = i; j < argc; ++j)
182 argv[j] = argv[j + remove];
188 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
189 // On Windows, allow bringing the LyX window to top
190 AllowSetForegroundWindow(ASFW_ANY);
193 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
194 // I'd rather do that in the constructor, but I do not think that
195 // the palette is accessible there.
196 guiApp->colorCache().setPalette(guiApp->palette());
205 if (lyxrc.gui_language == "auto") {
206 theLocale = QLocale::system();
207 code = fromqstr(theLocale.name());
209 Language const * l = languages.getLanguage(lyxrc.gui_language);
210 code = l ? l->code() : "C";
211 theLocale = QLocale(toqstr(code));
213 // Qt tries to outsmart us and transforms en_US to C.
214 Messages::guiLanguage((code == "C") ? "en_US" : code);
215 QLocale::setDefault(theLocale);
216 setlocale(LC_NUMERIC, "C");
223 /// Return the list of loadable formats.
224 vector<string> loadableImageFormats()
228 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
230 LYXERR(Debug::GRAPHICS,
231 "\nThe image loader can load the following directly:\n");
233 if (qt_formats.empty())
234 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
236 bool jpeg_found = false;
237 bool jpg_found = false;
238 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
240 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
242 string ext = ascii_lowercase((const char *) *it);
250 else if (ext == "jpg") {
255 else if (lyxrc.use_converter_cache &&
256 (ext == "svg" || ext == "svgz") &&
257 theConverters().isReachable("svg", "png"))
258 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
259 // the SVG as in the output. However we require that the converter
260 // cache is enabled since this is expensive. We also require that
261 // an explicit svg->png converter is defined, since the default
262 // converter could produce bad quality as well. This assumes that
263 // png can always be loaded.
272 ////////////////////////////////////////////////////////////////////////
274 // Icon loading support code
276 ////////////////////////////////////////////////////////////////////////
286 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
288 return lhs.key < rhs.key;
294 CompareKey(QString const & name) : name_(name) {}
295 bool operator()(ImgMap const & other) const { return other.key == name_; }
301 // this must be sorted alphabetically
302 // Upper case comes before lower case
303 // Please don't change the formatting, this list is parsed by
304 // development/tools/generate_symbols_images.py.
305 ImgMap sorted_img_map[] = {
306 { "Arrownot", "arrownot2"},
307 { "Arrowvert", "arrowvert2"},
308 { "Bowtie", "bowtie2" },
310 { "Bumpeq", "bumpeq2" },
311 { "CIRCLE", "circle3" },
313 { "CheckedBox", "checkedbox2" },
314 { "Circle", "circle2" },
315 { "Colonapprox", "colonapprox2" },
316 { "Coloneq", "coloneq2" },
317 { "Coloneqq", "coloneqq2" },
318 { "Colonsim", "colonsim2" },
320 { "DOWNarrow", "downarrow3" },
321 { "Delta", "delta2" },
322 { "Diamond", "diamond2" },
323 { "Doteq", "doteq2" },
324 { "Downarrow", "downarrow2" },
325 { "Eqcolon", "eqcolon2" },
326 { "Eqqcolon", "eqqcolon2" },
327 { "Gamma", "gamma2" },
329 { "LEFTCIRCLE", "leftcircle3" },
330 { "LEFTarrow", "leftarrow3" },
331 { "LEFTcircle", "leftcircle4" },
333 { "Lambda", "lambda2" },
335 { "Leftarrow", "leftarrow2" },
336 { "Leftcircle", "leftcircle2" },
337 { "Leftrightarrow", "leftrightarrow2" },
338 { "Longarrownot", "longarrownot2"},
339 { "Longleftarrow", "longleftarrow2" },
340 { "Longleftrightarrow", "longleftrightarrow2" },
341 { "Longmapsfrom", "longmapsfrom2"},
342 { "Longmapsto", "longmapsto2"},
343 { "Longrightarrow", "longrightarrow2" },
344 { "Mapsfrom", "mapsfrom2"},
345 { "Mapsfromchar", "mapsfromchar2"},
346 { "Mapsto", "mapsto2"},
347 { "Mapstochar", "mapstochar2"},
348 { "Omega", "omega2" },
353 { "RIGHTCIRCLE", "rightcircle3" },
354 { "RIGHTarrow", "rightarrow3" },
355 { "RIGHTcircle", "rightcircle4" },
357 { "Rightarrow", "rightarrow2" },
358 { "Rightcircle", "rightcircle2" },
359 { "Sigma", "sigma2" },
360 { "Square", "square2" },
361 { "Subset", "subset2" },
362 { "Supset", "supset2" },
363 { "Theta", "theta2" },
364 { "Thorn", "thorn2" },
365 { "UParrow", "uparrow3" },
366 { "Uparrow", "uparrow2" },
367 { "Updownarrow", "updownarrow2" },
368 { "Upsilon", "upsilon2" },
369 { "Vdash", "vdash3" },
374 { "lVert", "vert2" },
376 { "nLeftarrow", "nleftarrow2" },
377 { "nLeftrightarrow", "nleftrightarrow2" },
378 { "nRightarrow", "nrightarrow2" },
379 { "nVDash", "nvdash3" },
380 { "nVdash", "nvdash4" },
381 { "nvDash", "nvdash2" },
382 { "rVert", "vert2" },
384 { "textrm \\AA", "textrm_AA"},
385 { "textrm \\O", "textrm_O"},
386 { "vDash", "vdash2" },
387 { "varDelta", "vardelta2" },
388 { "varGamma", "vargamma2" },
389 { "varLambda", "varlambda2" },
390 { "varOmega", "varomega2" },
391 { "varPhi", "varphi2" },
392 { "varPi", "varpi2" },
393 { "varPsi", "varpsi2" },
394 { "varSigma", "varsigma2" },
395 { "varTheta", "vartheta2" },
396 { "varUpsilon", "varupsilon2" },
397 { "varXi", "varxi2" }
401 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
403 // This list specifies which system's theme icon is related to which lyx
404 // command. It was based on:
405 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
406 // this must be sorted alphabetically
407 // Upper case comes before lower case
408 ImgMap sorted_theme_icon_map[] = {
409 { "bookmark-goto 0", "go-jump" },
410 { "buffer-new", "document-new" },
411 { "buffer-write", "document-save" },
412 { "buffer-write-as", "document-save-as" },
413 { "buffer-zoom-in", "zoom-in" },
414 { "buffer-zoom-out", "zoom-out" },
415 { "copy", "edit-copy" },
416 { "cut", "edit-cut" },
417 { "depth-decrement", "format-indent-less" },
418 { "depth-increment", "format-indent-more" },
419 { "dialog-show spellchecker", "tools-check-spelling" },
420 { "dialog-show-new-inset graphics", "insert-image" },
421 { "dialog-toggle findreplaceadv", "edit-find-replace" },
422 { "file-open", "document-open" },
423 { "font-bold", "format-text-bold" },
424 { "font-ital", "format-text-italic" },
425 { "font-strikeout", "format-text-strikethrough" },
426 { "font-underline", "format-text-underline" },
427 { "lyx-quit", "application-exit" },
428 { "paste", "edit-paste" },
429 { "redo", "edit-redo" },
430 { "undo", "edit-undo" },
431 { "window-close", "window-close" },
432 { "window-new", "window-new" }
435 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
438 QString findImg(QString const & name)
440 ImgMap const * const begin = sorted_img_map;
441 ImgMap const * const end = begin + nr_sorted_img_map;
442 LATTEST(sorted(begin, end));
444 ImgMap const * const it = find_if(begin, end, CompareKey(name));
448 img_name = it->value;
451 img_name.replace('_', "underscore");
452 img_name.replace(' ', '_');
454 // This way we can have "math-delim { }" on the toolbar.
455 img_name.replace('(', "lparen");
456 img_name.replace(')', "rparen");
457 img_name.replace('[', "lbracket");
458 img_name.replace(']', "rbracket");
459 img_name.replace('{', "lbrace");
460 img_name.replace('}', "rbrace");
461 img_name.replace('|', "bars");
462 img_name.replace(',', "thinspace");
463 img_name.replace(':', "mediumspace");
464 img_name.replace(';', "thickspace");
465 img_name.replace('!', "negthinspace");
468 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
469 << "Looking for math icon called \"" << img_name << '"');
476 QString themeIconName(QString const & action)
478 ImgMap const * const begin = sorted_theme_icon_map;
479 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
480 LASSERT(sorted(begin, end), /**/);
482 ImgMap const * const it = find_if(begin, end, CompareKey(action));
490 QString iconName(FuncRequest const & f, bool unknown)
492 initializeResources();
496 switch (f.action()) {
497 case LFUN_MATH_INSERT:
498 if (!f.argument().empty()) {
500 name1 = findImg(toqstr(f.argument()).mid(1));
503 case LFUN_MATH_DELIM:
504 case LFUN_MATH_BIGDELIM:
506 name1 = findImg(toqstr(f.argument()));
510 name1 = toqstr(f.argument());
512 case LFUN_COMMAND_ALTERNATIVES: {
513 // use the first of the alternative commands
515 docstring dummy = split(f.argument(), firstcom, ';');
516 name1 = toqstr(firstcom);
517 name1.replace(' ', '_');
521 name2 = toqstr(lyxaction.getActionName(f.action()));
524 if (!f.argument().empty()) {
525 name1 = name2 + ' ' + toqstr(f.argument());
526 name1.replace(' ', '_');
527 name1.replace('\\', "backslash");
531 QStringList imagedirs;
532 imagedirs << "images/" << "images/ipa/";
533 search_mode mode = theGuiApp()->imageSearchMode();
534 for (int i = 0; i < imagedirs.size(); ++i) {
535 QString imagedir = imagedirs.at(i) + path;
536 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
538 return toqstr(fname.absFileName());
540 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
542 return toqstr(fname.absFileName());
545 path = ":/images/" + path;
548 LYXERR0("Directory " << path << " not found in resource!");
551 if (res.exists(name1 + ".svgz"))
552 return path + name1 + ".svgz";
553 else if (res.exists(name1 + ".png"))
554 return path + name1 + ".png";
556 if (res.exists(name2 + ".svgz"))
557 return path + name2 + ".svgz";
558 else if (res.exists(name2 + ".png"))
559 return path + name2 + ".png";
561 LYXERR(Debug::GUI, "Cannot find icon with filename "
562 << "\"" << name1 << ".{svgz,png}\""
564 << "\"" << name2 << ".{svgz,png}\""
566 << lyxaction.getActionName(f.action())
567 << '(' << to_utf8(f.argument()) << ")\"");
570 QString imagedir = "images/";
571 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
573 return toqstr(fname.absFileName());
574 return QString(":/images/unknown.svgz");
581 bool getPixmap(QPixmap & pixmap, QString const & path)
583 return pixmap.load(path);
587 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
589 QString imagedir = path;
590 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
591 QString fpath = toqstr(fname.absFileName());
592 QPixmap pixmap = QPixmap();
594 if (getPixmap(pixmap, fpath)) {
598 QStringList exts = ext.split(",");
599 fpath = ":/" + path + name + ".";
600 for (int i = 0; i < exts.size(); ++i) {
601 if (getPixmap(pixmap, fpath + exts.at(i))) {
606 bool const list = ext.contains(",");
607 LYXERR0("Cannot load pixmap \""
608 << path << name << "." << (list ? "{" : "") << ext
609 << (list ? "}" : "") << "\", please verify resource system!");
615 QIcon getIcon(FuncRequest const & f, bool unknown)
617 #if (QT_VERSION >= 0x040600)
618 if (lyxrc.use_system_theme_icons) {
619 // use the icons from system theme that are available
620 QString action = toqstr(lyxaction.getActionName(f.action()));
621 if (!f.argument().empty())
622 action += " " + toqstr(f.argument());
623 QString const theme_icon = themeIconName(action);
624 if (QIcon::hasThemeIcon(theme_icon)) {
625 QIcon const thmicn = QIcon::fromTheme(theme_icon);
626 if (!thmicn.isNull())
632 QString icon = iconName(f, unknown);
636 //LYXERR(Debug::GUI, "Found icon: " << icon);
637 QPixmap pixmap = QPixmap();
638 if (!getPixmap(pixmap,icon)) {
639 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
643 return QIcon(pixmap);
647 ////////////////////////////////////////////////////////////////////////
649 // LyX server support code.
651 ////////////////////////////////////////////////////////////////////////
653 class SocketNotifier : public QSocketNotifier
656 /// connect a connection notification from the LyXServerSocket
657 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
658 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
662 /// The callback function
663 Application::SocketCallback func_;
667 ////////////////////////////////////////////////////////////////////////
669 // Mac specific stuff goes here...
671 ////////////////////////////////////////////////////////////////////////
673 class MenuTranslator : public QTranslator
676 MenuTranslator(QObject * parent)
677 : QTranslator(parent)
680 #if QT_VERSION >= 0x050000
681 virtual QString translate(const char * /* context */,
682 const char *sourceText,
683 const char * /* disambiguation */ = 0, int /* n */ = -1) const
685 QString translate(const char * /*context*/,
686 const char * sourceText,
687 const char * /*comment*/ = 0) const
690 string const s = sourceText;
691 if (s == N_("About %1") || s == N_("Preferences")
692 || s == N_("Reconfigure") || s == N_("Quit %1"))
700 // QMacPasteboardMimeGraphics can only be compiled on Mac.
702 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
705 QMacPasteboardMimeGraphics()
706 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
709 QString convertorName() { return "Graphics"; }
711 QString flavorFor(QString const & mime)
713 LYXERR(Debug::ACTION, "flavorFor " << mime);
714 if (mime == pdfMimeType())
715 return QLatin1String("com.adobe.pdf");
719 QString mimeFor(QString flav)
721 LYXERR(Debug::ACTION, "mimeFor " << flav);
722 if (flav == QLatin1String("com.adobe.pdf"))
723 return pdfMimeType();
727 bool canConvert(QString const & mime, QString flav)
729 return mimeFor(flav) == mime;
732 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
736 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
740 QList<QByteArray> convertFromMime(QString const & /*mime*/,
741 QVariant data, QString /*flav*/)
743 QList<QByteArray> ret;
744 ret.append(data.toByteArray());
750 ///////////////////////////////////////////////////////////////
752 // You can find more platform specific stuff at the end of this file...
754 ///////////////////////////////////////////////////////////////
756 ////////////////////////////////////////////////////////////////////////
757 // Windows specific stuff goes here...
759 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
760 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
761 // QWindowsMimeMetafile can only be compiled on Windows.
763 static FORMATETC cfFromMime(QString const & mimetype)
766 if (mimetype == emfMimeType()) {
767 formatetc.cfFormat = CF_ENHMETAFILE;
768 formatetc.tymed = TYMED_ENHMF;
769 } else if (mimetype == wmfMimeType()) {
770 formatetc.cfFormat = CF_METAFILEPICT;
771 formatetc.tymed = TYMED_MFPICT;
774 formatetc.dwAspect = DVASPECT_CONTENT;
775 formatetc.lindex = -1;
780 class QWindowsMimeMetafile : public QWINDOWSMIME {
782 QWindowsMimeMetafile() {}
784 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
785 QMimeData const * /*mimedata*/) const
790 bool canConvertToMime(QString const & mimetype,
791 IDataObject * pDataObj) const
793 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
795 FORMATETC formatetc = cfFromMime(mimetype);
796 return pDataObj->QueryGetData(&formatetc) == S_OK;
799 bool convertFromMime(FORMATETC const & /*formatetc*/,
800 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
805 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
806 QVariant::Type /*preferredType*/) const
809 if (!canConvertToMime(mimetype, pDataObj))
812 FORMATETC formatetc = cfFromMime(mimetype);
814 if (pDataObj->GetData(&formatetc, &s) != S_OK)
818 if (s.tymed == TYMED_ENHMF) {
819 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
820 data.resize(dataSize);
821 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
822 (LPBYTE)data.data());
823 } else if (s.tymed == TYMED_MFPICT) {
824 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
825 data.resize(dataSize);
826 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
827 (LPBYTE)data.data());
830 ReleaseStgMedium(&s);
836 QVector<FORMATETC> formatsForMime(QString const & mimetype,
837 QMimeData const * /*mimedata*/) const
839 QVector<FORMATETC> formats;
840 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
841 formats += cfFromMime(mimetype);
845 QString mimeForFormat(FORMATETC const & formatetc) const
847 switch (formatetc.cfFormat) {
849 return emfMimeType();
850 case CF_METAFILEPICT:
851 return wmfMimeType();
861 /// Allows to check whether ESC was pressed during a long operation
862 class KeyChecker : public QObject {
867 KeyChecker() : pressed_(false), started_(false) {}
870 QCoreApplication::instance()->installEventFilter(this);
875 QCoreApplication::instance()->removeEventFilter(this);
879 QCoreApplication::processEvents();
882 bool started() const {
885 bool eventFilter(QObject *obj, QEvent *event) {
886 LYXERR(Debug::ACTION, "Event Type: " << event->type());
887 switch (event->type()) {
891 case QEvent::UpdateRequest:
892 case QEvent::CursorChange:
893 case QEvent::ActionChanged:
894 case QEvent::EnabledChange:
895 case QEvent::SockAct:
898 case QEvent::ToolTipChange:
899 case QEvent::LayoutRequest:
900 case QEvent::MetaCall:
901 return QObject::eventFilter(obj, event);
903 // FIXME Blocking all these events is a bad idea.
904 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
905 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
913 ////////////////////////////////////////////////////////////////////////
914 // GuiApplication::Private definition and implementation.
915 ////////////////////////////////////////////////////////////////////////
917 struct GuiApplication::Private
919 Private(): language_model_(0), meta_fake_bit(NoModifier),
922 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
923 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
924 /// WMF Mime handler for Windows clipboard.
925 wmf_mime_ = new QWindowsMimeMetafile;
928 initKeySequences(&theTopLevelKeymap());
931 void initKeySequences(KeyMap * kb)
933 keyseq = KeySequence(kb, kb);
934 cancel_meta_seq = KeySequence(kb, kb);
938 QSortFilterProxyModel * language_model_;
940 GuiClipboard clipboard_;
942 GuiSelection selection_;
944 FontLoader font_loader_;
946 ColorCache color_cache_;
948 QTranslator qt_trans_;
950 QHash<int, SocketNotifier *> socket_notifiers_;
954 /// The global instance
957 /// this timer is used for any regular events one wants to
958 /// perform. at present it is used to check if forked processes
960 QTimer general_timer_;
962 /// delayed FuncRequests
963 std::queue<FuncRequest> func_request_queue_;
968 KeySequence cancel_meta_seq;
970 KeyModifier meta_fake_bit;
972 /// The result of last dispatch action
973 DispatchResult dispatch_result_;
975 /// Multiple views container.
977 * Warning: This must not be a smart pointer as the destruction of the
978 * object is handled by Qt when the view is closed
979 * \sa Qt::WA_DeleteOnClose attribute.
981 QHash<int, GuiView *> views_;
983 /// Only used on mac.
984 QMenuBar * global_menubar_;
987 /// Linkback mime handler for MacOSX.
988 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
991 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
992 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
993 /// WMF Mime handler for Windows clipboard.
994 QWindowsMimeMetafile * wmf_mime_;
998 /// Allows to check whether ESC was pressed during a long operation
999 KeyChecker key_checker_;
1003 GuiApplication * guiApp;
1005 GuiApplication::~GuiApplication()
1008 closeAllLinkBackLinks();
1014 GuiApplication::GuiApplication(int & argc, char ** argv)
1015 : QApplication(argc, argv), current_view_(0),
1016 d(new GuiApplication::Private)
1018 QString app_name = "LyX";
1019 QCoreApplication::setOrganizationName(app_name);
1020 QCoreApplication::setOrganizationDomain("lyx.org");
1021 QCoreApplication::setApplicationName(lyx_package);
1022 #if QT_VERSION >= 0x050000
1023 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1026 qsrand(QDateTime::currentDateTime().toTime_t());
1028 // Install translator for GUI elements.
1029 installTranslator(&d->qt_trans_);
1032 // Enable reception of XCB events.
1033 installNativeEventFilter(this);
1036 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1037 // lyxrc setting for this in order to let the application stay resident.
1038 // But then we need some kind of dock icon, at least on Windows.
1040 if (lyxrc.quit_on_last_window_closed)
1041 setQuitOnLastWindowClosed(false);
1044 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1045 // seems to be the default case for applications like LyX.
1046 setQuitOnLastWindowClosed(false);
1047 // This allows to translate the strings that appear in the LyX menu.
1048 /// A translator suitable for the entries in the LyX menu.
1049 /// Only needed with Qt/Mac.
1050 installTranslator(new MenuTranslator(this));
1055 #if defined(Q_WS_X11) || defined(QPA_XCB)
1056 // doubleClickInterval() is 400 ms on X11 which is just too long.
1057 // On Windows and Mac OS X, the operating system's value is used.
1058 // On Microsoft Windows, calling this function sets the double
1059 // click interval for all applications. So we don't!
1060 QApplication::setDoubleClickInterval(300);
1063 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1065 // needs to be done before reading lyxrc
1067 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1071 // Set the cache to 5120 kilobytes which corresponds to screen size of
1072 // 1280 by 1024 pixels with a color depth of 32 bits.
1073 QPixmapCache::setCacheLimit(5120);
1075 // Initialize RC Fonts
1076 if (lyxrc.roman_font_name.empty())
1077 lyxrc.roman_font_name = fromqstr(romanFontName());
1079 if (lyxrc.sans_font_name.empty())
1080 lyxrc.sans_font_name = fromqstr(sansFontName());
1082 if (lyxrc.typewriter_font_name.empty())
1083 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1085 d->general_timer_.setInterval(500);
1086 connect(&d->general_timer_, SIGNAL(timeout()),
1087 this, SLOT(handleRegularEvents()));
1088 d->general_timer_.start();
1090 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1091 // This is clearly not enough in a time where we use threads for
1092 // document preview and/or export. 20 should be OK.
1093 QThreadPool::globalInstance()->setMaxThreadCount(20);
1095 // make sure tooltips are formatted
1096 installEventFilter(new ToolTipFormatter(this));
1100 GuiApplication * theGuiApp()
1102 return dynamic_cast<GuiApplication *>(theApp());
1106 double GuiApplication::pixelRatio() const
1108 #if QT_VERSION >= 0x050000
1109 return qt_scale_factor * devicePixelRatio();
1116 void GuiApplication::clearSession()
1123 docstring Application::iconName(FuncRequest const & f, bool unknown)
1125 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1129 docstring Application::mathIcon(docstring const & c)
1131 return qstring_to_ucs4(findImg(toqstr(c)));
1135 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1139 BufferView * bv = 0;
1140 BufferView * doc_bv = 0;
1142 if (cmd.action() == LFUN_NOACTION) {
1143 status.message(from_utf8(N_("Nothing to do")));
1144 status.setEnabled(false);
1147 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1148 status.setUnknown(true);
1149 status.message(from_utf8(N_("Unknown action")));
1150 status.setEnabled(false);
1153 // Does the GuiApplication know something?
1154 else if (getStatus(cmd, status)) { }
1156 // If we do not have a GuiView, then other functions are disabled
1157 else if (!current_view_)
1158 status.setEnabled(false);
1160 // Does the GuiView know something?
1161 else if (current_view_->getStatus(cmd, status)) { }
1163 // In LyX/Mac, when a dialog is open, the menus of the
1164 // application can still be accessed without giving focus to
1165 // the main window. In this case, we want to disable the menu
1166 // entries that are buffer or view-related.
1167 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1169 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1170 status.setEnabled(false);
1173 // If we do not have a BufferView, then other functions are disabled
1174 else if (!(bv = current_view_->currentBufferView()))
1175 status.setEnabled(false);
1177 // Does the current BufferView know something?
1178 else if (bv->getStatus(cmd, status)) { }
1180 // Does the current Buffer know something?
1181 else if (bv->buffer().getStatus(cmd, status)) { }
1183 // If we do not have a document BufferView, different from the
1184 // current BufferView, then other functions are disabled
1185 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1186 status.setEnabled(false);
1188 // Does the document Buffer know something?
1189 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1192 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1193 status.message(from_utf8(N_("Command not handled")));
1194 status.setEnabled(false);
1197 // the default error message if we disable the command
1198 if (!status.enabled() && status.message().empty())
1199 status.message(from_utf8(N_("Command disabled")));
1205 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1207 // I would really like to avoid having this switch and rather try to
1208 // encode this in the function itself.
1209 // -- And I'd rather let an inset decide which LFUNs it is willing
1210 // to handle (Andre')
1212 switch (cmd.action()) {
1214 // This could be used for the no-GUI version. The GUI version is handled in
1215 // GuiView::getStatus(). See above.
1217 case LFUN_BUFFER_WRITE:
1218 case LFUN_BUFFER_WRITE_AS: {
1219 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1220 enable = b && (b->isUnnamed() || !b->isClean());
1225 case LFUN_BOOKMARK_GOTO: {
1226 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1227 enable = theSession().bookmarks().isValid(num);
1231 case LFUN_BOOKMARK_CLEAR:
1232 enable = theSession().bookmarks().hasValid();
1235 // this one is difficult to get right. As a half-baked
1236 // solution, we consider only the first action of the sequence
1237 case LFUN_COMMAND_SEQUENCE: {
1238 // argument contains ';'-terminated commands
1239 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1240 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1241 func.setOrigin(cmd.origin());
1242 flag = getStatus(func);
1246 // we want to check if at least one of these is enabled
1247 case LFUN_COMMAND_ALTERNATIVES: {
1248 // argument contains ';'-terminated commands
1249 string arg = to_utf8(cmd.argument());
1250 while (!arg.empty()) {
1252 arg = split(arg, first, ';');
1253 FuncRequest func(lyxaction.lookupFunc(first));
1254 func.setOrigin(cmd.origin());
1255 flag = getStatus(func);
1256 // if this one is enabled, the whole thing is
1265 string name = to_utf8(cmd.argument());
1266 if (theTopLevelCmdDef().lock(name, func)) {
1267 func.setOrigin(cmd.origin());
1268 flag = getStatus(func);
1269 theTopLevelCmdDef().release(name);
1271 // catch recursion or unknown command
1272 // definition. all operations until the
1273 // recursion or unknown command definition
1274 // occurs are performed, so set the state to
1281 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1283 case LFUN_PREFERENCES_SAVE:
1284 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1285 case LFUN_DEBUG_LEVEL_SET:
1286 // these are handled in our dispatch()
1289 case LFUN_WINDOW_CLOSE:
1290 enable = d->views_.size() > 0;
1293 case LFUN_BUFFER_NEW:
1294 case LFUN_BUFFER_NEW_TEMPLATE:
1295 case LFUN_FILE_OPEN:
1296 case LFUN_HELP_OPEN:
1297 case LFUN_SCREEN_FONT_UPDATE:
1298 case LFUN_SET_COLOR:
1299 case LFUN_WINDOW_NEW:
1301 case LFUN_LYXRC_APPLY:
1302 case LFUN_COMMAND_PREFIX:
1304 case LFUN_META_PREFIX:
1305 case LFUN_RECONFIGURE:
1306 case LFUN_SERVER_GET_FILENAME:
1307 case LFUN_SERVER_NOTIFY:
1311 case LFUN_BUFFER_FORALL: {
1312 if (theBufferList().empty()) {
1313 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1314 flag.setEnabled(false);
1318 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1319 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1320 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1321 flag.setEnabled(false);
1326 case LFUN_DIALOG_SHOW: {
1327 string const name = cmd.getArg(0);
1328 return name == "aboutlyx"
1330 || name == "texinfo"
1331 || name == "progress"
1332 || name == "compare";
1340 flag.setEnabled(false);
1344 /// make a post-dispatch status message
1345 static docstring makeDispatchMessage(docstring const & msg,
1346 FuncRequest const & cmd)
1348 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1349 || cmd.origin() == FuncRequest::TOOLBAR
1350 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1352 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1353 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1357 docstring dispatch_msg = msg;
1358 if (!dispatch_msg.empty())
1359 dispatch_msg += ' ';
1361 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1363 bool argsadded = false;
1365 if (!cmd.argument().empty()) {
1366 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1367 comname += ' ' + cmd.argument();
1371 docstring const shortcuts = theTopLevelKeymap().
1372 printBindings(cmd, KeySequence::ForGui);
1374 if (!shortcuts.empty())
1375 comname += ": " + shortcuts;
1376 else if (!argsadded && !cmd.argument().empty())
1377 comname += ' ' + cmd.argument();
1379 if (!comname.empty()) {
1380 comname = rtrim(comname);
1381 dispatch_msg += '(' + rtrim(comname) + ')';
1383 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1384 return dispatch_msg;
1388 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1392 Buffer * buffer = 0;
1393 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1394 //setCurrentView(cmd.view_origin); //does not work
1396 dr.setMessage(_("Wrong focus!"));
1397 d->dispatch_result_ = dr;
1398 return d->dispatch_result_;
1400 if (current_view_ && current_view_->currentBufferView()) {
1401 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1402 buffer = ¤t_view_->currentBufferView()->buffer();
1404 // This handles undo groups automagically
1405 UndoGroupHelper ugh(buffer);
1407 // redraw the screen at the end (first of the two drawing steps).
1408 // This is done unless explicitly requested otherwise
1409 dr.screenUpdate(Update::FitCursor);
1411 updateCurrentView(cmd, dr);
1413 d->dispatch_result_ = dr;
1414 return d->dispatch_result_;
1418 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1423 BufferView * bv = current_view_->currentBufferView();
1425 if (dr.needBufferUpdate()) {
1426 bv->cursor().clearBufferUpdate();
1427 bv->buffer().updateBuffer();
1428 } else if (dr.needChangesUpdate()) {
1429 // updateBuffer() already updates the change-tracking presence flag
1430 bv->buffer().updateChangesPresent();
1432 // BufferView::update() updates the ViewMetricsInfo and
1433 // also initializes the position cache for all insets in
1434 // (at least partially) visible top-level paragraphs.
1435 // We will redraw the screen only if needed.
1436 bv->processUpdateFlags(dr.screenUpdate());
1438 // Do we have a selection?
1439 theSelection().haveSelection(bv->cursor().selection());
1442 current_view_->restartCaret();
1444 if (dr.needMessageUpdate()) {
1445 // Some messages may already be translated, so we cannot use _()
1446 current_view_->message(makeDispatchMessage(
1447 translateIfPossible(dr.message()), cmd));
1452 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1453 bool switchToBuffer)
1455 if (!theSession().bookmarks().isValid(idx))
1457 BookmarksSection::Bookmark const & bm =
1458 theSession().bookmarks().bookmark(idx);
1459 LASSERT(!bm.filename.empty(), return);
1460 string const file = bm.filename.absFileName();
1461 // if the file is not opened, open it.
1462 if (!theBufferList().exists(bm.filename)) {
1464 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1468 // open may fail, so we need to test it again
1469 if (!theBufferList().exists(bm.filename))
1472 // bm can be changed when saving
1473 BookmarksSection::Bookmark tmp = bm;
1475 // Special case idx == 0 used for back-from-back jump navigation
1477 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1479 // if the current buffer is not that one, switch to it.
1480 BufferView * doc_bv = current_view_ ?
1481 current_view_->documentBufferView() : 0;
1482 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1483 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1484 if (switchToBuffer) {
1485 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1488 doc_bv = current_view_->documentBufferView();
1493 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1494 if (!doc_bv || !doc_bv->moveToPosition(
1495 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1498 Cursor & cur = doc_bv->cursor();
1499 if (old && cur != *old)
1500 notifyCursorLeavesOrEnters(*old, cur);
1506 // Cursor jump succeeded!
1507 pit_type new_pit = cur.pit();
1508 pos_type new_pos = cur.pos();
1509 int new_id = cur.paragraph().id();
1511 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1512 // see http://www.lyx.org/trac/ticket/3092
1513 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1514 || bm.top_id != new_id) {
1515 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1516 new_pit, new_pos, new_id);
1520 // This function runs "configure" and then rereads lyx.defaults to
1521 // reconfigure the automatic settings.
1522 void GuiApplication::reconfigure(string const & option)
1524 // emit message signal.
1526 current_view_->message(_("Running configure..."));
1528 // Run configure in user lyx directory
1529 string const lock_file = package().getConfigureLockName();
1530 int fd = fileLock(lock_file.c_str());
1531 int const ret = package().reconfigureUserLyXDir(option);
1532 // emit message signal.
1534 current_view_->message(_("Reloading configuration..."));
1535 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1536 // Re-read packages.lst
1537 LaTeXPackages::getAvailable();
1538 fileUnlock(fd, lock_file.c_str());
1541 Alert::information(_("System reconfiguration failed"),
1542 _("The system reconfiguration has failed.\n"
1543 "Default textclass is used but LyX may\n"
1544 "not be able to work properly.\n"
1545 "Please reconfigure again if needed."));
1547 Alert::information(_("System reconfigured"),
1548 _("The system has been reconfigured.\n"
1549 "You need to restart LyX to make use of any\n"
1550 "updated document class specifications."));
1553 void GuiApplication::validateCurrentView()
1555 if (!d->views_.empty() && !current_view_) {
1556 // currently at least one view exists but no view has the focus.
1557 // choose the last view to make it current.
1558 // a view without any open document is preferred.
1559 GuiView * candidate = 0;
1560 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1561 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1562 for (; it != end; ++it) {
1564 if (!candidate->documentBufferView())
1567 setCurrentView(candidate);
1571 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1573 string const argument = to_utf8(cmd.argument());
1574 FuncCode const action = cmd.action();
1576 LYXERR(Debug::ACTION, "cmd: " << cmd);
1578 // we have not done anything wrong yet.
1581 FuncStatus const flag = getStatus(cmd);
1582 if (!flag.enabled()) {
1583 // We cannot use this function here
1584 LYXERR(Debug::ACTION, "action "
1585 << lyxaction.getActionName(action)
1586 << " [" << action << "] is disabled at this location");
1587 dr.setMessage(flag.message());
1589 dr.dispatched(false);
1590 dr.screenUpdate(Update::None);
1591 dr.clearBufferUpdate();
1595 if (cmd.origin() == FuncRequest::LYXSERVER) {
1596 if (current_view_ && current_view_->currentBufferView())
1597 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1598 // we will also need to redraw the screen at the end
1599 dr.screenUpdate(Update::FitCursor);
1602 // Assumes that the action will be dispatched.
1603 dr.dispatched(true);
1605 switch (cmd.action()) {
1607 case LFUN_WINDOW_NEW:
1608 createView(toqstr(cmd.argument()));
1611 case LFUN_WINDOW_CLOSE:
1612 // update bookmark pit of the current buffer before window close
1613 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1614 gotoBookmark(i+1, false, false);
1615 // clear the last opened list, because
1616 // maybe this will end the session
1617 theSession().lastOpened().clear();
1618 // check for valid current_view_
1619 validateCurrentView();
1621 current_view_->closeScheduled();
1625 // quitting is triggered by the gui code
1626 // (leaving the event loop).
1628 current_view_->message(from_utf8(N_("Exiting.")));
1629 if (closeAllViews())
1633 case LFUN_SCREEN_FONT_UPDATE: {
1634 // handle the screen font changes.
1635 d->font_loader_.update();
1636 dr.screenUpdate(Update::Force | Update::FitCursor);
1640 case LFUN_BUFFER_NEW:
1641 validateCurrentView();
1643 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1644 createView(QString(), false); // keep hidden
1645 current_view_->newDocument(to_utf8(cmd.argument()), false);
1646 current_view_->show();
1647 setActiveWindow(current_view_);
1649 current_view_->newDocument(to_utf8(cmd.argument()), false);
1653 case LFUN_BUFFER_NEW_TEMPLATE:
1654 validateCurrentView();
1656 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1658 current_view_->newDocument(to_utf8(cmd.argument()), true);
1659 if (!current_view_->documentBufferView())
1660 current_view_->close();
1662 current_view_->newDocument(to_utf8(cmd.argument()), true);
1666 case LFUN_FILE_OPEN: {
1667 // FIXME: normally the code below is not needed, since getStatus makes sure that
1668 // current_view_ is not null.
1669 validateCurrentView();
1670 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1671 string const fname = to_utf8(cmd.argument());
1672 bool const is_open = FileName::isAbsolute(fname)
1673 && theBufferList().getBuffer(FileName(fname));
1675 || (!lyxrc.open_buffers_in_tabs
1676 && current_view_->documentBufferView() != 0
1678 // We want the ui session to be saved per document and not per
1679 // window number. The filename crc is a good enough identifier.
1680 boost::crc_32_type crc;
1681 crc = for_each(fname.begin(), fname.end(), crc);
1682 createView(crc.checksum());
1683 current_view_->openDocument(fname);
1684 if (!current_view_->documentBufferView())
1685 current_view_->close();
1686 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1687 current_view_->raise();
1688 current_view_->activateWindow();
1689 current_view_->showNormal();
1692 current_view_->openDocument(fname);
1693 if (cmd.origin() == FuncRequest::LYXSERVER) {
1694 current_view_->raise();
1695 current_view_->activateWindow();
1696 current_view_->showNormal();
1702 case LFUN_HELP_OPEN: {
1703 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1704 if (current_view_ == 0)
1706 string const arg = to_utf8(cmd.argument());
1708 current_view_->message(_("Missing argument"));
1711 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1713 fname = i18nLibFileSearch("examples", arg, "lyx");
1715 if (fname.empty()) {
1716 lyxerr << "LyX: unable to find documentation file `"
1717 << arg << "'. Bad installation?" << endl;
1720 current_view_->message(bformat(_("Opening help file %1$s..."),
1721 makeDisplayPath(fname.absFileName())));
1722 Buffer * buf = current_view_->loadDocument(fname, false);
1724 buf->setReadonly(!current_view_->develMode());
1728 case LFUN_SET_COLOR: {
1730 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1731 if (lyx_name.empty() || x11_name.empty()) {
1733 current_view_->message(
1734 _("Syntax: set-color <lyx_name> <x11_name>"));
1739 // FIXME: The graphics cache no longer has a changeDisplay method.
1740 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1741 bool const graphicsbg_changed =
1742 lyx_name == graphicsbg && x11_name != graphicsbg;
1743 if (graphicsbg_changed)
1744 graphics::GCache::get().changeDisplay(true);
1747 if (!lcolor.setColor(lyx_name, x11_name)) {
1749 current_view_->message(
1750 bformat(_("Set-color \"%1$s\" failed "
1751 "- color is undefined or "
1752 "may not be redefined"),
1753 from_utf8(lyx_name)));
1756 // Make sure we don't keep old colors in cache.
1757 d->color_cache_.clear();
1758 // Update the current view
1759 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1763 case LFUN_LYXRC_APPLY: {
1764 // reset active key sequences, since the bindings
1765 // are updated (bug 6064)
1767 LyXRC const lyxrc_orig = lyxrc;
1769 istringstream ss(to_utf8(cmd.argument()));
1770 bool const success = lyxrc.read(ss);
1773 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1774 << "Unable to read lyxrc data"
1779 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1781 // If the request comes from the minibuffer, then we can't reset
1782 // the GUI, since that would destory the minibuffer itself and
1783 // cause a crash, since we are currently in one of the methods of
1784 // GuiCommandBuffer. See bug #8540.
1785 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1788 // FIXME Unfortunately, that leaves a bug here, since we cannot
1789 // reset the GUI in this case. If the changes to lyxrc affected the
1790 // UI, then, nothing would happen. This seems fairly unlikely, but
1791 // it definitely is a bug.
1796 case LFUN_COMMAND_PREFIX:
1797 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1802 d->meta_fake_bit = NoModifier;
1803 GuiView * gv = currentView();
1804 if (gv && gv->currentBufferView())
1805 // cancel any selection
1806 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1807 dr.setMessage(from_ascii(N_("Cancel")));
1810 case LFUN_META_PREFIX:
1811 d->meta_fake_bit = AltModifier;
1812 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1815 // --- Menus -----------------------------------------------
1816 case LFUN_RECONFIGURE:
1817 // argument is any additional parameter to the configure.py command
1818 reconfigure(to_utf8(cmd.argument()));
1821 // --- lyxserver commands ----------------------------
1822 case LFUN_SERVER_GET_FILENAME: {
1823 if (current_view_ && current_view_->documentBufferView()) {
1824 docstring const fname = from_utf8(
1825 current_view_->documentBufferView()->buffer().absFileName());
1826 dr.setMessage(fname);
1827 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1829 dr.setMessage(docstring());
1830 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1835 case LFUN_SERVER_NOTIFY: {
1836 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1837 dr.setMessage(dispatch_buffer);
1838 theServer().notifyClient(to_utf8(dispatch_buffer));
1842 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1843 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1849 string rest = split(argument, countstr, ' ');
1850 int const count = convert<int>(countstr);
1851 // an arbitrary number to limit number of iterations
1852 int const max_iter = 10000;
1853 if (count > max_iter) {
1854 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1857 for (int i = 0; i < count; ++i)
1858 dispatch(lyxaction.lookupFunc(rest));
1863 case LFUN_COMMAND_SEQUENCE: {
1864 // argument contains ';'-terminated commands
1865 string arg = argument;
1866 // FIXME: this LFUN should also work without any view.
1867 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1868 ? &(current_view_->documentBufferView()->buffer()) : 0;
1869 // This handles undo groups automagically
1870 UndoGroupHelper ugh(buffer);
1871 while (!arg.empty()) {
1873 arg = split(arg, first, ';');
1874 FuncRequest func(lyxaction.lookupFunc(first));
1875 func.setOrigin(cmd.origin());
1881 case LFUN_BUFFER_FORALL: {
1882 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1884 map<Buffer *, GuiView *> views_lVisible;
1885 map<GuiView *, Buffer *> activeBuffers;
1887 QList<GuiView *> allViews = d->views_.values();
1889 // this for does not modify any buffer. It just collects info on local
1890 // visibility of buffers and on which buffer is active in each view.
1891 Buffer * const last = theBufferList().last();
1892 for(GuiView * view : allViews) {
1893 // all of the buffers might be locally hidden. That is, there is no
1895 if (!view || !view->currentBufferView())
1896 activeBuffers[view] = 0;
1898 activeBuffers[view] = &view->currentBufferView()->buffer();
1900 // find out if each is locally visible or locally hidden.
1901 // we don't use a for loop as the buffer list cycles.
1902 Buffer * b = theBufferList().first();
1904 bool const locallyVisible = view && view->workArea(*b);
1905 if (locallyVisible) {
1906 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1907 // only need to overwrite/add if we don't already know a buffer is globally
1908 // visible or we do know but we would prefer to dispatch LFUN from the
1909 // current view because of cursor position issues.
1910 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1911 views_lVisible[b] = view;
1915 b = theBufferList().next(b);
1919 GuiView * const homeView = currentView();
1920 Buffer * b = theBufferList().first();
1921 Buffer * nextBuf = 0;
1922 int numProcessed = 0;
1925 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1927 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1929 // first change to a view where b is locally visible, preferably current_view_.
1930 GuiView * const vLv = views_lVisible[b];
1932 lyx::dispatch(funcToRun);
1940 // put things back to how they were (if possible).
1941 for (GuiView * view : allViews) {
1942 Buffer * originalBuf = activeBuffers[view];
1943 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1944 if (theBufferList().isLoaded(originalBuf))
1945 view->setBuffer(originalBuf);
1947 homeView->setFocus();
1949 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1953 case LFUN_COMMAND_ALTERNATIVES: {
1954 // argument contains ';'-terminated commands
1955 string arg = argument;
1956 while (!arg.empty()) {
1958 arg = split(arg, first, ';');
1959 FuncRequest func(lyxaction.lookupFunc(first));
1960 func.setOrigin(cmd.origin());
1961 FuncStatus const stat = getStatus(func);
1962 if (stat.enabled()) {
1972 if (theTopLevelCmdDef().lock(argument, func)) {
1973 func.setOrigin(cmd.origin());
1975 theTopLevelCmdDef().release(argument);
1977 if (func.action() == LFUN_UNKNOWN_ACTION) {
1978 // unknown command definition
1979 lyxerr << "Warning: unknown command definition `"
1983 // recursion detected
1984 lyxerr << "Warning: Recursion in the command definition `"
1985 << argument << "' detected"
1992 case LFUN_PREFERENCES_SAVE:
1993 lyxrc.write(support::makeAbsPath("preferences",
1994 package().user_support().absFileName()), false);
1997 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1998 string const fname = addName(addPath(package().user_support().absFileName(),
1999 "templates/"), "defaults.lyx");
2000 Buffer defaults(fname);
2002 istringstream ss(argument);
2007 // We need to make sure that, after we recreat the DocumentClass,
2008 // which we do in readHeader, we apply it to the document itself.
2009 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2010 int const unknown_tokens = defaults.readHeader(lex);
2011 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2013 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2014 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2016 if (unknown_tokens != 0) {
2017 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2018 << unknown_tokens << " unknown token"
2019 << (unknown_tokens == 1 ? "" : "s")
2023 if (defaults.writeFile(FileName(defaults.absFileName())))
2024 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2025 makeDisplayPath(fname)));
2028 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2033 case LFUN_BOOKMARK_GOTO:
2034 // go to bookmark, open unopened file and switch to buffer if necessary
2035 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2036 dr.screenUpdate(Update::Force | Update::FitCursor);
2039 case LFUN_BOOKMARK_CLEAR:
2040 theSession().bookmarks().clear();
2043 case LFUN_DEBUG_LEVEL_SET:
2044 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2047 case LFUN_DIALOG_SHOW: {
2048 string const name = cmd.getArg(0);
2050 if ( name == "aboutlyx"
2052 || name == "texinfo"
2053 || name == "progress"
2054 || name == "compare")
2056 // work around: on Mac OS the application
2057 // is not terminated when closing the last view.
2058 // Create a new one to be able to dispatch the
2059 // LFUN_DIALOG_SHOW to this view.
2060 if (current_view_ == 0)
2066 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2069 current_view_->dispatch(cmd, dr);
2073 if (cmd.origin() == FuncRequest::LYXSERVER)
2074 updateCurrentView(cmd, dr);
2078 docstring GuiApplication::viewStatusMessage()
2080 // When meta-fake key is pressed, show the key sequence so far + "M-".
2081 if (d->meta_fake_bit != NoModifier)
2082 return d->keyseq.print(KeySequence::ForGui) + "M-";
2084 // Else, when a non-complete key sequence is pressed,
2085 // show the available options.
2086 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2087 return d->keyseq.printOptions(true);
2093 void GuiApplication::handleKeyFunc(FuncCode action)
2097 if (d->keyseq.length())
2099 GuiView * gv = currentView();
2100 LASSERT(gv && gv->currentBufferView(), return);
2101 BufferView * bv = gv->currentBufferView();
2102 bv->getIntl().getTransManager().deadkey(
2103 c, get_accent(action).accent, bv->cursor().innerText(),
2105 // Need to clear, in case the minibuffer calls these
2108 // copied verbatim from do_accent_char
2109 bv->cursor().resetAnchor();
2113 //Keep this in sync with GuiApplication::processKeySym below
2114 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2115 KeyModifier state) const
2117 // Do nothing if we have nothing
2118 if (!keysym.isOK() || keysym.isModifier())
2120 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2122 FuncRequest func = seq.addkey(keysym, state);
2123 // When not cancel or meta-fake, do the normal lookup.
2124 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2126 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2128 // Maybe user can only reach the key via holding down shift.
2129 // Let's see. But only if shift is the only modifier
2130 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2131 // If addkey looked up a command and did not find further commands then
2132 // seq has been reset at this point
2133 func = seq.addkey(keysym, NoModifier);
2135 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2136 << seq.print(KeySequence::Portable) << ']');
2137 return func.action() != LFUN_UNKNOWN_ACTION;
2141 //Keep this in sync with GuiApplication::queryKeySym above
2142 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2144 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2146 // Do nothing if we have nothing (JMarc)
2147 if (!keysym.isOK() || keysym.isModifier()) {
2149 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2151 current_view_->restartCaret();
2155 char_type encoded_last_key = keysym.getUCSEncoded();
2157 // Do a one-deep top-level lookup for
2158 // cancel and meta-fake keys. RVDK_PATCH_5
2159 d->cancel_meta_seq.reset();
2161 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2162 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2164 // When not cancel or meta-fake, do the normal lookup.
2165 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2166 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2167 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2168 // remove Caps Lock and Mod2 as a modifiers
2169 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2170 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2173 // Dont remove this unless you know what you are doing.
2174 d->meta_fake_bit = NoModifier;
2176 // Can this happen now ?
2177 if (func.action() == LFUN_NOACTION)
2178 func = FuncRequest(LFUN_COMMAND_PREFIX);
2180 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2181 << d->keyseq.print(KeySequence::Portable) << ']');
2183 // already here we know if it any point in going further
2184 // why not return already here if action == -1 and
2185 // num_bytes == 0? (Lgb)
2187 if (d->keyseq.length() > 1 && current_view_)
2188 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2191 // Maybe user can only reach the key via holding down shift.
2192 // Let's see. But only if shift is the only modifier
2193 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2194 LYXERR(Debug::KEY, "Trying without shift");
2195 // If addkey looked up a command and did not find further commands then
2196 // seq has been reset at this point
2197 func = d->keyseq.addkey(keysym, NoModifier);
2198 LYXERR(Debug::KEY, "Action now " << func.action());
2201 if (func.action() == LFUN_UNKNOWN_ACTION) {
2202 // We didn't match any of the key sequences.
2203 // See if it's normal insertable text not already
2204 // covered by a binding
2205 if (keysym.isText() && d->keyseq.length() == 1) {
2206 // Non-printable characters (such as ASCII control characters)
2207 // must not be inserted (#5704)
2208 if (!isPrintable(encoded_last_key)) {
2209 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2211 current_view_->restartCaret();
2214 // The following modifier check is not needed on Mac.
2215 // The keysym is either not text or it is different
2216 // from the non-modifier keysym. See #9875 for the
2217 // broken alt-modifier effect of having this code active.
2218 #if !defined(Q_OS_MAC)
2219 // If a non-Shift Modifier is used we have a non-bound key sequence
2220 // (such as Alt+j = j). This should be omitted (#5575).
2221 // On Windows, AltModifier and ControlModifier are both
2222 // set when AltGr is pressed. Therefore, in order to not
2223 // break AltGr-bound symbols (see #5575 for details),
2224 // unbound Ctrl+Alt key sequences are allowed.
2225 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2226 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2227 && !(state & AltModifier && state & ControlModifier)
2231 if (current_view_) {
2232 current_view_->message(_("Unknown function."));
2233 current_view_->restartCaret();
2238 // Since all checks above were passed, we now really have text that
2239 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2240 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2242 LYXERR(Debug::KEY, "isText() is true, inserting.");
2243 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2245 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2246 if (current_view_) {
2247 current_view_->message(_("Unknown function."));
2248 current_view_->restartCaret();
2254 if (func.action() == LFUN_SELF_INSERT) {
2255 if (encoded_last_key != 0) {
2256 docstring const arg(1, encoded_last_key);
2257 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2258 FuncRequest::KEYBOARD));
2259 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2262 processFuncRequest(func);
2266 void GuiApplication::processFuncRequest(FuncRequest const & func)
2268 lyx::dispatch(func);
2272 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2274 addToFuncRequestQueue(func);
2275 processFuncRequestQueueAsync();
2279 void GuiApplication::processFuncRequestQueue()
2281 while (!d->func_request_queue_.empty()) {
2282 // take the item from the stack _before_ processing the
2283 // request in order to avoid race conditions from nested
2284 // or parallel requests (see #10406)
2285 FuncRequest const fr(d->func_request_queue_.front());
2286 d->func_request_queue_.pop();
2287 processFuncRequest(fr);
2292 void GuiApplication::processFuncRequestQueueAsync()
2294 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2298 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2300 d->func_request_queue_.push(func);
2304 void GuiApplication::resetGui()
2306 // Set the language defined by the user.
2310 if (!readUIFile(toqstr(lyxrc.ui_file)))
2311 // Gives some error box here.
2314 if (d->global_menubar_)
2315 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2317 QHash<int, GuiView *>::iterator it;
2318 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2321 gv->setLayoutDirection(layoutDirection());
2325 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2329 void GuiApplication::createView(int view_id)
2331 createView(QString(), true, view_id);
2335 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2338 // release the keyboard which might have been grabed by the global
2339 // menubar on Mac to catch shortcuts even without any GuiView.
2340 if (d->global_menubar_)
2341 d->global_menubar_->releaseKeyboard();
2345 while (d->views_.find(id) != d->views_.end())
2348 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2349 GuiView * view = new GuiView(id);
2350 // `view' is the new current_view_. Tell coverity that is is not 0.
2351 LATTEST(current_view_);
2353 d->views_[id] = view;
2357 setActiveWindow(view);
2360 if (!geometry_arg.isEmpty()) {
2361 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2365 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2366 re.indexIn(geometry_arg);
2367 w = re.cap(1).toInt();
2368 h = re.cap(2).toInt();
2369 x = re.cap(3).toInt();
2370 y = re.cap(4).toInt();
2371 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2372 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2373 // Set initial geometry such that we can get the frame size.
2374 view->setGeometry(x, y, w, h);
2375 int framewidth = view->geometry().x() - view->x();
2376 int titleheight = view->geometry().y() - view->y();
2377 // Negative displacements must be interpreted as distances
2378 // from the right or bottom screen borders.
2379 if (sx == '-' || sy == '-') {
2380 QRect rec = QApplication::desktop()->screenGeometry();
2382 x += rec.width() - w - framewidth;
2384 y += rec.height() - h - titleheight;
2385 view->setGeometry(x, y, w, h);
2387 // Make sure that the left and top frame borders are visible.
2388 if (view->x() < 0 || view->y() < 0) {
2393 view->setGeometry(x, y, w, h);
2401 bool GuiApplication::unhide(Buffer * buf)
2405 currentView()->setBuffer(buf, false);
2410 Clipboard & GuiApplication::clipboard()
2412 return d->clipboard_;
2416 Selection & GuiApplication::selection()
2418 return d->selection_;
2422 FontLoader & GuiApplication::fontLoader()
2424 return d->font_loader_;
2428 Toolbars const & GuiApplication::toolbars() const
2430 return d->toolbars_;
2434 Toolbars & GuiApplication::toolbars()
2436 return d->toolbars_;
2440 Menus const & GuiApplication::menus() const
2446 Menus & GuiApplication::menus()
2452 QList<int> GuiApplication::viewIds() const
2454 return d->views_.keys();
2458 ColorCache & GuiApplication::colorCache()
2460 return d->color_cache_;
2464 int GuiApplication::exec()
2466 // asynchronously handle batch commands. This event will be in
2467 // the event queue in front of other asynchronous events. Hence,
2468 // we can assume in the latter that the gui is setup already.
2469 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2471 return QApplication::exec();
2475 void GuiApplication::exit(int status)
2477 QApplication::exit(status);
2481 void GuiApplication::setGuiLanguage()
2485 // install translation file for Qt built-in dialogs
2486 QString const language_name = QString("qt_") + theLocale.name();
2487 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2488 // Short-named translator can be loaded from a long name, but not the
2489 // opposite. Therefore, long name should be used without truncation.
2490 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2491 if (!d->qt_trans_.load(language_name,
2492 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2493 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2496 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2500 switch (theLocale.language()) {
2501 case QLocale::Arabic :
2502 case QLocale::Hebrew :
2503 case QLocale::Persian :
2504 case QLocale::Urdu :
2505 setLayoutDirection(Qt::RightToLeft);
2508 setLayoutDirection(Qt::LeftToRight);
2513 void GuiApplication::execBatchCommands()
2518 if (!readUIFile(toqstr(lyxrc.ui_file)))
2519 // Gives some error box here.
2523 #if QT_VERSION > 0x040600
2524 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2526 #if QT_VERSION > 0x050100
2527 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2529 // Create the global default menubar which is shown for the dialogs
2530 // and if no GuiView is visible.
2531 // This must be done after the session was recovered to know the "last files".
2532 d->global_menubar_ = new QMenuBar(0);
2533 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2536 lyx::execBatchCommands();
2540 QAbstractItemModel * GuiApplication::languageModel()
2542 if (d->language_model_)
2543 return d->language_model_;
2545 QStandardItemModel * lang_model = new QStandardItemModel(this);
2546 lang_model->insertColumns(0, 3);
2547 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2548 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2549 Languages::const_iterator it = lyx::languages.begin();
2550 Languages::const_iterator end = lyx::languages.end();
2551 for (; it != end; ++it) {
2552 int current_row = lang_model->rowCount();
2553 lang_model->insertRows(current_row, 1);
2554 QModelIndex pl_item = lang_model->index(current_row, 0);
2555 QModelIndex sp_item = lang_model->index(current_row, 1);
2556 QModelIndex th_item = lang_model->index(current_row, 2);
2557 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2558 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2559 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2560 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2561 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2562 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2563 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2564 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2565 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2566 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2568 d->language_model_ = new QSortFilterProxyModel(this);
2569 d->language_model_->setSourceModel(lang_model);
2570 d->language_model_->setSortLocaleAware(true);
2571 return d->language_model_;
2575 void GuiApplication::restoreGuiSession()
2577 if (!lyxrc.load_session)
2580 Session & session = theSession();
2581 LastOpenedSection::LastOpened const & lastopened =
2582 session.lastOpened().getfiles();
2584 validateCurrentView();
2586 FileName active_file;
2587 // do not add to the lastfile list since these files are restored from
2588 // last session, and should be already there (regular files), or should
2589 // not be added at all (help files).
2590 for (size_t i = 0; i < lastopened.size(); ++i) {
2591 FileName const & file_name = lastopened[i].file_name;
2592 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2593 && current_view_->documentBufferView() != 0)) {
2594 boost::crc_32_type crc;
2595 string const & fname = file_name.absFileName();
2596 crc = for_each(fname.begin(), fname.end(), crc);
2597 createView(crc.checksum());
2599 current_view_->loadDocument(file_name, false);
2601 if (lastopened[i].active)
2602 active_file = file_name;
2605 // Restore last active buffer
2606 Buffer * buffer = theBufferList().getBuffer(active_file);
2607 if (buffer && current_view_)
2608 current_view_->setBuffer(buffer);
2610 // clear this list to save a few bytes of RAM
2611 session.lastOpened().clear();
2615 QString const GuiApplication::romanFontName()
2618 font.setStyleHint(QFont::Serif);
2619 font.setFamily("serif");
2621 return QFontInfo(font).family();
2625 QString const GuiApplication::sansFontName()
2628 font.setStyleHint(QFont::SansSerif);
2629 font.setFamily("sans");
2631 return QFontInfo(font).family();
2635 QString const GuiApplication::typewriterFontName()
2637 return QFontInfo(typewriterSystemFont()).family();
2642 // We cannot use QFont::fixedPitch() because it doesn't
2643 // return the fact but only if it is requested.
2644 static bool isFixedPitch(const QFont & font) {
2645 const QFontInfo fi(font);
2646 return fi.fixedPitch();
2651 QFont const GuiApplication::typewriterSystemFont()
2653 #if QT_VERSION >= 0x050200
2654 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2656 QFont font("monospace");
2658 if (!isFixedPitch(font)) {
2659 // try to enforce a real monospaced font
2660 font.setStyleHint(QFont::Monospace);
2661 if (!isFixedPitch(font)) {
2662 font.setStyleHint(QFont::TypeWriter);
2663 if (!isFixedPitch(font)) font.setFamily("courier");
2667 // On a Mac the result is too small and it's not practical to
2668 // rely on Qtconfig utility to change the system settings of Qt.
2669 font.setPointSize(12);
2675 void GuiApplication::handleRegularEvents()
2677 ForkedCallsController::handleCompletedProcesses();
2681 bool GuiApplication::event(QEvent * e)
2684 case QEvent::FileOpen: {
2685 // Open a file; this happens only on Mac OS X for now.
2687 // We do this asynchronously because on startup the batch
2688 // commands are not executed here yet and the gui is not ready
2690 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2691 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2692 processFuncRequestAsync(fr);
2697 return QApplication::event(e);
2702 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2705 return QApplication::notify(receiver, event);
2707 catch (ExceptionMessage const & e) {
2709 case ErrorException:
2711 setQuitOnLastWindowClosed(false);
2713 Alert::error(e.title_, e.details_);
2715 // Properly crash in debug mode in order to get a useful backtrace.
2718 // In release mode, try to exit gracefully.
2720 // FIXME: GCC 7 thinks we can fall through here. Can we?
2722 case BufferException: {
2723 if (!current_view_ || !current_view_->documentBufferView())
2725 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2726 docstring details = e.details_ + '\n';
2727 details += buf->emergencyWrite();
2728 theBufferList().release(buf);
2729 details += "\n" + _("The current document was closed.");
2730 Alert::error(e.title_, details);
2733 case WarningException:
2734 Alert::warning(e.title_, e.details_);
2738 catch (exception const & e) {
2739 docstring s = _("LyX has caught an exception, it will now "
2740 "attempt to save all unsaved documents and exit."
2742 s += from_ascii(e.what());
2743 Alert::error(_("Software exception Detected"), s);
2747 docstring s = _("LyX has caught some really weird exception, it will "
2748 "now attempt to save all unsaved documents and exit.");
2749 Alert::error(_("Software exception Detected"), s);
2757 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2759 QColor const & qcol = d->color_cache_.get(col);
2760 if (!qcol.isValid()) {
2766 rgbcol.r = qcol.red();
2767 rgbcol.g = qcol.green();
2768 rgbcol.b = qcol.blue();
2773 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2775 QColor const qcol(lcolor.getX11Name(col).c_str());
2776 if (!qcol.isValid()) {
2782 rgbcol.r = qcol.red();
2783 rgbcol.g = qcol.green();
2784 rgbcol.b = qcol.blue();
2789 string const GuiApplication::hexName(ColorCode col)
2791 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2795 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2797 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2798 d->socket_notifiers_[fd] = sn;
2799 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2803 void GuiApplication::socketDataReceived(int fd)
2805 d->socket_notifiers_[fd]->func_();
2809 void GuiApplication::unregisterSocketCallback(int fd)
2811 d->socket_notifiers_.take(fd)->setEnabled(false);
2815 void GuiApplication::commitData(QSessionManager & sm)
2817 /** The implementation is required to avoid an application exit
2818 ** when session state save is triggered by session manager.
2819 ** The default implementation sends a close event to all
2820 ** visible top level widgets when session managment allows
2822 ** We are changing that to check the state of each buffer in all
2823 ** views and ask the users what to do if buffers are dirty.
2824 ** Furthermore, we save the session state.
2825 ** We do NOT close the views here since the user still can cancel
2826 ** the logout process (see #9277); also, this would hide LyX from
2827 ** an OSes own session handling (application restoration).
2829 #ifdef QT_NO_SESSIONMANAGER
2831 #warning Qt is compiled without session manager
2833 #pragma message("warning: Qt is compiled without session manager")
2837 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2845 void GuiApplication::unregisterView(GuiView * gv)
2847 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2848 d->views_.remove(gv->id());
2849 if (current_view_ == gv)
2855 bool GuiApplication::closeAllViews()
2857 if (d->views_.empty())
2860 // When a view/window was closed before without quitting LyX, there
2861 // are already entries in the lastOpened list.
2862 theSession().lastOpened().clear();
2864 QList<GuiView *> const views = d->views_.values();
2865 for (GuiView * view : views) {
2866 if (!view->closeScheduled())
2875 bool GuiApplication::prepareAllViewsForLogout()
2877 if (d->views_.empty())
2880 QList<GuiView *> const views = d->views_.values();
2881 for (GuiView * view : views) {
2882 if (!view->prepareAllBuffersForLogout())
2890 GuiView & GuiApplication::view(int id) const
2892 LAPPERR(d->views_.contains(id));
2893 return *d->views_.value(id);
2897 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2899 QList<GuiView *> const views = d->views_.values();
2900 for (GuiView * view : views)
2901 view->hideDialog(name, inset);
2905 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2907 Buffer const * buffer_ = 0;
2908 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2909 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2910 if (Buffer const * ptr = (*it)->updateInset(inset))
2917 bool GuiApplication::searchMenu(FuncRequest const & func,
2918 docstring_list & names) const
2920 return d->menus_.searchMenu(func, names);
2924 // Ensure that a file is read only once (prevents include loops)
2925 static QStringList uifiles;
2926 // store which ui files define Toolbars
2927 static QStringList toolbar_uifiles;
2930 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2941 LexerKeyword uitags[] = {
2942 { "format", ui_format },
2943 { "include", ui_include },
2944 { "menuset", ui_menuset },
2945 { "toolbars", ui_toolbars },
2946 { "toolbarset", ui_toolbarset }
2950 lex.setFile(ui_path);
2952 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2956 if (lyxerr.debugging(Debug::PARSER))
2957 lex.printTable(lyxerr);
2960 // format before introduction of format tag
2961 unsigned int format = 0;
2962 while (lex.isOK()) {
2963 int const status = lex.lex();
2965 // we have to do this check here, outside the switch,
2966 // because otherwise we would start reading include files,
2967 // e.g., if the first tag we hit was an include tag.
2968 if (status == ui_format)
2970 format = lex.getInteger();
2974 // this will trigger unless the first tag we hit is a format
2975 // tag, with the right format.
2976 if (format != LFUN_FORMAT)
2977 return FormatMismatch;
2980 case Lexer::LEX_FEOF:
2985 QString const file = toqstr(lex.getString());
2986 bool const success = readUIFile(file, true);
2988 LYXERR0("Failed to read included file: " << fromqstr(file));
2995 d->menus_.read(lex);
2999 d->toolbars_.readToolbars(lex);
3003 d->toolbars_.readToolbarSettings(lex);
3004 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3008 if (!rtrim(lex.getString()).empty())
3009 lex.printError("LyX::ReadUIFile: "
3010 "Unknown menu tag: `$$Token'");
3012 LYXERR0("Error with status: " << status);
3018 return (error ? ReadError : ReadOK);
3022 bool GuiApplication::readUIFile(QString const & name, bool include)
3024 LYXERR(Debug::INIT, "About to read " << name << "...");
3028 ui_path = libFileSearch("ui", name, "inc");
3029 if (ui_path.empty())
3030 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3032 ui_path = libFileSearch("ui", name, "ui");
3035 if (ui_path.empty()) {
3036 static const QString defaultUIFile = "default";
3037 LYXERR(Debug::INIT, "Could not find " << name);
3039 Alert::warning(_("Could not find UI definition file"),
3040 bformat(_("Error while reading the included file\n%1$s\n"
3041 "Please check your installation."), qstring_to_ucs4(name)));
3044 if (name == defaultUIFile) {
3045 LYXERR(Debug::INIT, "Could not find default UI file!!");
3046 Alert::warning(_("Could not find default UI file"),
3047 _("LyX could not find the default UI file!\n"
3048 "Please check your installation."));
3051 Alert::warning(_("Could not find UI definition file"),
3052 bformat(_("Error while reading the configuration file\n%1$s\n"
3053 "Falling back to default.\n"
3054 "Please look under Tools>Preferences>User Interface and\n"
3055 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3056 return readUIFile(defaultUIFile, false);
3059 QString const uifile = toqstr(ui_path.absFileName());
3060 if (uifiles.contains(uifile)) {
3062 // We are reading again the top uifile so reset the safeguard:
3065 d->toolbars_.reset();
3067 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3068 << "Is this an include loop?");
3072 uifiles.push_back(uifile);
3074 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3076 ReturnValues retval = readUIFile(ui_path);
3078 if (retval == FormatMismatch) {
3079 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3080 TempFile tmp("convertXXXXXX.ui");
3081 FileName const tempfile = tmp.name();
3082 bool const success = prefs2prefs(ui_path, tempfile, true);
3084 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3085 " to format " << LFUN_FORMAT << ".");
3087 retval = readUIFile(tempfile);
3091 if (retval != ReadOK) {
3092 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3100 settings.beginGroup("ui_files");
3101 bool touched = false;
3102 for (int i = 0; i != uifiles.size(); ++i) {
3103 QFileInfo fi(uifiles[i]);
3104 QDateTime const date_value = fi.lastModified();
3105 QString const name_key = QString::number(i);
3106 // if an ui file which defines Toolbars has changed,
3107 // we have to reset the settings
3108 if (toolbar_uifiles.contains(uifiles[i])
3109 && (!settings.contains(name_key)
3110 || settings.value(name_key).toString() != uifiles[i]
3111 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3113 settings.setValue(name_key, uifiles[i]);
3114 settings.setValue(name_key + "/date", date_value);
3117 settings.endGroup();
3119 settings.remove("views");
3125 void GuiApplication::onLastWindowClosed()
3127 if (d->global_menubar_)
3128 d->global_menubar_->grabKeyboard();
3132 void GuiApplication::startLongOperation() {
3133 d->key_checker_.start();
3137 bool GuiApplication::longOperationCancelled() {
3138 return d->key_checker_.pressed();
3142 void GuiApplication::stopLongOperation() {
3143 d->key_checker_.stop();
3147 bool GuiApplication::longOperationStarted() {
3148 return d->key_checker_.started();
3152 ////////////////////////////////////////////////////////////////////////
3154 // X11 specific stuff goes here...
3157 bool GuiApplication::x11EventFilter(XEvent * xev)
3162 switch (xev->type) {
3163 case SelectionRequest: {
3164 if (xev->xselectionrequest.selection != XA_PRIMARY)
3166 LYXERR(Debug::SELECTION, "X requested selection.");
3167 BufferView * bv = current_view_->currentBufferView();
3169 docstring const sel = bv->requestSelection();
3171 d->selection_.put(sel);
3172 // Refresh the selection request timestamp.
3173 // We have to do this by ourselves as Qt seems
3174 // not doing that, maybe because of our
3175 // "persistent selection" implementation
3176 // (see comments in GuiSelection.cpp).
3177 XSelectionEvent nev;
3178 nev.type = SelectionNotify;
3179 nev.display = xev->xselectionrequest.display;
3180 nev.requestor = xev->xselectionrequest.requestor;
3181 nev.selection = xev->xselectionrequest.selection;
3182 nev.target = xev->xselectionrequest.target;
3183 nev.property = 0L; // None
3184 nev.time = CurrentTime;
3185 XSendEvent(QX11Info::display(),
3186 nev.requestor, False, 0,
3187 reinterpret_cast<XEvent *>(&nev));
3193 case SelectionClear: {
3194 if (xev->xselectionclear.selection != XA_PRIMARY)
3196 LYXERR(Debug::SELECTION, "Lost selection.");
3197 BufferView * bv = current_view_->currentBufferView();
3199 bv->clearSelection();
3205 #elif defined(QPA_XCB)
3206 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3207 void * message, long *)
3209 if (!current_view_ || eventType != "xcb_generic_event_t")
3212 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3214 switch (ev->response_type) {
3215 case XCB_SELECTION_REQUEST: {
3216 xcb_selection_request_event_t * srev =
3217 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3218 if (srev->selection != XCB_ATOM_PRIMARY)
3220 LYXERR(Debug::SELECTION, "X requested selection.");
3221 BufferView * bv = current_view_->currentBufferView();
3223 docstring const sel = bv->requestSelection();
3225 d->selection_.put(sel);
3226 #ifdef HAVE_QT5_X11_EXTRAS
3227 // Refresh the selection request timestamp.
3228 // We have to do this by ourselves as Qt seems
3229 // not doing that, maybe because of our
3230 // "persistent selection" implementation
3231 // (see comments in GuiSelection.cpp).
3232 xcb_selection_notify_event_t nev;
3233 nev.response_type = XCB_SELECTION_NOTIFY;
3234 nev.requestor = srev->requestor;
3235 nev.selection = srev->selection;
3236 nev.target = srev->target;
3237 nev.property = XCB_NONE;
3238 nev.time = XCB_CURRENT_TIME;
3239 xcb_connection_t * con = QX11Info::connection();
3240 xcb_send_event(con, 0, srev->requestor,
3241 XCB_EVENT_MASK_NO_EVENT,
3242 reinterpret_cast<char const *>(&nev));
3250 case XCB_SELECTION_CLEAR: {
3251 xcb_selection_clear_event_t * scev =
3252 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3253 if (scev->selection != XCB_ATOM_PRIMARY)
3255 LYXERR(Debug::SELECTION, "Lost selection.");
3256 BufferView * bv = current_view_->currentBufferView();
3258 bv->clearSelection();
3266 } // namespace frontend
3269 void hideDialogs(std::string const & name, Inset * inset)
3272 frontend::guiApp->hideDialogs(name, inset);
3276 ////////////////////////////////////////////////////////////////////
3280 ////////////////////////////////////////////////////////////////////
3282 frontend::FontLoader & theFontLoader()
3284 LAPPERR(frontend::guiApp);
3285 return frontend::guiApp->fontLoader();
3289 frontend::FontMetrics const & theFontMetrics(Font const & f)
3291 return theFontMetrics(f.fontInfo());
3295 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3297 LAPPERR(frontend::guiApp);
3298 return frontend::guiApp->fontLoader().metrics(f);
3302 ////////////////////////////////////////////////////////////////////
3306 ////////////////////////////////////////////////////////////////////
3308 frontend::Clipboard & theClipboard()
3310 LAPPERR(frontend::guiApp);
3311 return frontend::guiApp->clipboard();
3315 frontend::Selection & theSelection()
3317 LAPPERR(frontend::guiApp);
3318 return frontend::guiApp->selection();
3324 #include "moc_GuiApplication.cpp"