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>
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 ////////////////////////////////////////////////////////////////////////
668 // Mac specific stuff goes here...
670 ////////////////////////////////////////////////////////////////////////
672 class MenuTranslator : public QTranslator
675 MenuTranslator(QObject * parent)
676 : QTranslator(parent)
679 #if QT_VERSION >= 0x050000
680 virtual QString translate(const char * /* context */,
681 const char *sourceText,
682 const char * /* disambiguation */ = 0, int /* n */ = -1) const
684 QString translate(const char * /*context*/,
685 const char * sourceText,
686 const char * /*comment*/ = 0) const
689 string const s = sourceText;
690 if (s == N_("About %1") || s == N_("Preferences")
691 || s == N_("Reconfigure") || s == N_("Quit %1"))
699 // QMacPasteboardMimeGraphics can only be compiled on Mac.
701 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
704 QMacPasteboardMimeGraphics()
705 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
708 QString convertorName() { return "Graphics"; }
710 QString flavorFor(QString const & mime)
712 LYXERR(Debug::ACTION, "flavorFor " << mime);
713 if (mime == pdfMimeType())
714 return QLatin1String("com.adobe.pdf");
718 QString mimeFor(QString flav)
720 LYXERR(Debug::ACTION, "mimeFor " << flav);
721 if (flav == QLatin1String("com.adobe.pdf"))
722 return pdfMimeType();
726 bool canConvert(QString const & mime, QString flav)
728 return mimeFor(flav) == mime;
731 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
735 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
739 QList<QByteArray> convertFromMime(QString const & /*mime*/,
740 QVariant data, QString /*flav*/)
742 QList<QByteArray> ret;
743 ret.append(data.toByteArray());
749 ///////////////////////////////////////////////////////////////
751 // You can find more platform specific stuff at the end of this file...
753 ///////////////////////////////////////////////////////////////
755 ////////////////////////////////////////////////////////////////////////
756 // Windows specific stuff goes here...
758 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
759 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
760 // QWindowsMimeMetafile can only be compiled on Windows.
762 static FORMATETC cfFromMime(QString const & mimetype)
765 if (mimetype == emfMimeType()) {
766 formatetc.cfFormat = CF_ENHMETAFILE;
767 formatetc.tymed = TYMED_ENHMF;
768 } else if (mimetype == wmfMimeType()) {
769 formatetc.cfFormat = CF_METAFILEPICT;
770 formatetc.tymed = TYMED_MFPICT;
773 formatetc.dwAspect = DVASPECT_CONTENT;
774 formatetc.lindex = -1;
779 class QWindowsMimeMetafile : public QWINDOWSMIME {
781 QWindowsMimeMetafile() {}
783 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
784 QMimeData const * /*mimedata*/) const
789 bool canConvertToMime(QString const & mimetype,
790 IDataObject * pDataObj) const
792 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
794 FORMATETC formatetc = cfFromMime(mimetype);
795 return pDataObj->QueryGetData(&formatetc) == S_OK;
798 bool convertFromMime(FORMATETC const & /*formatetc*/,
799 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
804 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
805 QVariant::Type /*preferredType*/) const
808 if (!canConvertToMime(mimetype, pDataObj))
811 FORMATETC formatetc = cfFromMime(mimetype);
813 if (pDataObj->GetData(&formatetc, &s) != S_OK)
817 if (s.tymed == TYMED_ENHMF) {
818 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
819 data.resize(dataSize);
820 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
821 (LPBYTE)data.data());
822 } else if (s.tymed == TYMED_MFPICT) {
823 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
824 data.resize(dataSize);
825 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
826 (LPBYTE)data.data());
829 ReleaseStgMedium(&s);
835 QVector<FORMATETC> formatsForMime(QString const & mimetype,
836 QMimeData const * /*mimedata*/) const
838 QVector<FORMATETC> formats;
839 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
840 formats += cfFromMime(mimetype);
844 QString mimeForFormat(FORMATETC const & formatetc) const
846 switch (formatetc.cfFormat) {
848 return emfMimeType();
849 case CF_METAFILEPICT:
850 return wmfMimeType();
860 /// Allows to check whether ESC was pressed during a long operation
861 class KeyChecker : public QObject {
866 KeyChecker() : pressed_(false), started_(false) {}
869 QCoreApplication::instance()->installEventFilter(this);
874 QCoreApplication::instance()->removeEventFilter(this);
878 QCoreApplication::processEvents();
881 bool started() const {
884 bool eventFilter(QObject *obj, QEvent *event) {
885 LYXERR(Debug::ACTION, "Event Type: " << event->type());
886 switch (event->type()) {
890 case QEvent::UpdateRequest:
891 case QEvent::CursorChange:
892 case QEvent::ActionChanged:
893 case QEvent::EnabledChange:
894 case QEvent::SockAct:
897 case QEvent::ToolTipChange:
898 case QEvent::LayoutRequest:
899 case QEvent::MetaCall:
900 return QObject::eventFilter(obj, event);
902 // FIXME Blocking all these events is a bad idea.
903 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
904 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
912 ////////////////////////////////////////////////////////////////////////
913 // GuiApplication::Private definition and implementation.
914 ////////////////////////////////////////////////////////////////////////
916 struct GuiApplication::Private
918 Private(): language_model_(0), meta_fake_bit(NoModifier),
921 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
922 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
923 /// WMF Mime handler for Windows clipboard.
924 wmf_mime_ = new QWindowsMimeMetafile;
927 initKeySequences(&theTopLevelKeymap());
930 void initKeySequences(KeyMap * kb)
932 keyseq = KeySequence(kb, kb);
933 cancel_meta_seq = KeySequence(kb, kb);
937 QSortFilterProxyModel * language_model_;
939 GuiClipboard clipboard_;
941 GuiSelection selection_;
943 FontLoader font_loader_;
945 ColorCache color_cache_;
947 QTranslator qt_trans_;
949 QHash<int, SocketNotifier *> socket_notifiers_;
953 /// The global instance
956 /// this timer is used for any regular events one wants to
957 /// perform. at present it is used to check if forked processes
959 QTimer general_timer_;
961 /// delayed FuncRequests
962 std::queue<FuncRequest> func_request_queue_;
967 KeySequence cancel_meta_seq;
969 KeyModifier meta_fake_bit;
971 /// The result of last dispatch action
972 DispatchResult dispatch_result_;
974 /// Multiple views container.
976 * Warning: This must not be a smart pointer as the destruction of the
977 * object is handled by Qt when the view is closed
978 * \sa Qt::WA_DeleteOnClose attribute.
980 QHash<int, GuiView *> views_;
982 /// Only used on mac.
983 QMenuBar * global_menubar_;
986 /// Linkback mime handler for MacOSX.
987 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
990 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
991 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
992 /// WMF Mime handler for Windows clipboard.
993 QWindowsMimeMetafile * wmf_mime_;
997 /// Allows to check whether ESC was pressed during a long operation
998 KeyChecker key_checker_;
1002 GuiApplication * guiApp;
1004 GuiApplication::~GuiApplication()
1007 closeAllLinkBackLinks();
1013 GuiApplication::GuiApplication(int & argc, char ** argv)
1014 : QApplication(argc, argv), current_view_(0),
1015 d(new GuiApplication::Private)
1017 QString app_name = "LyX";
1018 QCoreApplication::setOrganizationName(app_name);
1019 QCoreApplication::setOrganizationDomain("lyx.org");
1020 QCoreApplication::setApplicationName(lyx_package);
1021 #if QT_VERSION >= 0x050000
1022 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1025 qsrand(QDateTime::currentDateTime().toTime_t());
1027 // Install translator for GUI elements.
1028 installTranslator(&d->qt_trans_);
1031 // Enable reception of XCB events.
1032 installNativeEventFilter(this);
1035 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1036 // lyxrc setting for this in order to let the application stay resident.
1037 // But then we need some kind of dock icon, at least on Windows.
1039 if (lyxrc.quit_on_last_window_closed)
1040 setQuitOnLastWindowClosed(false);
1043 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1044 // seems to be the default case for applications like LyX.
1045 setQuitOnLastWindowClosed(false);
1046 // This allows to translate the strings that appear in the LyX menu.
1047 /// A translator suitable for the entries in the LyX menu.
1048 /// Only needed with Qt/Mac.
1049 installTranslator(new MenuTranslator(this));
1054 #if defined(Q_WS_X11) || defined(QPA_XCB)
1055 // doubleClickInterval() is 400 ms on X11 which is just too long.
1056 // On Windows and Mac OS X, the operating system's value is used.
1057 // On Microsoft Windows, calling this function sets the double
1058 // click interval for all applications. So we don't!
1059 QApplication::setDoubleClickInterval(300);
1062 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1064 // needs to be done before reading lyxrc
1066 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1070 // Set the cache to 5120 kilobytes which corresponds to screen size of
1071 // 1280 by 1024 pixels with a color depth of 32 bits.
1072 QPixmapCache::setCacheLimit(5120);
1074 // Initialize RC Fonts
1075 if (lyxrc.roman_font_name.empty())
1076 lyxrc.roman_font_name = fromqstr(romanFontName());
1078 if (lyxrc.sans_font_name.empty())
1079 lyxrc.sans_font_name = fromqstr(sansFontName());
1081 if (lyxrc.typewriter_font_name.empty())
1082 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1084 d->general_timer_.setInterval(500);
1085 connect(&d->general_timer_, SIGNAL(timeout()),
1086 this, SLOT(handleRegularEvents()));
1087 d->general_timer_.start();
1089 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1090 // This is clearly not enough in a time where we use threads for
1091 // document preview and/or export. 20 should be OK.
1092 QThreadPool::globalInstance()->setMaxThreadCount(20);
1094 // make sure tooltips are formatted
1095 installEventFilter(new ToolTipFormatter(this));
1099 GuiApplication * theGuiApp()
1101 return dynamic_cast<GuiApplication *>(theApp());
1105 double GuiApplication::pixelRatio() const
1107 #if QT_VERSION >= 0x050000
1108 return qt_scale_factor * devicePixelRatio();
1115 void GuiApplication::clearSession()
1122 docstring Application::iconName(FuncRequest const & f, bool unknown)
1124 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1128 docstring Application::mathIcon(docstring const & c)
1130 return qstring_to_ucs4(findImg(toqstr(c)));
1134 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1138 BufferView * bv = 0;
1139 BufferView * doc_bv = 0;
1141 if (cmd.action() == LFUN_NOACTION) {
1142 status.message(from_utf8(N_("Nothing to do")));
1143 status.setEnabled(false);
1146 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1147 status.setUnknown(true);
1148 status.message(from_utf8(N_("Unknown action")));
1149 status.setEnabled(false);
1152 // Does the GuiApplication know something?
1153 else if (getStatus(cmd, status)) { }
1155 // If we do not have a GuiView, then other functions are disabled
1156 else if (!current_view_)
1157 status.setEnabled(false);
1159 // Does the GuiView know something?
1160 else if (current_view_->getStatus(cmd, status)) { }
1162 // In LyX/Mac, when a dialog is open, the menus of the
1163 // application can still be accessed without giving focus to
1164 // the main window. In this case, we want to disable the menu
1165 // entries that are buffer or view-related.
1166 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1168 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1169 status.setEnabled(false);
1172 // If we do not have a BufferView, then other functions are disabled
1173 else if (!(bv = current_view_->currentBufferView()))
1174 status.setEnabled(false);
1176 // Does the current BufferView know something?
1177 else if (bv->getStatus(cmd, status)) { }
1179 // Does the current Buffer know something?
1180 else if (bv->buffer().getStatus(cmd, status)) { }
1182 // If we do not have a document BufferView, different from the
1183 // current BufferView, then other functions are disabled
1184 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1185 status.setEnabled(false);
1187 // Does the document Buffer know something?
1188 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1191 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1192 status.message(from_utf8(N_("Command not handled")));
1193 status.setEnabled(false);
1196 // the default error message if we disable the command
1197 if (!status.enabled() && status.message().empty())
1198 status.message(from_utf8(N_("Command disabled")));
1204 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1206 // I would really like to avoid having this switch and rather try to
1207 // encode this in the function itself.
1208 // -- And I'd rather let an inset decide which LFUNs it is willing
1209 // to handle (Andre')
1211 switch (cmd.action()) {
1213 // This could be used for the no-GUI version. The GUI version is handled in
1214 // GuiView::getStatus(). See above.
1216 case LFUN_BUFFER_WRITE:
1217 case LFUN_BUFFER_WRITE_AS: {
1218 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1219 enable = b && (b->isUnnamed() || !b->isClean());
1224 case LFUN_BOOKMARK_GOTO: {
1225 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1226 enable = theSession().bookmarks().isValid(num);
1230 case LFUN_BOOKMARK_CLEAR:
1231 enable = theSession().bookmarks().hasValid();
1234 // this one is difficult to get right. As a half-baked
1235 // solution, we consider only the first action of the sequence
1236 case LFUN_COMMAND_SEQUENCE: {
1237 // argument contains ';'-terminated commands
1238 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1239 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1240 func.setOrigin(cmd.origin());
1241 flag = getStatus(func);
1245 // we want to check if at least one of these is enabled
1246 case LFUN_COMMAND_ALTERNATIVES: {
1247 // argument contains ';'-terminated commands
1248 string arg = to_utf8(cmd.argument());
1249 while (!arg.empty()) {
1251 arg = split(arg, first, ';');
1252 FuncRequest func(lyxaction.lookupFunc(first));
1253 func.setOrigin(cmd.origin());
1254 flag = getStatus(func);
1255 // if this one is enabled, the whole thing is
1264 string name = to_utf8(cmd.argument());
1265 if (theTopLevelCmdDef().lock(name, func)) {
1266 func.setOrigin(cmd.origin());
1267 flag = getStatus(func);
1268 theTopLevelCmdDef().release(name);
1270 // catch recursion or unknown command
1271 // definition. all operations until the
1272 // recursion or unknown command definition
1273 // occurs are performed, so set the state to
1280 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1282 case LFUN_PREFERENCES_SAVE:
1283 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1284 case LFUN_DEBUG_LEVEL_SET:
1285 // these are handled in our dispatch()
1288 case LFUN_WINDOW_CLOSE:
1289 enable = d->views_.size() > 0;
1292 case LFUN_BUFFER_NEW:
1293 case LFUN_BUFFER_NEW_TEMPLATE:
1294 case LFUN_FILE_OPEN:
1295 case LFUN_HELP_OPEN:
1296 case LFUN_SCREEN_FONT_UPDATE:
1297 case LFUN_SET_COLOR:
1298 case LFUN_WINDOW_NEW:
1300 case LFUN_LYXRC_APPLY:
1301 case LFUN_COMMAND_PREFIX:
1303 case LFUN_META_PREFIX:
1304 case LFUN_RECONFIGURE:
1305 case LFUN_SERVER_GET_FILENAME:
1306 case LFUN_SERVER_NOTIFY:
1310 case LFUN_BUFFER_FORALL: {
1311 if (theBufferList().empty()) {
1312 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1313 flag.setEnabled(false);
1317 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1318 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1319 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1320 flag.setEnabled(false);
1325 case LFUN_DIALOG_SHOW: {
1326 string const name = cmd.getArg(0);
1327 return name == "aboutlyx"
1329 || name == "texinfo"
1330 || name == "progress"
1331 || name == "compare";
1339 flag.setEnabled(false);
1343 /// make a post-dispatch status message
1344 static docstring makeDispatchMessage(docstring const & msg,
1345 FuncRequest const & cmd)
1347 const bool verbose = (cmd.origin() == FuncRequest::MENU
1348 || cmd.origin() == FuncRequest::TOOLBAR
1349 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1351 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1352 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1356 docstring dispatch_msg = msg;
1357 if (!dispatch_msg.empty())
1358 dispatch_msg += ' ';
1360 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1362 bool argsadded = false;
1364 if (!cmd.argument().empty()) {
1365 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1366 comname += ' ' + cmd.argument();
1370 docstring const shortcuts = theTopLevelKeymap().
1371 printBindings(cmd, KeySequence::ForGui);
1373 if (!shortcuts.empty())
1374 comname += ": " + shortcuts;
1375 else if (!argsadded && !cmd.argument().empty())
1376 comname += ' ' + cmd.argument();
1378 if (!comname.empty()) {
1379 comname = rtrim(comname);
1380 dispatch_msg += '(' + rtrim(comname) + ')';
1382 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1383 return dispatch_msg;
1387 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1389 Buffer * buffer = 0;
1390 if (current_view_ && current_view_->currentBufferView()) {
1391 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1392 buffer = ¤t_view_->currentBufferView()->buffer();
1394 buffer->undo().beginUndoGroup();
1398 // redraw the screen at the end (first of the two drawing steps).
1399 // This is done unless explicitly requested otherwise
1400 dr.screenUpdate(Update::FitCursor);
1402 updateCurrentView(cmd, dr);
1404 // the buffer may have been closed by one action
1405 if (theBufferList().isLoaded(buffer))
1406 buffer->undo().endUndoGroup();
1408 d->dispatch_result_ = dr;
1409 return d->dispatch_result_;
1413 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1418 BufferView * bv = current_view_->currentBufferView();
1420 if (dr.needBufferUpdate()) {
1421 bv->cursor().clearBufferUpdate();
1422 bv->buffer().updateBuffer();
1423 } else if (dr.needChangesUpdate()) {
1424 // updateBuffer() already updates the change-tracking presence flag
1425 bv->buffer().updateChangesPresent();
1427 // BufferView::update() updates the ViewMetricsInfo and
1428 // also initializes the position cache for all insets in
1429 // (at least partially) visible top-level paragraphs.
1430 // We will redraw the screen only if needed.
1431 bv->processUpdateFlags(dr.screenUpdate());
1433 // Do we have a selection?
1434 theSelection().haveSelection(bv->cursor().selection());
1437 current_view_->restartCaret();
1439 if (dr.needMessageUpdate()) {
1440 // Some messages may already be translated, so we cannot use _()
1441 current_view_->message(makeDispatchMessage(
1442 translateIfPossible(dr.message()), cmd));
1447 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1448 bool switchToBuffer)
1450 if (!theSession().bookmarks().isValid(idx))
1452 BookmarksSection::Bookmark const & bm =
1453 theSession().bookmarks().bookmark(idx);
1454 LASSERT(!bm.filename.empty(), return);
1455 string const file = bm.filename.absFileName();
1456 // if the file is not opened, open it.
1457 if (!theBufferList().exists(bm.filename)) {
1459 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1463 // open may fail, so we need to test it again
1464 if (!theBufferList().exists(bm.filename))
1467 // bm can be changed when saving
1468 BookmarksSection::Bookmark tmp = bm;
1470 // Special case idx == 0 used for back-from-back jump navigation
1472 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1474 // if the current buffer is not that one, switch to it.
1475 BufferView * doc_bv = current_view_ ?
1476 current_view_->documentBufferView() : 0;
1477 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1478 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1479 if (switchToBuffer) {
1480 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1483 doc_bv = current_view_->documentBufferView();
1488 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1489 if (!doc_bv || !doc_bv->moveToPosition(
1490 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1493 Cursor & cur = doc_bv->cursor();
1494 if (old && cur != *old)
1495 notifyCursorLeavesOrEnters(*old, cur);
1501 // Cursor jump succeeded!
1502 pit_type new_pit = cur.pit();
1503 pos_type new_pos = cur.pos();
1504 int new_id = cur.paragraph().id();
1506 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1507 // see http://www.lyx.org/trac/ticket/3092
1508 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1509 || bm.top_id != new_id) {
1510 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1511 new_pit, new_pos, new_id);
1515 // This function runs "configure" and then rereads lyx.defaults to
1516 // reconfigure the automatic settings.
1517 void GuiApplication::reconfigure(string const & option)
1519 // emit message signal.
1521 current_view_->message(_("Running configure..."));
1523 // Run configure in user lyx directory
1524 string const lock_file = package().getConfigureLockName();
1525 int fd = fileLock(lock_file.c_str());
1526 int const ret = package().reconfigureUserLyXDir(option);
1527 // emit message signal.
1529 current_view_->message(_("Reloading configuration..."));
1530 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1531 // Re-read packages.lst
1532 LaTeXPackages::getAvailable();
1533 fileUnlock(fd, lock_file.c_str());
1536 Alert::information(_("System reconfiguration failed"),
1537 _("The system reconfiguration has failed.\n"
1538 "Default textclass is used but LyX may\n"
1539 "not be able to work properly.\n"
1540 "Please reconfigure again if needed."));
1542 Alert::information(_("System reconfigured"),
1543 _("The system has been reconfigured.\n"
1544 "You need to restart LyX to make use of any\n"
1545 "updated document class specifications."));
1548 void GuiApplication::validateCurrentView()
1550 if (!d->views_.empty() && !current_view_) {
1551 // currently at least one view exists but no view has the focus.
1552 // choose the last view to make it current.
1553 // a view without any open document is preferred.
1554 GuiView * candidate = 0;
1555 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1556 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1557 for (; it != end; ++it) {
1559 if (!candidate->documentBufferView())
1562 setCurrentView(candidate);
1566 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1568 string const argument = to_utf8(cmd.argument());
1569 FuncCode const action = cmd.action();
1571 LYXERR(Debug::ACTION, "cmd: " << cmd);
1573 // we have not done anything wrong yet.
1576 FuncStatus const flag = getStatus(cmd);
1577 if (!flag.enabled()) {
1578 // We cannot use this function here
1579 LYXERR(Debug::ACTION, "action "
1580 << lyxaction.getActionName(action)
1581 << " [" << action << "] is disabled at this location");
1582 dr.setMessage(flag.message());
1584 dr.dispatched(false);
1585 dr.screenUpdate(Update::None);
1586 dr.clearBufferUpdate();
1590 if (cmd.origin() == FuncRequest::LYXSERVER) {
1591 if (current_view_ && current_view_->currentBufferView())
1592 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1593 // we will also need to redraw the screen at the end
1594 dr.screenUpdate(Update::FitCursor);
1597 // Assumes that the action will be dispatched.
1598 dr.dispatched(true);
1600 switch (cmd.action()) {
1602 case LFUN_WINDOW_NEW:
1603 createView(toqstr(cmd.argument()));
1606 case LFUN_WINDOW_CLOSE:
1607 // update bookmark pit of the current buffer before window close
1608 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1609 gotoBookmark(i+1, false, false);
1610 // clear the last opened list, because
1611 // maybe this will end the session
1612 theSession().lastOpened().clear();
1613 // check for valid current_view_
1614 validateCurrentView();
1616 current_view_->closeScheduled();
1620 // quitting is triggered by the gui code
1621 // (leaving the event loop).
1623 current_view_->message(from_utf8(N_("Exiting.")));
1624 if (closeAllViews())
1628 case LFUN_SCREEN_FONT_UPDATE: {
1629 // handle the screen font changes.
1630 d->font_loader_.update();
1631 dr.screenUpdate(Update::Force | Update::FitCursor);
1635 case LFUN_BUFFER_NEW:
1636 validateCurrentView();
1638 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1639 createView(QString(), false); // keep hidden
1640 current_view_->newDocument(to_utf8(cmd.argument()), false);
1641 current_view_->show();
1642 setActiveWindow(current_view_);
1644 current_view_->newDocument(to_utf8(cmd.argument()), false);
1648 case LFUN_BUFFER_NEW_TEMPLATE:
1649 validateCurrentView();
1651 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1653 current_view_->newDocument(to_utf8(cmd.argument()), true);
1654 if (!current_view_->documentBufferView())
1655 current_view_->close();
1657 current_view_->newDocument(to_utf8(cmd.argument()), true);
1661 case LFUN_FILE_OPEN: {
1662 // FIXME: normally the code below is not needed, since getStatus makes sure that
1663 // current_view_ is not null.
1664 validateCurrentView();
1665 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1666 string const fname = to_utf8(cmd.argument());
1667 bool const is_open = FileName::isAbsolute(fname)
1668 && theBufferList().getBuffer(FileName(fname));
1670 || (!lyxrc.open_buffers_in_tabs
1671 && current_view_->documentBufferView() != 0
1673 // We want the ui session to be saved per document and not per
1674 // window number. The filename crc is a good enough identifier.
1675 boost::crc_32_type crc;
1676 crc = for_each(fname.begin(), fname.end(), crc);
1677 createView(crc.checksum());
1678 current_view_->openDocument(fname);
1679 if (!current_view_->documentBufferView())
1680 current_view_->close();
1681 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1682 current_view_->raise();
1683 current_view_->activateWindow();
1684 current_view_->showNormal();
1687 current_view_->openDocument(fname);
1688 if (cmd.origin() == FuncRequest::LYXSERVER) {
1689 current_view_->raise();
1690 current_view_->activateWindow();
1691 current_view_->showNormal();
1697 case LFUN_HELP_OPEN: {
1698 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1699 if (current_view_ == 0)
1701 string const arg = to_utf8(cmd.argument());
1703 current_view_->message(_("Missing argument"));
1706 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1708 fname = i18nLibFileSearch("examples", arg, "lyx");
1710 if (fname.empty()) {
1711 lyxerr << "LyX: unable to find documentation file `"
1712 << arg << "'. Bad installation?" << endl;
1715 current_view_->message(bformat(_("Opening help file %1$s..."),
1716 makeDisplayPath(fname.absFileName())));
1717 Buffer * buf = current_view_->loadDocument(fname, false);
1719 buf->setReadonly(!current_view_->develMode());
1723 case LFUN_SET_COLOR: {
1725 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1726 if (lyx_name.empty() || x11_name.empty()) {
1728 current_view_->message(
1729 _("Syntax: set-color <lyx_name> <x11_name>"));
1734 // FIXME: The graphics cache no longer has a changeDisplay method.
1735 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1736 bool const graphicsbg_changed =
1737 lyx_name == graphicsbg && x11_name != graphicsbg;
1738 if (graphicsbg_changed)
1739 graphics::GCache::get().changeDisplay(true);
1742 if (!lcolor.setColor(lyx_name, x11_name)) {
1744 current_view_->message(
1745 bformat(_("Set-color \"%1$s\" failed "
1746 "- color is undefined or "
1747 "may not be redefined"),
1748 from_utf8(lyx_name)));
1751 // Make sure we don't keep old colors in cache.
1752 d->color_cache_.clear();
1753 // Update the current view
1754 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1758 case LFUN_LYXRC_APPLY: {
1759 // reset active key sequences, since the bindings
1760 // are updated (bug 6064)
1762 LyXRC const lyxrc_orig = lyxrc;
1764 istringstream ss(to_utf8(cmd.argument()));
1765 bool const success = lyxrc.read(ss);
1768 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1769 << "Unable to read lyxrc data"
1774 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1776 // If the request comes from the minibuffer, then we can't reset
1777 // the GUI, since that would destory the minibuffer itself and
1778 // cause a crash, since we are currently in one of the methods of
1779 // GuiCommandBuffer. See bug #8540.
1780 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1783 // FIXME Unfortunately, that leaves a bug here, since we cannot
1784 // reset the GUI in this case. If the changes to lyxrc affected the
1785 // UI, then, nothing would happen. This seems fairly unlikely, but
1786 // it definitely is a bug.
1791 case LFUN_COMMAND_PREFIX:
1792 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1797 d->meta_fake_bit = NoModifier;
1798 GuiView * gv = currentView();
1799 if (gv && gv->currentBufferView())
1800 // cancel any selection
1801 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1802 dr.setMessage(from_ascii(N_("Cancel")));
1805 case LFUN_META_PREFIX:
1806 d->meta_fake_bit = AltModifier;
1807 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1810 // --- Menus -----------------------------------------------
1811 case LFUN_RECONFIGURE:
1812 // argument is any additional parameter to the configure.py command
1813 reconfigure(to_utf8(cmd.argument()));
1816 // --- lyxserver commands ----------------------------
1817 case LFUN_SERVER_GET_FILENAME: {
1818 if (current_view_ && current_view_->documentBufferView()) {
1819 docstring const fname = from_utf8(
1820 current_view_->documentBufferView()->buffer().absFileName());
1821 dr.setMessage(fname);
1822 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1824 dr.setMessage(docstring());
1825 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1830 case LFUN_SERVER_NOTIFY: {
1831 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1832 dr.setMessage(dispatch_buffer);
1833 theServer().notifyClient(to_utf8(dispatch_buffer));
1837 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1838 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1844 string rest = split(argument, countstr, ' ');
1845 int const count = convert<int>(countstr);
1846 // an arbitrary number to limit number of iterations
1847 int const max_iter = 10000;
1848 if (count > max_iter) {
1849 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1852 for (int i = 0; i < count; ++i)
1853 dispatch(lyxaction.lookupFunc(rest));
1858 case LFUN_COMMAND_SEQUENCE: {
1859 // argument contains ';'-terminated commands
1860 string arg = argument;
1861 // FIXME: this LFUN should also work without any view.
1862 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1863 ? &(current_view_->documentBufferView()->buffer()) : 0;
1865 buffer->undo().beginUndoGroup();
1866 while (!arg.empty()) {
1868 arg = split(arg, first, ';');
1869 FuncRequest func(lyxaction.lookupFunc(first));
1870 func.setOrigin(cmd.origin());
1873 // the buffer may have been closed by one action
1874 if (theBufferList().isLoaded(buffer))
1875 buffer->undo().endUndoGroup();
1879 case LFUN_BUFFER_FORALL: {
1880 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1882 map<Buffer *, GuiView *> views_lVisible;
1883 map<GuiView *, Buffer *> activeBuffers;
1885 QList<GuiView *> allViews = d->views_.values();
1887 // this for does not modify any buffer. It just collects info on local
1888 // visibility of buffers and on which buffer is active in each view.
1889 Buffer * const last = theBufferList().last();
1890 for(GuiView * view : allViews) {
1891 // all of the buffers might be locally hidden. That is, there is no
1893 if (!view || !view->currentBufferView())
1894 activeBuffers[view] = 0;
1896 activeBuffers[view] = &view->currentBufferView()->buffer();
1898 // find out if each is locally visible or locally hidden.
1899 // we don't use a for loop as the buffer list cycles.
1900 Buffer * b = theBufferList().first();
1902 bool const locallyVisible = view && view->workArea(*b);
1903 if (locallyVisible) {
1904 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1905 // only need to overwrite/add if we don't already know a buffer is globally
1906 // visible or we do know but we would prefer to dispatch LFUN from the
1907 // current view because of cursor position issues.
1908 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1909 views_lVisible[b] = view;
1913 b = theBufferList().next(b);
1917 GuiView * const homeView = currentView();
1918 Buffer * b = theBufferList().first();
1919 Buffer * nextBuf = 0;
1920 int numProcessed = 0;
1923 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1925 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1927 // first change to a view where b is locally visible, preferably current_view_.
1928 GuiView * const vLv = views_lVisible[b];
1930 lyx::dispatch(funcToRun);
1938 // put things back to how they were (if possible).
1939 for (GuiView * view : allViews) {
1940 Buffer * originalBuf = activeBuffers[view];
1941 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1942 if (theBufferList().isLoaded(originalBuf))
1943 view->setBuffer(originalBuf);
1945 homeView->setFocus();
1947 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1951 case LFUN_COMMAND_ALTERNATIVES: {
1952 // argument contains ';'-terminated commands
1953 string arg = argument;
1954 while (!arg.empty()) {
1956 arg = split(arg, first, ';');
1957 FuncRequest func(lyxaction.lookupFunc(first));
1958 func.setOrigin(cmd.origin());
1959 FuncStatus const stat = getStatus(func);
1960 if (stat.enabled()) {
1970 if (theTopLevelCmdDef().lock(argument, func)) {
1971 func.setOrigin(cmd.origin());
1973 theTopLevelCmdDef().release(argument);
1975 if (func.action() == LFUN_UNKNOWN_ACTION) {
1976 // unknown command definition
1977 lyxerr << "Warning: unknown command definition `"
1981 // recursion detected
1982 lyxerr << "Warning: Recursion in the command definition `"
1983 << argument << "' detected"
1990 case LFUN_PREFERENCES_SAVE:
1991 lyxrc.write(support::makeAbsPath("preferences",
1992 package().user_support().absFileName()), false);
1995 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1996 string const fname = addName(addPath(package().user_support().absFileName(),
1997 "templates/"), "defaults.lyx");
1998 Buffer defaults(fname);
2000 istringstream ss(argument);
2005 // We need to make sure that, after we recreat the DocumentClass,
2006 // which we do in readHeader, we apply it to the document itself.
2007 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2008 int const unknown_tokens = defaults.readHeader(lex);
2009 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2011 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2012 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2014 if (unknown_tokens != 0) {
2015 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2016 << unknown_tokens << " unknown token"
2017 << (unknown_tokens == 1 ? "" : "s")
2021 if (defaults.writeFile(FileName(defaults.absFileName())))
2022 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2023 makeDisplayPath(fname)));
2026 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2031 case LFUN_BOOKMARK_GOTO:
2032 // go to bookmark, open unopened file and switch to buffer if necessary
2033 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2034 dr.screenUpdate(Update::Force | Update::FitCursor);
2037 case LFUN_BOOKMARK_CLEAR:
2038 theSession().bookmarks().clear();
2041 case LFUN_DEBUG_LEVEL_SET:
2042 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2045 case LFUN_DIALOG_SHOW: {
2046 string const name = cmd.getArg(0);
2048 if ( name == "aboutlyx"
2050 || name == "texinfo"
2051 || name == "progress"
2052 || name == "compare")
2054 // work around: on Mac OS the application
2055 // is not terminated when closing the last view.
2056 // Create a new one to be able to dispatch the
2057 // LFUN_DIALOG_SHOW to this view.
2058 if (current_view_ == 0)
2064 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2067 current_view_->dispatch(cmd, dr);
2071 if (cmd.origin() == FuncRequest::LYXSERVER)
2072 updateCurrentView(cmd, dr);
2076 docstring GuiApplication::viewStatusMessage()
2078 // When meta-fake key is pressed, show the key sequence so far + "M-".
2079 if (d->meta_fake_bit != NoModifier)
2080 return d->keyseq.print(KeySequence::ForGui) + "M-";
2082 // Else, when a non-complete key sequence is pressed,
2083 // show the available options.
2084 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2085 return d->keyseq.printOptions(true);
2091 void GuiApplication::handleKeyFunc(FuncCode action)
2095 if (d->keyseq.length())
2097 GuiView * gv = currentView();
2098 LASSERT(gv && gv->currentBufferView(), return);
2099 BufferView * bv = gv->currentBufferView();
2100 bv->getIntl().getTransManager().deadkey(
2101 c, get_accent(action).accent, bv->cursor().innerText(),
2103 // Need to clear, in case the minibuffer calls these
2106 // copied verbatim from do_accent_char
2107 bv->cursor().resetAnchor();
2111 //Keep this in sync with GuiApplication::processKeySym below
2112 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2113 KeyModifier state) const
2115 // Do nothing if we have nothing
2116 if (!keysym.isOK() || keysym.isModifier())
2118 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2120 FuncRequest func = seq.addkey(keysym, state);
2121 // When not cancel or meta-fake, do the normal lookup.
2122 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2124 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2126 // Maybe user can only reach the key via holding down shift.
2127 // Let's see. But only if shift is the only modifier
2128 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2129 // If addkey looked up a command and did not find further commands then
2130 // seq has been reset at this point
2131 func = seq.addkey(keysym, NoModifier);
2133 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2134 << seq.print(KeySequence::Portable) << ']');
2135 return func.action() != LFUN_UNKNOWN_ACTION;
2139 //Keep this in sync with GuiApplication::queryKeySym above
2140 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2142 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2144 // Do nothing if we have nothing (JMarc)
2145 if (!keysym.isOK() || keysym.isModifier()) {
2147 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2149 current_view_->restartCaret();
2153 char_type encoded_last_key = keysym.getUCSEncoded();
2155 // Do a one-deep top-level lookup for
2156 // cancel and meta-fake keys. RVDK_PATCH_5
2157 d->cancel_meta_seq.reset();
2159 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2160 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2162 // When not cancel or meta-fake, do the normal lookup.
2163 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2164 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2165 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2166 // remove Caps Lock and Mod2 as a modifiers
2167 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2168 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2171 // Dont remove this unless you know what you are doing.
2172 d->meta_fake_bit = NoModifier;
2174 // Can this happen now ?
2175 if (func.action() == LFUN_NOACTION)
2176 func = FuncRequest(LFUN_COMMAND_PREFIX);
2178 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2179 << d->keyseq.print(KeySequence::Portable) << ']');
2181 // already here we know if it any point in going further
2182 // why not return already here if action == -1 and
2183 // num_bytes == 0? (Lgb)
2185 if (d->keyseq.length() > 1 && current_view_)
2186 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2189 // Maybe user can only reach the key via holding down shift.
2190 // Let's see. But only if shift is the only modifier
2191 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2192 LYXERR(Debug::KEY, "Trying without shift");
2193 // If addkey looked up a command and did not find further commands then
2194 // seq has been reset at this point
2195 func = d->keyseq.addkey(keysym, NoModifier);
2196 LYXERR(Debug::KEY, "Action now " << func.action());
2199 if (func.action() == LFUN_UNKNOWN_ACTION) {
2200 // We didn't match any of the key sequences.
2201 // See if it's normal insertable text not already
2202 // covered by a binding
2203 if (keysym.isText() && d->keyseq.length() == 1) {
2204 // Non-printable characters (such as ASCII control characters)
2205 // must not be inserted (#5704)
2206 if (!isPrintable(encoded_last_key)) {
2207 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2209 current_view_->restartCaret();
2212 // The following modifier check is not needed on Mac.
2213 // The keysym is either not text or it is different
2214 // from the non-modifier keysym. See #9875 for the
2215 // broken alt-modifier effect of having this code active.
2216 #if !defined(Q_OS_MAC)
2217 // If a non-Shift Modifier is used we have a non-bound key sequence
2218 // (such as Alt+j = j). This should be omitted (#5575).
2219 // On Windows, AltModifier and ControlModifier are both
2220 // set when AltGr is pressed. Therefore, in order to not
2221 // break AltGr-bound symbols (see #5575 for details),
2222 // unbound Ctrl+Alt key sequences are allowed.
2223 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2224 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2225 && !(state & AltModifier && state & ControlModifier)
2229 if (current_view_) {
2230 current_view_->message(_("Unknown function."));
2231 current_view_->restartCaret();
2236 // Since all checks above were passed, we now really have text that
2237 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2238 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2240 LYXERR(Debug::KEY, "isText() is true, inserting.");
2241 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2243 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2244 if (current_view_) {
2245 current_view_->message(_("Unknown function."));
2246 current_view_->restartCaret();
2252 if (func.action() == LFUN_SELF_INSERT) {
2253 if (encoded_last_key != 0) {
2254 docstring const arg(1, encoded_last_key);
2255 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2256 FuncRequest::KEYBOARD));
2257 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2260 processFuncRequest(func);
2264 void GuiApplication::processFuncRequest(FuncRequest const & func)
2266 lyx::dispatch(func);
2270 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2272 addToFuncRequestQueue(func);
2273 processFuncRequestQueueAsync();
2277 void GuiApplication::processFuncRequestQueue()
2279 while (!d->func_request_queue_.empty()) {
2280 processFuncRequest(d->func_request_queue_.front());
2281 d->func_request_queue_.pop();
2286 void GuiApplication::processFuncRequestQueueAsync()
2288 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2292 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2294 d->func_request_queue_.push(func);
2298 void GuiApplication::resetGui()
2300 // Set the language defined by the user.
2304 if (!readUIFile(toqstr(lyxrc.ui_file)))
2305 // Gives some error box here.
2308 if (d->global_menubar_)
2309 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2311 QHash<int, GuiView *>::iterator it;
2312 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2315 gv->setLayoutDirection(layoutDirection());
2319 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2323 void GuiApplication::createView(int view_id)
2325 createView(QString(), true, view_id);
2329 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2332 // release the keyboard which might have been grabed by the global
2333 // menubar on Mac to catch shortcuts even without any GuiView.
2334 if (d->global_menubar_)
2335 d->global_menubar_->releaseKeyboard();
2339 while (d->views_.find(id) != d->views_.end())
2342 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2343 GuiView * view = new GuiView(id);
2344 // `view' is the new current_view_. Tell coverity that is is not 0.
2345 LATTEST(current_view_);
2347 d->views_[id] = view;
2351 setActiveWindow(view);
2354 if (!geometry_arg.isEmpty()) {
2355 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2359 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2360 re.indexIn(geometry_arg);
2361 w = re.cap(1).toInt();
2362 h = re.cap(2).toInt();
2363 x = re.cap(3).toInt();
2364 y = re.cap(4).toInt();
2365 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2366 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2367 // Set initial geometry such that we can get the frame size.
2368 view->setGeometry(x, y, w, h);
2369 int framewidth = view->geometry().x() - view->x();
2370 int titleheight = view->geometry().y() - view->y();
2371 // Negative displacements must be interpreted as distances
2372 // from the right or bottom screen borders.
2373 if (sx == '-' || sy == '-') {
2374 QRect rec = QApplication::desktop()->screenGeometry();
2376 x += rec.width() - w - framewidth;
2378 y += rec.height() - h - titleheight;
2379 view->setGeometry(x, y, w, h);
2381 // Make sure that the left and top frame borders are visible.
2382 if (view->x() < 0 || view->y() < 0) {
2387 view->setGeometry(x, y, w, h);
2395 bool GuiApplication::unhide(Buffer * buf)
2399 currentView()->setBuffer(buf, false);
2404 Clipboard & GuiApplication::clipboard()
2406 return d->clipboard_;
2410 Selection & GuiApplication::selection()
2412 return d->selection_;
2416 FontLoader & GuiApplication::fontLoader()
2418 return d->font_loader_;
2422 Toolbars const & GuiApplication::toolbars() const
2424 return d->toolbars_;
2428 Toolbars & GuiApplication::toolbars()
2430 return d->toolbars_;
2434 Menus const & GuiApplication::menus() const
2440 Menus & GuiApplication::menus()
2446 QList<int> GuiApplication::viewIds() const
2448 return d->views_.keys();
2452 ColorCache & GuiApplication::colorCache()
2454 return d->color_cache_;
2458 int GuiApplication::exec()
2460 // asynchronously handle batch commands. This event will be in
2461 // the event queue in front of other asynchronous events. Hence,
2462 // we can assume in the latter that the gui is setup already.
2463 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2465 return QApplication::exec();
2469 void GuiApplication::exit(int status)
2471 QApplication::exit(status);
2475 void GuiApplication::setGuiLanguage()
2479 // install translation file for Qt built-in dialogs
2480 QString const language_name = QString("qt_") + theLocale.name();
2481 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2482 // Short-named translator can be loaded from a long name, but not the
2483 // opposite. Therefore, long name should be used without truncation.
2484 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2485 if (!d->qt_trans_.load(language_name,
2486 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2487 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2490 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2494 switch (theLocale.language()) {
2495 case QLocale::Arabic :
2496 case QLocale::Hebrew :
2497 case QLocale::Persian :
2498 case QLocale::Urdu :
2499 setLayoutDirection(Qt::RightToLeft);
2502 setLayoutDirection(Qt::LeftToRight);
2507 void GuiApplication::execBatchCommands()
2512 if (!readUIFile(toqstr(lyxrc.ui_file)))
2513 // Gives some error box here.
2517 #if QT_VERSION > 0x040600
2518 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2520 #if QT_VERSION > 0x050100
2521 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2523 // Create the global default menubar which is shown for the dialogs
2524 // and if no GuiView is visible.
2525 // This must be done after the session was recovered to know the "last files".
2526 d->global_menubar_ = new QMenuBar(0);
2527 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2530 lyx::execBatchCommands();
2534 QAbstractItemModel * GuiApplication::languageModel()
2536 if (d->language_model_)
2537 return d->language_model_;
2539 QStandardItemModel * lang_model = new QStandardItemModel(this);
2540 lang_model->insertColumns(0, 3);
2541 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2542 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2543 Languages::const_iterator it = lyx::languages.begin();
2544 Languages::const_iterator end = lyx::languages.end();
2545 for (; it != end; ++it) {
2546 int current_row = lang_model->rowCount();
2547 lang_model->insertRows(current_row, 1);
2548 QModelIndex pl_item = lang_model->index(current_row, 0);
2549 QModelIndex sp_item = lang_model->index(current_row, 1);
2550 QModelIndex th_item = lang_model->index(current_row, 2);
2551 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2552 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2553 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2554 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2555 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2556 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2557 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2558 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2559 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2560 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2562 d->language_model_ = new QSortFilterProxyModel(this);
2563 d->language_model_->setSourceModel(lang_model);
2564 d->language_model_->setSortLocaleAware(true);
2565 return d->language_model_;
2569 void GuiApplication::restoreGuiSession()
2571 if (!lyxrc.load_session)
2574 Session & session = theSession();
2575 LastOpenedSection::LastOpened const & lastopened =
2576 session.lastOpened().getfiles();
2578 validateCurrentView();
2580 FileName active_file;
2581 // do not add to the lastfile list since these files are restored from
2582 // last session, and should be already there (regular files), or should
2583 // not be added at all (help files).
2584 for (size_t i = 0; i < lastopened.size(); ++i) {
2585 FileName const & file_name = lastopened[i].file_name;
2586 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2587 && current_view_->documentBufferView() != 0)) {
2588 boost::crc_32_type crc;
2589 string const & fname = file_name.absFileName();
2590 crc = for_each(fname.begin(), fname.end(), crc);
2591 createView(crc.checksum());
2593 current_view_->loadDocument(file_name, false);
2595 if (lastopened[i].active)
2596 active_file = file_name;
2599 // Restore last active buffer
2600 Buffer * buffer = theBufferList().getBuffer(active_file);
2601 if (buffer && current_view_)
2602 current_view_->setBuffer(buffer);
2604 // clear this list to save a few bytes of RAM
2605 session.lastOpened().clear();
2609 QString const GuiApplication::romanFontName()
2612 font.setStyleHint(QFont::Serif);
2613 font.setFamily("serif");
2615 return QFontInfo(font).family();
2619 QString const GuiApplication::sansFontName()
2622 font.setStyleHint(QFont::SansSerif);
2623 font.setFamily("sans");
2625 return QFontInfo(font).family();
2629 QString const GuiApplication::typewriterFontName()
2631 return QFontInfo(typewriterSystemFont()).family();
2636 // We cannot use QFont::fixedPitch() because it doesn't
2637 // return the fact but only if it is requested.
2638 static bool isFixedPitch(const QFont & font) {
2639 const QFontInfo fi(font);
2640 return fi.fixedPitch();
2645 QFont const GuiApplication::typewriterSystemFont()
2647 #if QT_VERSION >= 0x050200
2648 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2650 QFont font("monospace");
2652 if (!isFixedPitch(font)) {
2653 // try to enforce a real monospaced font
2654 font.setStyleHint(QFont::Monospace);
2655 if (!isFixedPitch(font)) {
2656 font.setStyleHint(QFont::TypeWriter);
2657 if (!isFixedPitch(font)) font.setFamily("courier");
2661 // On a Mac the result is too small and it's not practical to
2662 // rely on Qtconfig utility to change the system settings of Qt.
2663 font.setPointSize(12);
2669 void GuiApplication::handleRegularEvents()
2671 ForkedCallsController::handleCompletedProcesses();
2675 bool GuiApplication::event(QEvent * e)
2678 case QEvent::FileOpen: {
2679 // Open a file; this happens only on Mac OS X for now.
2681 // We do this asynchronously because on startup the batch
2682 // commands are not executed here yet and the gui is not ready
2684 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2685 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2686 processFuncRequestAsync(fr);
2691 return QApplication::event(e);
2696 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2699 return QApplication::notify(receiver, event);
2701 catch (ExceptionMessage const & e) {
2703 case ErrorException:
2705 setQuitOnLastWindowClosed(false);
2707 Alert::error(e.title_, e.details_);
2709 // Properly crash in debug mode in order to get a useful backtrace.
2712 // In release mode, try to exit gracefully.
2714 // FIXME: GCC 7 thinks we can fall through here. Can we?
2716 case BufferException: {
2717 if (!current_view_ || !current_view_->documentBufferView())
2719 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2720 docstring details = e.details_ + '\n';
2721 details += buf->emergencyWrite();
2722 theBufferList().release(buf);
2723 details += "\n" + _("The current document was closed.");
2724 Alert::error(e.title_, details);
2727 case WarningException:
2728 Alert::warning(e.title_, e.details_);
2732 catch (exception const & e) {
2733 docstring s = _("LyX has caught an exception, it will now "
2734 "attempt to save all unsaved documents and exit."
2736 s += from_ascii(e.what());
2737 Alert::error(_("Software exception Detected"), s);
2741 docstring s = _("LyX has caught some really weird exception, it will "
2742 "now attempt to save all unsaved documents and exit.");
2743 Alert::error(_("Software exception Detected"), s);
2751 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2753 QColor const & qcol = d->color_cache_.get(col);
2754 if (!qcol.isValid()) {
2760 rgbcol.r = qcol.red();
2761 rgbcol.g = qcol.green();
2762 rgbcol.b = qcol.blue();
2767 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2769 QColor const qcol(lcolor.getX11Name(col).c_str());
2770 if (!qcol.isValid()) {
2776 rgbcol.r = qcol.red();
2777 rgbcol.g = qcol.green();
2778 rgbcol.b = qcol.blue();
2783 string const GuiApplication::hexName(ColorCode col)
2785 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2789 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2791 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2792 d->socket_notifiers_[fd] = sn;
2793 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2797 void GuiApplication::socketDataReceived(int fd)
2799 d->socket_notifiers_[fd]->func_();
2803 void GuiApplication::unregisterSocketCallback(int fd)
2805 d->socket_notifiers_.take(fd)->setEnabled(false);
2809 void GuiApplication::commitData(QSessionManager & sm)
2811 /** The implementation is required to avoid an application exit
2812 ** when session state save is triggered by session manager.
2813 ** The default implementation sends a close event to all
2814 ** visible top level widgets when session managment allows
2816 ** We are changing that to check the state of each buffer in all
2817 ** views and ask the users what to do if buffers are dirty.
2818 ** Furthermore, we save the session state.
2819 ** We do NOT close the views here since the user still can cancel
2820 ** the logout process (see #9277); also, this would hide LyX from
2821 ** an OSes own session handling (application restoration).
2823 #ifdef QT_NO_SESSIONMANAGER
2825 #warning Qt is compiled without session manager
2827 #pragma message("warning: Qt is compiled without session manager")
2831 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2839 void GuiApplication::unregisterView(GuiView * gv)
2841 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2842 d->views_.remove(gv->id());
2843 if (current_view_ == gv)
2849 bool GuiApplication::closeAllViews()
2851 if (d->views_.empty())
2854 // When a view/window was closed before without quitting LyX, there
2855 // are already entries in the lastOpened list.
2856 theSession().lastOpened().clear();
2858 QList<GuiView *> const views = d->views_.values();
2859 for (GuiView * view : views) {
2860 if (!view->closeScheduled())
2869 bool GuiApplication::prepareAllViewsForLogout()
2871 if (d->views_.empty())
2874 QList<GuiView *> const views = d->views_.values();
2875 for (GuiView * view : views) {
2876 if (!view->prepareAllBuffersForLogout())
2884 GuiView & GuiApplication::view(int id) const
2886 LAPPERR(d->views_.contains(id));
2887 return *d->views_.value(id);
2891 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2893 QList<GuiView *> const views = d->views_.values();
2894 for (GuiView * view : views)
2895 view->hideDialog(name, inset);
2899 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2901 Buffer const * buffer_ = 0;
2902 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2903 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2904 if (Buffer const * ptr = (*it)->updateInset(inset))
2911 bool GuiApplication::searchMenu(FuncRequest const & func,
2912 docstring_list & names) const
2914 return d->menus_.searchMenu(func, names);
2918 // Ensure that a file is read only once (prevents include loops)
2919 static QStringList uifiles;
2920 // store which ui files define Toolbars
2921 static QStringList toolbar_uifiles;
2924 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2935 LexerKeyword uitags[] = {
2936 { "format", ui_format },
2937 { "include", ui_include },
2938 { "menuset", ui_menuset },
2939 { "toolbars", ui_toolbars },
2940 { "toolbarset", ui_toolbarset }
2944 lex.setFile(ui_path);
2946 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2950 if (lyxerr.debugging(Debug::PARSER))
2951 lex.printTable(lyxerr);
2954 // format before introduction of format tag
2955 unsigned int format = 0;
2956 while (lex.isOK()) {
2957 int const status = lex.lex();
2959 // we have to do this check here, outside the switch,
2960 // because otherwise we would start reading include files,
2961 // e.g., if the first tag we hit was an include tag.
2962 if (status == ui_format)
2964 format = lex.getInteger();
2968 // this will trigger unless the first tag we hit is a format
2969 // tag, with the right format.
2970 if (format != LFUN_FORMAT)
2971 return FormatMismatch;
2974 case Lexer::LEX_FEOF:
2979 QString const file = toqstr(lex.getString());
2980 bool const success = readUIFile(file, true);
2982 LYXERR0("Failed to read included file: " << fromqstr(file));
2989 d->menus_.read(lex);
2993 d->toolbars_.readToolbars(lex);
2997 d->toolbars_.readToolbarSettings(lex);
2998 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3002 if (!rtrim(lex.getString()).empty())
3003 lex.printError("LyX::ReadUIFile: "
3004 "Unknown menu tag: `$$Token'");
3006 LYXERR0("Error with status: " << status);
3012 return (error ? ReadError : ReadOK);
3016 bool GuiApplication::readUIFile(QString const & name, bool include)
3018 LYXERR(Debug::INIT, "About to read " << name << "...");
3022 ui_path = libFileSearch("ui", name, "inc");
3023 if (ui_path.empty())
3024 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3026 ui_path = libFileSearch("ui", name, "ui");
3029 if (ui_path.empty()) {
3030 static const QString defaultUIFile = "default";
3031 LYXERR(Debug::INIT, "Could not find " << name);
3033 Alert::warning(_("Could not find UI definition file"),
3034 bformat(_("Error while reading the included file\n%1$s\n"
3035 "Please check your installation."), qstring_to_ucs4(name)));
3038 if (name == defaultUIFile) {
3039 LYXERR(Debug::INIT, "Could not find default UI file!!");
3040 Alert::warning(_("Could not find default UI file"),
3041 _("LyX could not find the default UI file!\n"
3042 "Please check your installation."));
3045 Alert::warning(_("Could not find UI definition file"),
3046 bformat(_("Error while reading the configuration file\n%1$s\n"
3047 "Falling back to default.\n"
3048 "Please look under Tools>Preferences>User Interface and\n"
3049 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3050 return readUIFile(defaultUIFile, false);
3053 QString const uifile = toqstr(ui_path.absFileName());
3054 if (uifiles.contains(uifile)) {
3056 // We are reading again the top uifile so reset the safeguard:
3059 d->toolbars_.reset();
3061 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3062 << "Is this an include loop?");
3066 uifiles.push_back(uifile);
3068 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3070 ReturnValues retval = readUIFile(ui_path);
3072 if (retval == FormatMismatch) {
3073 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3074 TempFile tmp("convertXXXXXX.ui");
3075 FileName const tempfile = tmp.name();
3076 bool const success = prefs2prefs(ui_path, tempfile, true);
3078 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3079 " to format " << LFUN_FORMAT << ".");
3081 retval = readUIFile(tempfile);
3085 if (retval != ReadOK) {
3086 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3094 settings.beginGroup("ui_files");
3095 bool touched = false;
3096 for (int i = 0; i != uifiles.size(); ++i) {
3097 QFileInfo fi(uifiles[i]);
3098 QDateTime const date_value = fi.lastModified();
3099 QString const name_key = QString::number(i);
3100 // if an ui file which defines Toolbars has changed,
3101 // we have to reset the settings
3102 if (toolbar_uifiles.contains(uifiles[i])
3103 && (!settings.contains(name_key)
3104 || settings.value(name_key).toString() != uifiles[i]
3105 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3107 settings.setValue(name_key, uifiles[i]);
3108 settings.setValue(name_key + "/date", date_value);
3111 settings.endGroup();
3113 settings.remove("views");
3119 void GuiApplication::onLastWindowClosed()
3121 if (d->global_menubar_)
3122 d->global_menubar_->grabKeyboard();
3126 void GuiApplication::startLongOperation() {
3127 d->key_checker_.start();
3131 bool GuiApplication::longOperationCancelled() {
3132 return d->key_checker_.pressed();
3136 void GuiApplication::stopLongOperation() {
3137 d->key_checker_.stop();
3141 bool GuiApplication::longOperationStarted() {
3142 return d->key_checker_.started();
3146 ////////////////////////////////////////////////////////////////////////
3148 // X11 specific stuff goes here...
3151 bool GuiApplication::x11EventFilter(XEvent * xev)
3156 switch (xev->type) {
3157 case SelectionRequest: {
3158 if (xev->xselectionrequest.selection != XA_PRIMARY)
3160 LYXERR(Debug::SELECTION, "X requested selection.");
3161 BufferView * bv = current_view_->currentBufferView();
3163 docstring const sel = bv->requestSelection();
3165 d->selection_.put(sel);
3166 // Refresh the selection request timestamp.
3167 // We have to do this by ourselves as Qt seems
3168 // not doing that, maybe because of our
3169 // "persistent selection" implementation
3170 // (see comments in GuiSelection.cpp).
3171 XSelectionEvent nev;
3172 nev.type = SelectionNotify;
3173 nev.display = xev->xselectionrequest.display;
3174 nev.requestor = xev->xselectionrequest.requestor;
3175 nev.selection = xev->xselectionrequest.selection;
3176 nev.target = xev->xselectionrequest.target;
3177 nev.property = 0L; // None
3178 nev.time = CurrentTime;
3179 XSendEvent(QX11Info::display(),
3180 nev.requestor, False, 0,
3181 reinterpret_cast<XEvent *>(&nev));
3187 case SelectionClear: {
3188 if (xev->xselectionclear.selection != XA_PRIMARY)
3190 LYXERR(Debug::SELECTION, "Lost selection.");
3191 BufferView * bv = current_view_->currentBufferView();
3193 bv->clearSelection();
3199 #elif defined(QPA_XCB)
3200 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3201 void * message, long *)
3203 if (!current_view_ || eventType != "xcb_generic_event_t")
3206 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3208 switch (ev->response_type) {
3209 case XCB_SELECTION_REQUEST: {
3210 xcb_selection_request_event_t * srev =
3211 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3212 if (srev->selection != XCB_ATOM_PRIMARY)
3214 LYXERR(Debug::SELECTION, "X requested selection.");
3215 BufferView * bv = current_view_->currentBufferView();
3217 docstring const sel = bv->requestSelection();
3219 d->selection_.put(sel);
3220 #ifdef HAVE_QT5_X11_EXTRAS
3221 // Refresh the selection request timestamp.
3222 // We have to do this by ourselves as Qt seems
3223 // not doing that, maybe because of our
3224 // "persistent selection" implementation
3225 // (see comments in GuiSelection.cpp).
3226 xcb_selection_notify_event_t nev;
3227 nev.response_type = XCB_SELECTION_NOTIFY;
3228 nev.requestor = srev->requestor;
3229 nev.selection = srev->selection;
3230 nev.target = srev->target;
3231 nev.property = XCB_NONE;
3232 nev.time = XCB_CURRENT_TIME;
3233 xcb_connection_t * con = QX11Info::connection();
3234 xcb_send_event(con, 0, srev->requestor,
3235 XCB_EVENT_MASK_NO_EVENT,
3236 reinterpret_cast<char const *>(&nev));
3244 case XCB_SELECTION_CLEAR: {
3245 xcb_selection_clear_event_t * scev =
3246 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3247 if (scev->selection != XCB_ATOM_PRIMARY)
3249 LYXERR(Debug::SELECTION, "Lost selection.");
3250 BufferView * bv = current_view_->currentBufferView();
3252 bv->clearSelection();
3260 } // namespace frontend
3263 void hideDialogs(std::string const & name, Inset * inset)
3266 frontend::guiApp->hideDialogs(name, inset);
3270 ////////////////////////////////////////////////////////////////////
3274 ////////////////////////////////////////////////////////////////////
3276 frontend::FontLoader & theFontLoader()
3278 LAPPERR(frontend::guiApp);
3279 return frontend::guiApp->fontLoader();
3283 frontend::FontMetrics const & theFontMetrics(Font const & f)
3285 return theFontMetrics(f.fontInfo());
3289 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3291 LAPPERR(frontend::guiApp);
3292 return frontend::guiApp->fontLoader().metrics(f);
3296 ////////////////////////////////////////////////////////////////////
3300 ////////////////////////////////////////////////////////////////////
3302 frontend::Clipboard & theClipboard()
3304 LAPPERR(frontend::guiApp);
3305 return frontend::guiApp->clipboard();
3309 frontend::Selection & theSelection()
3311 LAPPERR(frontend::guiApp);
3312 return frontend::guiApp->selection();
3318 #include "moc_GuiApplication.cpp"