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"
86 #include <QFontDatabase>
90 #include <QDesktopWidget>
94 #include <QFileOpenEvent>
98 #include <QImageReader>
101 #include <QLibraryInfo>
107 #include <QPixmapCache>
109 #include <QSessionManager>
111 #include <QShowEvent>
112 #include <QSocketNotifier>
113 #include <QSortFilterProxyModel>
114 #include <QStandardItemModel>
115 #include <QTextCodec>
117 #include <QTranslator>
118 #include <QThreadPool>
122 #include <X11/Xatom.h>
123 #include <X11/Xlib.h>
127 #elif defined(QPA_XCB)
129 #ifdef HAVE_QT5_X11_EXTRAS
130 #include <QtX11Extras/QX11Info>
134 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
135 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
136 #if (QT_VERSION < 0x050000)
137 #include <QWindowsMime>
138 #define QWINDOWSMIME QWindowsMime
141 #define QWINDOWSMIME QWinMime
151 #include <QMacPasteboardMime>
154 #include <boost/crc.hpp>
161 using namespace lyx::support;
164 static void initializeResources()
166 static bool initialized = false;
168 Q_INIT_RESOURCE(Resources);
176 frontend::Application * createApplication(int & argc, char * argv[])
178 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
179 // prune -geometry argument(s) by shifting
180 // the following ones 2 places down.
181 for (int i = 0 ; i < argc ; ++i) {
182 if (strcmp(argv[i], "-geometry") == 0) {
183 int const remove = (i+1) < argc ? 2 : 1;
185 for (int j = i; j < argc; ++j)
186 argv[j] = argv[j + remove];
192 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
193 // On Windows, allow bringing the LyX window to top
194 AllowSetForegroundWindow(ASFW_ANY);
197 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
198 // I'd rather do that in the constructor, but I do not think that
199 // the palette is accessible there.
200 guiApp->colorCache().setPalette(guiApp->palette());
209 if (lyxrc.gui_language == "auto") {
210 theLocale = QLocale::system();
211 code = fromqstr(theLocale.name());
213 Language const * l = languages.getLanguage(lyxrc.gui_language);
214 code = l ? l->code() : "C";
215 theLocale = QLocale(toqstr(code));
217 // Qt tries to outsmart us and transforms en_US to C.
218 Messages::guiLanguage((code == "C") ? "en_US" : code);
219 QLocale::setDefault(theLocale);
220 setlocale(LC_NUMERIC, "C");
227 /// Return the list of loadable formats.
228 vector<string> loadableImageFormats()
232 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
234 LYXERR(Debug::GRAPHICS,
235 "\nThe image loader can load the following directly:\n");
237 if (qt_formats.empty())
238 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
240 bool jpeg_found = false;
241 bool jpg_found = false;
242 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
244 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
246 string ext = ascii_lowercase((const char *) *it);
254 else if (ext == "jpg") {
259 else if (lyxrc.use_converter_cache &&
260 (ext == "svg" || ext == "svgz") &&
261 theConverters().isReachable("svg", "png"))
262 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
263 // the SVG as in the output. However we require that the converter
264 // cache is enabled since this is expensive. We also require that
265 // an explicit svg->png converter is defined, since the default
266 // converter could produce bad quality as well. This assumes that
267 // png can always be loaded.
276 ////////////////////////////////////////////////////////////////////////
278 // Icon loading support code
280 ////////////////////////////////////////////////////////////////////////
290 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
292 return lhs.key < rhs.key;
298 CompareKey(QString const & name) : name_(name) {}
299 bool operator()(ImgMap const & other) const { return other.key == name_; }
305 // this must be sorted alphabetically
306 // Upper case comes before lower case
307 // Please don't change the formatting, this list is parsed by
308 // development/tools/generate_symbols_images.py.
309 ImgMap sorted_img_map[] = {
310 { "Arrownot", "arrownot2"},
311 { "Arrowvert", "arrowvert2"},
312 { "Bowtie", "bowtie2" },
314 { "Bumpeq", "bumpeq2" },
315 { "CIRCLE", "circle3" },
317 { "CheckedBox", "checkedbox2" },
318 { "Circle", "circle2" },
319 { "Colonapprox", "colonapprox2" },
320 { "Coloneq", "coloneq2" },
321 { "Coloneqq", "coloneqq2" },
322 { "Colonsim", "colonsim2" },
324 { "DOWNarrow", "downarrow3" },
325 { "Delta", "delta2" },
326 { "Diamond", "diamond2" },
327 { "Doteq", "doteq2" },
328 { "Downarrow", "downarrow2" },
329 { "Eqcolon", "eqcolon2" },
330 { "Eqqcolon", "eqqcolon2" },
331 { "Gamma", "gamma2" },
333 { "LEFTCIRCLE", "leftcircle3" },
334 { "LEFTarrow", "leftarrow3" },
335 { "LEFTcircle", "leftcircle4" },
337 { "Lambda", "lambda2" },
339 { "Leftarrow", "leftarrow2" },
340 { "Leftcircle", "leftcircle2" },
341 { "Leftrightarrow", "leftrightarrow2" },
342 { "Longarrownot", "longarrownot2"},
343 { "Longleftarrow", "longleftarrow2" },
344 { "Longleftrightarrow", "longleftrightarrow2" },
345 { "Longmapsfrom", "longmapsfrom2"},
346 { "Longmapsto", "longmapsto2"},
347 { "Longrightarrow", "longrightarrow2" },
348 { "Mapsfrom", "mapsfrom2"},
349 { "Mapsfromchar", "mapsfromchar2"},
350 { "Mapsto", "mapsto2"},
351 { "Mapstochar", "mapstochar2"},
352 { "Omega", "omega2" },
357 { "RIGHTCIRCLE", "rightcircle3" },
358 { "RIGHTarrow", "rightarrow3" },
359 { "RIGHTcircle", "rightcircle4" },
361 { "Rightarrow", "rightarrow2" },
362 { "Rightcircle", "rightcircle2" },
363 { "Sigma", "sigma2" },
364 { "Square", "square2" },
365 { "Subset", "subset2" },
366 { "Supset", "supset2" },
367 { "Theta", "theta2" },
368 { "Thorn", "thorn2" },
369 { "UParrow", "uparrow3" },
370 { "Uparrow", "uparrow2" },
371 { "Updownarrow", "updownarrow2" },
372 { "Upsilon", "upsilon2" },
373 { "Vdash", "vdash3" },
378 { "lVert", "vert2" },
380 { "nLeftarrow", "nleftarrow2" },
381 { "nLeftrightarrow", "nleftrightarrow2" },
382 { "nRightarrow", "nrightarrow2" },
383 { "nVDash", "nvdash3" },
384 { "nVdash", "nvdash4" },
385 { "nvDash", "nvdash2" },
386 { "rVert", "vert2" },
388 { "textrm \\AA", "textrm_AA"},
389 { "textrm \\O", "textrm_O"},
390 { "vDash", "vdash2" },
391 { "varDelta", "vardelta2" },
392 { "varGamma", "vargamma2" },
393 { "varLambda", "varlambda2" },
394 { "varOmega", "varomega2" },
395 { "varPhi", "varphi2" },
396 { "varPi", "varpi2" },
397 { "varPsi", "varpsi2" },
398 { "varSigma", "varsigma2" },
399 { "varTheta", "vartheta2" },
400 { "varUpsilon", "varupsilon2" },
401 { "varXi", "varxi2" }
405 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
407 // This list specifies which system's theme icon is related to which lyx
408 // command. It was based on:
409 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
410 // this must be sorted alphabetically
411 // Upper case comes before lower case
412 ImgMap sorted_theme_icon_map[] = {
413 { "bookmark-goto 0", "go-jump" },
414 { "buffer-new", "document-new" },
415 { "buffer-write", "document-save" },
416 { "buffer-write-as", "document-save-as" },
417 { "buffer-zoom-in", "zoom-in" },
418 { "buffer-zoom-out", "zoom-out" },
419 { "copy", "edit-copy" },
420 { "cut", "edit-cut" },
421 { "depth-decrement", "format-indent-less" },
422 { "depth-increment", "format-indent-more" },
423 { "dialog-show spellchecker", "tools-check-spelling" },
424 { "dialog-show-new-inset graphics", "insert-image" },
425 { "dialog-toggle findreplaceadv", "edit-find-replace" },
426 { "file-open", "document-open" },
427 { "font-bold", "format-text-bold" },
428 { "font-ital", "format-text-italic" },
429 { "font-strikeout", "format-text-strikethrough" },
430 { "font-underline", "format-text-underline" },
431 { "lyx-quit", "application-exit" },
432 { "paste", "edit-paste" },
433 { "redo", "edit-redo" },
434 { "undo", "edit-undo" },
435 { "window-close", "window-close" },
436 { "window-new", "window-new" }
439 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
442 QString findImg(QString const & name)
444 ImgMap const * const begin = sorted_img_map;
445 ImgMap const * const end = begin + nr_sorted_img_map;
446 LATTEST(sorted(begin, end));
448 ImgMap const * const it = find_if(begin, end, CompareKey(name));
452 img_name = it->value;
455 img_name.replace('_', "underscore");
456 img_name.replace(' ', '_');
458 // This way we can have "math-delim { }" on the toolbar.
459 img_name.replace('(', "lparen");
460 img_name.replace(')', "rparen");
461 img_name.replace('[', "lbracket");
462 img_name.replace(']', "rbracket");
463 img_name.replace('{', "lbrace");
464 img_name.replace('}', "rbrace");
465 img_name.replace('|', "bars");
466 img_name.replace(',', "thinspace");
467 img_name.replace(':', "mediumspace");
468 img_name.replace(';', "thickspace");
469 img_name.replace('!', "negthinspace");
472 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
473 << "Looking for math icon called \"" << img_name << '"');
480 QString themeIconName(QString const & action)
482 ImgMap const * const begin = sorted_theme_icon_map;
483 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
484 LASSERT(sorted(begin, end), /**/);
486 ImgMap const * const it = find_if(begin, end, CompareKey(action));
494 QString iconName(FuncRequest const & f, bool unknown)
496 initializeResources();
500 switch (f.action()) {
501 case LFUN_MATH_INSERT:
502 if (!f.argument().empty()) {
504 name1 = findImg(toqstr(f.argument()).mid(1));
507 case LFUN_MATH_DELIM:
508 case LFUN_MATH_BIGDELIM:
510 name1 = findImg(toqstr(f.argument()));
514 name1 = toqstr(f.argument());
516 case LFUN_COMMAND_ALTERNATIVES: {
517 // use the first of the alternative commands
519 docstring dummy = split(f.argument(), firstcom, ';');
520 name1 = toqstr(firstcom);
521 name1.replace(' ', '_');
525 name2 = toqstr(lyxaction.getActionName(f.action()));
528 if (!f.argument().empty()) {
529 name1 = name2 + ' ' + toqstr(f.argument());
530 name1.replace(' ', '_');
531 name1.replace('\\', "backslash");
535 QStringList imagedirs;
536 imagedirs << "images/" << "images/ipa/";
537 search_mode mode = theGuiApp()->imageSearchMode();
538 for (int i = 0; i < imagedirs.size(); ++i) {
539 QString imagedir = imagedirs.at(i) + path;
540 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
542 return toqstr(fname.absFileName());
544 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
546 return toqstr(fname.absFileName());
549 path = ":/images/" + path;
552 LYXERR0("Directory " << path << " not found in resource!");
555 if (res.exists(name1 + ".svgz"))
556 return path + name1 + ".svgz";
557 else if (res.exists(name1 + ".png"))
558 return path + name1 + ".png";
560 if (res.exists(name2 + ".svgz"))
561 return path + name2 + ".svgz";
562 else if (res.exists(name2 + ".png"))
563 return path + name2 + ".png";
565 LYXERR(Debug::GUI, "Cannot find icon with filename "
566 << "\"" << name1 << ".{svgz,png}\""
568 << "\"" << name2 << ".{svgz,png}\""
570 << lyxaction.getActionName(f.action())
571 << '(' << to_utf8(f.argument()) << ")\"");
574 QString imagedir = "images/";
575 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
577 return toqstr(fname.absFileName());
578 return QString(":/images/unknown.svgz");
585 bool getPixmap(QPixmap & pixmap, QString const & path)
587 return pixmap.load(path);
591 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
593 QString imagedir = path;
594 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
595 QString fpath = toqstr(fname.absFileName());
596 QPixmap pixmap = QPixmap();
598 if (getPixmap(pixmap, fpath)) {
602 QStringList exts = ext.split(",");
603 fpath = ":/" + path + name + ".";
604 for (int i = 0; i < exts.size(); ++i) {
605 if (getPixmap(pixmap, fpath + exts.at(i))) {
610 bool const list = ext.contains(",");
611 LYXERR0("Cannot load pixmap \""
612 << path << name << "." << (list ? "{" : "") << ext
613 << (list ? "}" : "") << "\", please verify resource system!");
619 QIcon getIcon(FuncRequest const & f, bool unknown)
621 #if (QT_VERSION >= 0x040600)
622 if (lyxrc.use_system_theme_icons) {
623 // use the icons from system theme that are available
624 QString action = toqstr(lyxaction.getActionName(f.action()));
625 if (!f.argument().empty())
626 action += " " + toqstr(f.argument());
627 QString const theme_icon = themeIconName(action);
628 if (QIcon::hasThemeIcon(theme_icon)) {
629 QIcon const thmicn = QIcon::fromTheme(theme_icon);
630 if (!thmicn.isNull())
636 QString icon = iconName(f, unknown);
640 //LYXERR(Debug::GUI, "Found icon: " << icon);
641 QPixmap pixmap = QPixmap();
642 if (!getPixmap(pixmap,icon)) {
643 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
647 return QIcon(pixmap);
651 ////////////////////////////////////////////////////////////////////////
653 // LyX server support code.
655 ////////////////////////////////////////////////////////////////////////
657 class SocketNotifier : public QSocketNotifier
660 /// connect a connection notification from the LyXServerSocket
661 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
662 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
666 /// The callback function
667 Application::SocketCallback func_;
671 ////////////////////////////////////////////////////////////////////////
673 // Mac specific stuff goes here...
675 ////////////////////////////////////////////////////////////////////////
677 class MenuTranslator : public QTranslator
680 MenuTranslator(QObject * parent)
681 : QTranslator(parent)
684 #if QT_VERSION >= 0x050000
685 virtual QString translate(const char * /* context */,
686 const char *sourceText,
687 const char * /* disambiguation */ = 0, int /* n */ = -1) const
689 QString translate(const char * /*context*/,
690 const char * sourceText,
691 const char * /*comment*/ = 0) const
694 string const s = sourceText;
695 if (s == N_("About %1") || s == N_("Preferences")
696 || s == N_("Reconfigure") || s == N_("Quit %1"))
704 // QMacPasteboardMimeGraphics can only be compiled on Mac.
706 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
709 QMacPasteboardMimeGraphics()
710 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
713 QString convertorName() { return "Graphics"; }
715 QString flavorFor(QString const & mime)
717 LYXERR(Debug::ACTION, "flavorFor " << mime);
718 if (mime == pdfMimeType())
719 return QLatin1String("com.adobe.pdf");
723 QString mimeFor(QString flav)
725 LYXERR(Debug::ACTION, "mimeFor " << flav);
726 if (flav == QLatin1String("com.adobe.pdf"))
727 return pdfMimeType();
731 bool canConvert(QString const & mime, QString flav)
733 return mimeFor(flav) == mime;
736 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
740 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
744 QList<QByteArray> convertFromMime(QString const & /*mime*/,
745 QVariant data, QString /*flav*/)
747 QList<QByteArray> ret;
748 ret.append(data.toByteArray());
754 ///////////////////////////////////////////////////////////////
756 // You can find more platform specific stuff at the end of this file...
758 ///////////////////////////////////////////////////////////////
760 ////////////////////////////////////////////////////////////////////////
761 // Windows specific stuff goes here...
763 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
764 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
765 // QWindowsMimeMetafile can only be compiled on Windows.
767 static FORMATETC cfFromMime(QString const & mimetype)
770 if (mimetype == emfMimeType()) {
771 formatetc.cfFormat = CF_ENHMETAFILE;
772 formatetc.tymed = TYMED_ENHMF;
773 } else if (mimetype == wmfMimeType()) {
774 formatetc.cfFormat = CF_METAFILEPICT;
775 formatetc.tymed = TYMED_MFPICT;
778 formatetc.dwAspect = DVASPECT_CONTENT;
779 formatetc.lindex = -1;
784 class QWindowsMimeMetafile : public QWINDOWSMIME {
786 QWindowsMimeMetafile() {}
788 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
789 QMimeData const * /*mimedata*/) const
794 bool canConvertToMime(QString const & mimetype,
795 IDataObject * pDataObj) const
797 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
799 FORMATETC formatetc = cfFromMime(mimetype);
800 return pDataObj->QueryGetData(&formatetc) == S_OK;
803 bool convertFromMime(FORMATETC const & /*formatetc*/,
804 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
809 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
810 QVariant::Type /*preferredType*/) const
813 if (!canConvertToMime(mimetype, pDataObj))
816 FORMATETC formatetc = cfFromMime(mimetype);
818 if (pDataObj->GetData(&formatetc, &s) != S_OK)
822 if (s.tymed == TYMED_ENHMF) {
823 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
824 data.resize(dataSize);
825 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
826 (LPBYTE)data.data());
827 } else if (s.tymed == TYMED_MFPICT) {
828 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
829 data.resize(dataSize);
830 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
831 (LPBYTE)data.data());
834 ReleaseStgMedium(&s);
840 QVector<FORMATETC> formatsForMime(QString const & mimetype,
841 QMimeData const * /*mimedata*/) const
843 QVector<FORMATETC> formats;
844 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
845 formats += cfFromMime(mimetype);
849 QString mimeForFormat(FORMATETC const & formatetc) const
851 switch (formatetc.cfFormat) {
853 return emfMimeType();
854 case CF_METAFILEPICT:
855 return wmfMimeType();
865 /// Allows to check whether ESC was pressed during a long operation
866 class KeyChecker : public QObject {
871 KeyChecker() : pressed_(false), started_(false) {}
874 QCoreApplication::instance()->installEventFilter(this);
879 QCoreApplication::instance()->removeEventFilter(this);
883 QCoreApplication::processEvents();
886 bool started() const {
889 bool eventFilter(QObject *obj, QEvent *event) {
890 LYXERR(Debug::ACTION, "Event Type: " << event->type());
891 switch (event->type()) {
895 case QEvent::UpdateRequest:
896 case QEvent::CursorChange:
897 case QEvent::ActionChanged:
898 case QEvent::EnabledChange:
899 case QEvent::SockAct:
902 case QEvent::ToolTipChange:
903 case QEvent::LayoutRequest:
904 case QEvent::MetaCall:
905 return QObject::eventFilter(obj, event);
907 // FIXME Blocking all these events is a bad idea.
908 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
909 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
917 ////////////////////////////////////////////////////////////////////////
918 // GuiApplication::Private definition and implementation.
919 ////////////////////////////////////////////////////////////////////////
921 struct GuiApplication::Private
923 Private(): language_model_(0), meta_fake_bit(NoModifier),
926 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
927 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
928 /// WMF Mime handler for Windows clipboard.
929 wmf_mime_ = new QWindowsMimeMetafile;
932 initKeySequences(&theTopLevelKeymap());
935 void initKeySequences(KeyMap * kb)
937 keyseq = KeySequence(kb, kb);
938 cancel_meta_seq = KeySequence(kb, kb);
942 QSortFilterProxyModel * language_model_;
944 GuiClipboard clipboard_;
946 GuiSelection selection_;
948 FontLoader font_loader_;
950 ColorCache color_cache_;
952 QTranslator qt_trans_;
954 QHash<int, SocketNotifier *> socket_notifiers_;
958 /// The global instance
961 /// this timer is used for any regular events one wants to
962 /// perform. at present it is used to check if forked processes
964 QTimer general_timer_;
966 /// delayed FuncRequests
967 std::queue<FuncRequest> func_request_queue_;
972 KeySequence cancel_meta_seq;
974 KeyModifier meta_fake_bit;
976 /// The result of last dispatch action
977 DispatchResult dispatch_result_;
979 /// Multiple views container.
981 * Warning: This must not be a smart pointer as the destruction of the
982 * object is handled by Qt when the view is closed
983 * \sa Qt::WA_DeleteOnClose attribute.
985 QHash<int, GuiView *> views_;
987 /// Only used on mac.
988 QMenuBar * global_menubar_;
991 /// Linkback mime handler for MacOSX.
992 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
995 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
996 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
997 /// WMF Mime handler for Windows clipboard.
998 QWindowsMimeMetafile * wmf_mime_;
1002 /// Allows to check whether ESC was pressed during a long operation
1003 KeyChecker key_checker_;
1007 GuiApplication * guiApp;
1009 GuiApplication::~GuiApplication()
1012 closeAllLinkBackLinks();
1018 GuiApplication::GuiApplication(int & argc, char ** argv)
1019 : QApplication(argc, argv), current_view_(0),
1020 d(new GuiApplication::Private)
1022 QString app_name = "LyX";
1023 QCoreApplication::setOrganizationName(app_name);
1024 QCoreApplication::setOrganizationDomain("lyx.org");
1025 QCoreApplication::setApplicationName(lyx_package);
1026 #if QT_VERSION >= 0x050000
1027 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1030 qsrand(QDateTime::currentDateTime().toTime_t());
1032 // Install translator for GUI elements.
1033 installTranslator(&d->qt_trans_);
1036 // Enable reception of XCB events.
1037 installNativeEventFilter(this);
1040 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1041 // lyxrc setting for this in order to let the application stay resident.
1042 // But then we need some kind of dock icon, at least on Windows.
1044 if (lyxrc.quit_on_last_window_closed)
1045 setQuitOnLastWindowClosed(false);
1048 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1049 // seems to be the default case for applications like LyX.
1050 setQuitOnLastWindowClosed(false);
1051 // This allows to translate the strings that appear in the LyX menu.
1052 /// A translator suitable for the entries in the LyX menu.
1053 /// Only needed with Qt/Mac.
1054 installTranslator(new MenuTranslator(this));
1059 #if defined(Q_WS_X11) || defined(QPA_XCB)
1060 // doubleClickInterval() is 400 ms on X11 which is just too long.
1061 // On Windows and Mac OS X, the operating system's value is used.
1062 // On Microsoft Windows, calling this function sets the double
1063 // click interval for all applications. So we don't!
1064 QApplication::setDoubleClickInterval(300);
1067 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1069 // needs to be done before reading lyxrc
1071 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1075 // Set the cache to 5120 kilobytes which corresponds to screen size of
1076 // 1280 by 1024 pixels with a color depth of 32 bits.
1077 QPixmapCache::setCacheLimit(5120);
1079 // Initialize RC Fonts
1080 if (lyxrc.roman_font_name.empty())
1081 lyxrc.roman_font_name = fromqstr(romanFontName());
1083 if (lyxrc.sans_font_name.empty())
1084 lyxrc.sans_font_name = fromqstr(sansFontName());
1086 if (lyxrc.typewriter_font_name.empty())
1087 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1089 d->general_timer_.setInterval(500);
1090 connect(&d->general_timer_, SIGNAL(timeout()),
1091 this, SLOT(handleRegularEvents()));
1092 d->general_timer_.start();
1094 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1095 // This is clearly not enough in a time where we use threads for
1096 // document preview and/or export. 20 should be OK.
1097 QThreadPool::globalInstance()->setMaxThreadCount(20);
1099 // make sure tooltips are formatted
1100 installEventFilter(new ToolTipFormatter(this));
1104 GuiApplication * theGuiApp()
1106 return dynamic_cast<GuiApplication *>(theApp());
1110 double GuiApplication::pixelRatio() const
1112 #if QT_VERSION >= 0x050000
1113 return qt_scale_factor * devicePixelRatio();
1120 void GuiApplication::clearSession()
1127 docstring Application::iconName(FuncRequest const & f, bool unknown)
1129 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1133 docstring Application::mathIcon(docstring const & c)
1135 return qstring_to_ucs4(findImg(toqstr(c)));
1139 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1143 BufferView * bv = 0;
1144 BufferView * doc_bv = 0;
1146 if (cmd.action() == LFUN_NOACTION) {
1147 status.message(from_utf8(N_("Nothing to do")));
1148 status.setEnabled(false);
1151 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1152 status.setUnknown(true);
1153 status.message(from_utf8(N_("Unknown action")));
1154 status.setEnabled(false);
1157 // Does the GuiApplication know something?
1158 else if (getStatus(cmd, status)) { }
1160 // If we do not have a GuiView, then other functions are disabled
1161 else if (!current_view_)
1162 status.setEnabled(false);
1164 // Does the GuiView know something?
1165 else if (current_view_->getStatus(cmd, status)) { }
1167 // In LyX/Mac, when a dialog is open, the menus of the
1168 // application can still be accessed without giving focus to
1169 // the main window. In this case, we want to disable the menu
1170 // entries that are buffer or view-related.
1171 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1173 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1174 status.setEnabled(false);
1177 // If we do not have a BufferView, then other functions are disabled
1178 else if (!(bv = current_view_->currentBufferView()))
1179 status.setEnabled(false);
1181 // Does the current BufferView know something?
1182 else if (bv->getStatus(cmd, status)) { }
1184 // Does the current Buffer know something?
1185 else if (bv->buffer().getStatus(cmd, status)) { }
1187 // If we do not have a document BufferView, different from the
1188 // current BufferView, then other functions are disabled
1189 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1190 status.setEnabled(false);
1192 // Does the document Buffer know something?
1193 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1196 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1197 status.message(from_utf8(N_("Command not handled")));
1198 status.setEnabled(false);
1201 // the default error message if we disable the command
1202 if (!status.enabled() && status.message().empty())
1203 status.message(from_utf8(N_("Command disabled")));
1209 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1211 // I would really like to avoid having this switch and rather try to
1212 // encode this in the function itself.
1213 // -- And I'd rather let an inset decide which LFUNs it is willing
1214 // to handle (Andre')
1216 switch (cmd.action()) {
1218 // This could be used for the no-GUI version. The GUI version is handled in
1219 // GuiView::getStatus(). See above.
1221 case LFUN_BUFFER_WRITE:
1222 case LFUN_BUFFER_WRITE_AS: {
1223 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1224 enable = b && (b->isUnnamed() || !b->isClean());
1229 case LFUN_BOOKMARK_GOTO: {
1230 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1231 enable = theSession().bookmarks().isValid(num);
1235 case LFUN_BOOKMARK_CLEAR:
1236 enable = theSession().bookmarks().hasValid();
1239 // this one is difficult to get right. As a half-baked
1240 // solution, we consider only the first action of the sequence
1241 case LFUN_COMMAND_SEQUENCE: {
1242 // argument contains ';'-terminated commands
1243 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1244 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1245 func.setOrigin(cmd.origin());
1246 flag = getStatus(func);
1250 // we want to check if at least one of these is enabled
1251 case LFUN_COMMAND_ALTERNATIVES: {
1252 // argument contains ';'-terminated commands
1253 string arg = to_utf8(cmd.argument());
1254 while (!arg.empty()) {
1256 arg = split(arg, first, ';');
1257 FuncRequest func(lyxaction.lookupFunc(first));
1258 func.setOrigin(cmd.origin());
1259 flag = getStatus(func);
1260 // if this one is enabled, the whole thing is
1269 string name = to_utf8(cmd.argument());
1270 if (theTopLevelCmdDef().lock(name, func)) {
1271 func.setOrigin(cmd.origin());
1272 flag = getStatus(func);
1273 theTopLevelCmdDef().release(name);
1275 // catch recursion or unknown command
1276 // definition. all operations until the
1277 // recursion or unknown command definition
1278 // occurs are performed, so set the state to
1285 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1287 case LFUN_PREFERENCES_SAVE:
1288 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1289 case LFUN_DEBUG_LEVEL_SET:
1290 // these are handled in our dispatch()
1293 case LFUN_WINDOW_CLOSE:
1294 enable = d->views_.size() > 0;
1297 case LFUN_BUFFER_NEW:
1298 case LFUN_BUFFER_NEW_TEMPLATE:
1299 case LFUN_FILE_OPEN:
1300 case LFUN_HELP_OPEN:
1301 case LFUN_SCREEN_FONT_UPDATE:
1302 case LFUN_SET_COLOR:
1303 case LFUN_WINDOW_NEW:
1305 case LFUN_LYXRC_APPLY:
1306 case LFUN_COMMAND_PREFIX:
1308 case LFUN_META_PREFIX:
1309 case LFUN_RECONFIGURE:
1310 case LFUN_SERVER_GET_FILENAME:
1311 case LFUN_SERVER_NOTIFY:
1315 case LFUN_BUFFER_FORALL: {
1316 if (theBufferList().empty()) {
1317 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1318 flag.setEnabled(false);
1322 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1323 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1324 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1325 flag.setEnabled(false);
1330 case LFUN_DIALOG_SHOW: {
1331 string const name = cmd.getArg(0);
1332 return name == "aboutlyx"
1334 || name == "texinfo"
1335 || name == "progress"
1336 || name == "compare";
1344 flag.setEnabled(false);
1348 /// make a post-dispatch status message
1349 static docstring makeDispatchMessage(docstring const & msg,
1350 FuncRequest const & cmd)
1352 const bool verbose = (cmd.origin() == FuncRequest::MENU
1353 || cmd.origin() == FuncRequest::TOOLBAR
1354 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1356 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1357 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1361 docstring dispatch_msg = msg;
1362 if (!dispatch_msg.empty())
1363 dispatch_msg += ' ';
1365 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1367 bool argsadded = false;
1369 if (!cmd.argument().empty()) {
1370 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1371 comname += ' ' + cmd.argument();
1375 docstring const shortcuts = theTopLevelKeymap().
1376 printBindings(cmd, KeySequence::ForGui);
1378 if (!shortcuts.empty())
1379 comname += ": " + shortcuts;
1380 else if (!argsadded && !cmd.argument().empty())
1381 comname += ' ' + cmd.argument();
1383 if (!comname.empty()) {
1384 comname = rtrim(comname);
1385 dispatch_msg += '(' + rtrim(comname) + ')';
1387 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1388 return dispatch_msg;
1392 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1394 Buffer * buffer = 0;
1395 if (current_view_ && current_view_->currentBufferView()) {
1396 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1397 buffer = ¤t_view_->currentBufferView()->buffer();
1399 buffer->undo().beginUndoGroup();
1403 // redraw the screen at the end (first of the two drawing steps).
1404 // This is done unless explicitly requested otherwise
1405 dr.screenUpdate(Update::FitCursor);
1407 updateCurrentView(cmd, dr);
1409 // the buffer may have been closed by one action
1410 if (theBufferList().isLoaded(buffer) || theBufferList().isInternal(buffer))
1411 buffer->undo().endUndoGroup();
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_->restartCursor();
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 // Backup current_view_
1637 GuiView * view = current_view_;
1638 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1639 // to skip the refresh.
1641 theBufferList().changed(false);
1642 // Restore current_view_
1643 current_view_ = view;
1647 case LFUN_BUFFER_NEW:
1648 validateCurrentView();
1650 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1651 createView(QString(), false); // keep hidden
1652 current_view_->newDocument(to_utf8(cmd.argument()), false);
1653 current_view_->show();
1654 setActiveWindow(current_view_);
1656 current_view_->newDocument(to_utf8(cmd.argument()), false);
1660 case LFUN_BUFFER_NEW_TEMPLATE:
1661 validateCurrentView();
1663 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1665 current_view_->newDocument(to_utf8(cmd.argument()), true);
1666 if (!current_view_->documentBufferView())
1667 current_view_->close();
1669 current_view_->newDocument(to_utf8(cmd.argument()), true);
1673 case LFUN_FILE_OPEN: {
1674 // FIXME: normally the code below is not needed, since getStatus makes sure that
1675 // current_view_ is not null.
1676 validateCurrentView();
1677 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1678 string const fname = to_utf8(cmd.argument());
1679 bool const is_open = FileName::isAbsolute(fname)
1680 && theBufferList().getBuffer(FileName(fname));
1682 || (!lyxrc.open_buffers_in_tabs
1683 && current_view_->documentBufferView() != 0
1685 // We want the ui session to be saved per document and not per
1686 // window number. The filename crc is a good enough identifier.
1687 boost::crc_32_type crc;
1688 crc = for_each(fname.begin(), fname.end(), crc);
1689 createView(crc.checksum());
1690 current_view_->openDocument(fname);
1691 if (!current_view_->documentBufferView())
1692 current_view_->close();
1693 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1694 current_view_->raise();
1695 current_view_->activateWindow();
1696 current_view_->showNormal();
1699 current_view_->openDocument(fname);
1700 if (cmd.origin() == FuncRequest::LYXSERVER) {
1701 current_view_->raise();
1702 current_view_->activateWindow();
1703 current_view_->showNormal();
1709 case LFUN_HELP_OPEN: {
1710 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1711 if (current_view_ == 0)
1713 string const arg = to_utf8(cmd.argument());
1715 current_view_->message(_("Missing argument"));
1718 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1720 fname = i18nLibFileSearch("examples", arg, "lyx");
1722 if (fname.empty()) {
1723 lyxerr << "LyX: unable to find documentation file `"
1724 << arg << "'. Bad installation?" << endl;
1727 current_view_->message(bformat(_("Opening help file %1$s..."),
1728 makeDisplayPath(fname.absFileName())));
1729 Buffer * buf = current_view_->loadDocument(fname, false);
1731 buf->setReadonly(!current_view_->develMode());
1735 case LFUN_SET_COLOR: {
1737 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1738 if (lyx_name.empty() || x11_name.empty()) {
1740 current_view_->message(
1741 _("Syntax: set-color <lyx_name> <x11_name>"));
1746 // FIXME: The graphics cache no longer has a changeDisplay method.
1747 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1748 bool const graphicsbg_changed =
1749 lyx_name == graphicsbg && x11_name != graphicsbg;
1750 if (graphicsbg_changed)
1751 graphics::GCache::get().changeDisplay(true);
1754 if (!lcolor.setColor(lyx_name, x11_name)) {
1756 current_view_->message(
1757 bformat(_("Set-color \"%1$s\" failed "
1758 "- color is undefined or "
1759 "may not be redefined"),
1760 from_utf8(lyx_name)));
1763 // Make sure we don't keep old colors in cache.
1764 d->color_cache_.clear();
1765 // Update the current view
1766 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1770 case LFUN_LYXRC_APPLY: {
1771 // reset active key sequences, since the bindings
1772 // are updated (bug 6064)
1774 LyXRC const lyxrc_orig = lyxrc;
1776 istringstream ss(to_utf8(cmd.argument()));
1777 bool const success = lyxrc.read(ss);
1780 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1781 << "Unable to read lyxrc data"
1786 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1788 // If the request comes from the minibuffer, then we can't reset
1789 // the GUI, since that would destory the minibuffer itself and
1790 // cause a crash, since we are currently in one of the methods of
1791 // GuiCommandBuffer. See bug #8540.
1792 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1795 // FIXME Unfortunately, that leaves a bug here, since we cannot
1796 // reset the GUI in this case. If the changes to lyxrc affected the
1797 // UI, then, nothing would happen. This seems fairly unlikely, but
1798 // it definitely is a bug.
1803 case LFUN_COMMAND_PREFIX:
1804 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1809 d->meta_fake_bit = NoModifier;
1810 GuiView * gv = currentView();
1811 if (gv && gv->currentBufferView())
1812 // cancel any selection
1813 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1814 dr.setMessage(from_ascii(N_("Cancel")));
1817 case LFUN_META_PREFIX:
1818 d->meta_fake_bit = AltModifier;
1819 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1822 // --- Menus -----------------------------------------------
1823 case LFUN_RECONFIGURE:
1824 // argument is any additional parameter to the configure.py command
1825 reconfigure(to_utf8(cmd.argument()));
1828 // --- lyxserver commands ----------------------------
1829 case LFUN_SERVER_GET_FILENAME: {
1830 if (current_view_ && current_view_->documentBufferView()) {
1831 docstring const fname = from_utf8(
1832 current_view_->documentBufferView()->buffer().absFileName());
1833 dr.setMessage(fname);
1834 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1836 dr.setMessage(docstring());
1837 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1842 case LFUN_SERVER_NOTIFY: {
1843 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1844 dr.setMessage(dispatch_buffer);
1845 theServer().notifyClient(to_utf8(dispatch_buffer));
1849 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1850 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1856 string rest = split(argument, countstr, ' ');
1857 int const count = convert<int>(countstr);
1858 // an arbitrary number to limit number of iterations
1859 int const max_iter = 10000;
1860 if (count > max_iter) {
1861 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1864 for (int i = 0; i < count; ++i)
1865 dispatch(lyxaction.lookupFunc(rest));
1870 case LFUN_COMMAND_SEQUENCE: {
1871 // argument contains ';'-terminated commands
1872 string arg = argument;
1873 // FIXME: this LFUN should also work without any view.
1874 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1875 ? &(current_view_->documentBufferView()->buffer()) : 0;
1877 buffer->undo().beginUndoGroup();
1878 while (!arg.empty()) {
1880 arg = split(arg, first, ';');
1881 FuncRequest func(lyxaction.lookupFunc(first));
1882 func.setOrigin(cmd.origin());
1885 // the buffer may have been closed by one action
1886 if (theBufferList().isLoaded(buffer) || theBufferList().isInternal(buffer))
1887 buffer->undo().endUndoGroup();
1891 case LFUN_BUFFER_FORALL: {
1892 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1894 map<Buffer *, GuiView *> views_lVisible;
1895 map<GuiView *, Buffer *> activeBuffers;
1897 QList<GuiView *> allViews = d->views_.values();
1899 // this for does not modify any buffer. It just collects info on local
1900 // visibility of buffers and on which buffer is active in each view.
1901 Buffer * const last = theBufferList().last();
1902 for(GuiView * view : allViews) {
1903 // all of the buffers might be locally hidden. That is, there is no
1905 if (!view || !view->currentBufferView())
1906 activeBuffers[view] = 0;
1908 activeBuffers[view] = &view->currentBufferView()->buffer();
1910 // find out if each is locally visible or locally hidden.
1911 // we don't use a for loop as the buffer list cycles.
1912 Buffer * b = theBufferList().first();
1914 bool const locallyVisible = view && view->workArea(*b);
1915 if (locallyVisible) {
1916 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1917 // only need to overwrite/add if we don't already know a buffer is globally
1918 // visible or we do know but we would prefer to dispatch LFUN from the
1919 // current view because of cursor position issues.
1920 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1921 views_lVisible[b] = view;
1925 b = theBufferList().next(b);
1929 GuiView * const homeView = currentView();
1930 Buffer * b = theBufferList().first();
1931 Buffer * nextBuf = 0;
1932 int numProcessed = 0;
1935 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1937 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1939 // first change to a view where b is locally visible, preferably current_view_.
1940 GuiView * const vLv = views_lVisible[b];
1942 lyx::dispatch(funcToRun);
1950 // put things back to how they were (if possible).
1951 for (GuiView * view : allViews) {
1952 Buffer * originalBuf = activeBuffers[view];
1953 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1954 if (theBufferList().isLoaded(originalBuf))
1955 view->setBuffer(originalBuf);
1957 homeView->setFocus();
1959 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1963 case LFUN_COMMAND_ALTERNATIVES: {
1964 // argument contains ';'-terminated commands
1965 string arg = argument;
1966 while (!arg.empty()) {
1968 arg = split(arg, first, ';');
1969 FuncRequest func(lyxaction.lookupFunc(first));
1970 func.setOrigin(cmd.origin());
1971 FuncStatus const stat = getStatus(func);
1972 if (stat.enabled()) {
1982 if (theTopLevelCmdDef().lock(argument, func)) {
1983 func.setOrigin(cmd.origin());
1985 theTopLevelCmdDef().release(argument);
1987 if (func.action() == LFUN_UNKNOWN_ACTION) {
1988 // unknown command definition
1989 lyxerr << "Warning: unknown command definition `"
1993 // recursion detected
1994 lyxerr << "Warning: Recursion in the command definition `"
1995 << argument << "' detected"
2002 case LFUN_PREFERENCES_SAVE:
2003 lyxrc.write(support::makeAbsPath("preferences",
2004 package().user_support().absFileName()), false);
2007 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2008 string const fname = addName(addPath(package().user_support().absFileName(),
2009 "templates/"), "defaults.lyx");
2010 Buffer defaults(fname);
2012 istringstream ss(argument);
2017 // We need to make sure that, after we recreat the DocumentClass,
2018 // which we do in readHeader, we apply it to the document itself.
2019 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2020 int const unknown_tokens = defaults.readHeader(lex);
2021 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2023 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2024 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2026 if (unknown_tokens != 0) {
2027 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2028 << unknown_tokens << " unknown token"
2029 << (unknown_tokens == 1 ? "" : "s")
2033 if (defaults.writeFile(FileName(defaults.absFileName())))
2034 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2035 makeDisplayPath(fname)));
2038 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2043 case LFUN_BOOKMARK_GOTO:
2044 // go to bookmark, open unopened file and switch to buffer if necessary
2045 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2046 dr.screenUpdate(Update::Force | Update::FitCursor);
2049 case LFUN_BOOKMARK_CLEAR:
2050 theSession().bookmarks().clear();
2053 case LFUN_DEBUG_LEVEL_SET:
2054 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2057 case LFUN_DIALOG_SHOW: {
2058 string const name = cmd.getArg(0);
2060 if ( name == "aboutlyx"
2062 || name == "texinfo"
2063 || name == "progress"
2064 || name == "compare")
2066 // work around: on Mac OS the application
2067 // is not terminated when closing the last view.
2068 // Create a new one to be able to dispatch the
2069 // LFUN_DIALOG_SHOW to this view.
2070 if (current_view_ == 0)
2076 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2079 current_view_->dispatch(cmd, dr);
2083 if (cmd.origin() == FuncRequest::LYXSERVER)
2084 updateCurrentView(cmd, dr);
2088 docstring GuiApplication::viewStatusMessage()
2090 // When meta-fake key is pressed, show the key sequence so far + "M-".
2091 if (d->meta_fake_bit != NoModifier)
2092 return d->keyseq.print(KeySequence::ForGui) + "M-";
2094 // Else, when a non-complete key sequence is pressed,
2095 // show the available options.
2096 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2097 return d->keyseq.printOptions(true);
2103 void GuiApplication::handleKeyFunc(FuncCode action)
2107 if (d->keyseq.length())
2109 GuiView * gv = currentView();
2110 LASSERT(gv && gv->currentBufferView(), return);
2111 BufferView * bv = gv->currentBufferView();
2112 bv->getIntl().getTransManager().deadkey(
2113 c, get_accent(action).accent, bv->cursor().innerText(),
2115 // Need to clear, in case the minibuffer calls these
2118 // copied verbatim from do_accent_char
2119 bv->cursor().resetAnchor();
2123 //Keep this in sync with GuiApplication::processKeySym below
2124 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2125 KeyModifier state) const
2127 // Do nothing if we have nothing
2128 if (!keysym.isOK() || keysym.isModifier())
2130 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2132 FuncRequest func = seq.addkey(keysym, state);
2133 // When not cancel or meta-fake, do the normal lookup.
2134 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2136 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2138 // Maybe user can only reach the key via holding down shift.
2139 // Let's see. But only if shift is the only modifier
2140 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2141 // If addkey looked up a command and did not find further commands then
2142 // seq has been reset at this point
2143 func = seq.addkey(keysym, NoModifier);
2145 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2146 << seq.print(KeySequence::Portable) << ']');
2147 return func.action() != LFUN_UNKNOWN_ACTION;
2151 //Keep this in sync with GuiApplication::queryKeySym above
2152 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2154 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2156 // Do nothing if we have nothing (JMarc)
2157 if (!keysym.isOK() || keysym.isModifier()) {
2159 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2161 current_view_->restartCursor();
2165 char_type encoded_last_key = keysym.getUCSEncoded();
2167 // Do a one-deep top-level lookup for
2168 // cancel and meta-fake keys. RVDK_PATCH_5
2169 d->cancel_meta_seq.reset();
2171 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2172 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2174 // When not cancel or meta-fake, do the normal lookup.
2175 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2176 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2177 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2178 // remove Caps Lock and Mod2 as a modifiers
2179 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2180 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2183 // Dont remove this unless you know what you are doing.
2184 d->meta_fake_bit = NoModifier;
2186 // Can this happen now ?
2187 if (func.action() == LFUN_NOACTION)
2188 func = FuncRequest(LFUN_COMMAND_PREFIX);
2190 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2191 << d->keyseq.print(KeySequence::Portable) << ']');
2193 // already here we know if it any point in going further
2194 // why not return already here if action == -1 and
2195 // num_bytes == 0? (Lgb)
2197 if (d->keyseq.length() > 1 && current_view_)
2198 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2201 // Maybe user can only reach the key via holding down shift.
2202 // Let's see. But only if shift is the only modifier
2203 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2204 LYXERR(Debug::KEY, "Trying without shift");
2205 // If addkey looked up a command and did not find further commands then
2206 // seq has been reset at this point
2207 func = d->keyseq.addkey(keysym, NoModifier);
2208 LYXERR(Debug::KEY, "Action now " << func.action());
2211 if (func.action() == LFUN_UNKNOWN_ACTION) {
2212 // We didn't match any of the key sequences.
2213 // See if it's normal insertable text not already
2214 // covered by a binding
2215 if (keysym.isText() && d->keyseq.length() == 1) {
2216 // Non-printable characters (such as ASCII control characters)
2217 // must not be inserted (#5704)
2218 if (!isPrintable(encoded_last_key)) {
2219 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2221 current_view_->restartCursor();
2224 // The following modifier check is not needed on Mac.
2225 // The keysym is either not text or it is different
2226 // from the non-modifier keysym. See #9875 for the
2227 // broken alt-modifier effect of having this code active.
2228 #if !defined(Q_OS_MAC)
2229 // If a non-Shift Modifier is used we have a non-bound key sequence
2230 // (such as Alt+j = j). This should be omitted (#5575).
2231 // On Windows, AltModifier and ControlModifier are both
2232 // set when AltGr is pressed. Therefore, in order to not
2233 // break AltGr-bound symbols (see #5575 for details),
2234 // unbound Ctrl+Alt key sequences are allowed.
2235 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2236 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2237 && !(state & AltModifier && state & ControlModifier)
2241 if (current_view_) {
2242 current_view_->message(_("Unknown function."));
2243 current_view_->restartCursor();
2248 // Since all checks above were passed, we now really have text that
2249 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2250 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2252 LYXERR(Debug::KEY, "isText() is true, inserting.");
2253 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2255 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2256 if (current_view_) {
2257 current_view_->message(_("Unknown function."));
2258 current_view_->restartCursor();
2264 if (func.action() == LFUN_SELF_INSERT) {
2265 if (encoded_last_key != 0) {
2266 docstring const arg(1, encoded_last_key);
2267 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2268 FuncRequest::KEYBOARD));
2269 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2272 processFuncRequest(func);
2276 void GuiApplication::processFuncRequest(FuncRequest const & func)
2278 lyx::dispatch(func);
2282 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2284 addToFuncRequestQueue(func);
2285 processFuncRequestQueueAsync();
2289 void GuiApplication::processFuncRequestQueue()
2291 while (!d->func_request_queue_.empty()) {
2292 processFuncRequest(d->func_request_queue_.front());
2293 d->func_request_queue_.pop();
2298 void GuiApplication::processFuncRequestQueueAsync()
2300 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2304 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2306 d->func_request_queue_.push(func);
2310 void GuiApplication::resetGui()
2312 // Set the language defined by the user.
2316 if (!readUIFile(toqstr(lyxrc.ui_file)))
2317 // Gives some error box here.
2320 if (d->global_menubar_)
2321 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2323 QHash<int, GuiView *>::iterator it;
2324 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2327 gv->setLayoutDirection(layoutDirection());
2331 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2335 void GuiApplication::createView(int view_id)
2337 createView(QString(), true, view_id);
2341 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2344 // release the keyboard which might have been grabed by the global
2345 // menubar on Mac to catch shortcuts even without any GuiView.
2346 if (d->global_menubar_)
2347 d->global_menubar_->releaseKeyboard();
2351 while (d->views_.find(id) != d->views_.end())
2354 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2355 GuiView * view = new GuiView(id);
2356 // `view' is the new current_view_. Tell coverity that is is not 0.
2357 LATTEST(current_view_);
2359 d->views_[id] = view;
2363 setActiveWindow(view);
2366 if (!geometry_arg.isEmpty()) {
2367 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2371 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2372 re.indexIn(geometry_arg);
2373 w = re.cap(1).toInt();
2374 h = re.cap(2).toInt();
2375 x = re.cap(3).toInt();
2376 y = re.cap(4).toInt();
2377 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2378 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2379 // Set initial geometry such that we can get the frame size.
2380 view->setGeometry(x, y, w, h);
2381 int framewidth = view->geometry().x() - view->x();
2382 int titleheight = view->geometry().y() - view->y();
2383 // Negative displacements must be interpreted as distances
2384 // from the right or bottom screen borders.
2385 if (sx == '-' || sy == '-') {
2386 QRect rec = QApplication::desktop()->screenGeometry();
2388 x += rec.width() - w - framewidth;
2390 y += rec.height() - h - titleheight;
2391 view->setGeometry(x, y, w, h);
2393 // Make sure that the left and top frame borders are visible.
2394 if (view->x() < 0 || view->y() < 0) {
2399 view->setGeometry(x, y, w, h);
2407 bool GuiApplication::unhide(Buffer * buf)
2411 currentView()->setBuffer(buf, false);
2416 Clipboard & GuiApplication::clipboard()
2418 return d->clipboard_;
2422 Selection & GuiApplication::selection()
2424 return d->selection_;
2428 FontLoader & GuiApplication::fontLoader()
2430 return d->font_loader_;
2434 Toolbars const & GuiApplication::toolbars() const
2436 return d->toolbars_;
2440 Toolbars & GuiApplication::toolbars()
2442 return d->toolbars_;
2446 Menus const & GuiApplication::menus() const
2452 Menus & GuiApplication::menus()
2458 QList<int> GuiApplication::viewIds() const
2460 return d->views_.keys();
2464 ColorCache & GuiApplication::colorCache()
2466 return d->color_cache_;
2470 int GuiApplication::exec()
2472 // asynchronously handle batch commands. This event will be in
2473 // the event queue in front of other asynchronous events. Hence,
2474 // we can assume in the latter that the gui is setup already.
2475 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2477 return QApplication::exec();
2481 void GuiApplication::exit(int status)
2483 QApplication::exit(status);
2487 void GuiApplication::setGuiLanguage()
2491 // install translation file for Qt built-in dialogs
2492 QString const language_name = QString("qt_") + theLocale.name();
2493 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2494 // Short-named translator can be loaded from a long name, but not the
2495 // opposite. Therefore, long name should be used without truncation.
2496 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2497 if (!d->qt_trans_.load(language_name,
2498 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2499 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2502 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2506 switch (theLocale.language()) {
2507 case QLocale::Arabic :
2508 case QLocale::Hebrew :
2509 case QLocale::Persian :
2510 case QLocale::Urdu :
2511 setLayoutDirection(Qt::RightToLeft);
2514 setLayoutDirection(Qt::LeftToRight);
2519 void GuiApplication::execBatchCommands()
2524 if (!readUIFile(toqstr(lyxrc.ui_file)))
2525 // Gives some error box here.
2529 #if QT_VERSION > 0x040600
2530 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2532 #if QT_VERSION > 0x050100
2533 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2535 // Create the global default menubar which is shown for the dialogs
2536 // and if no GuiView is visible.
2537 // This must be done after the session was recovered to know the "last files".
2538 d->global_menubar_ = new QMenuBar(0);
2539 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2542 lyx::execBatchCommands();
2546 QAbstractItemModel * GuiApplication::languageModel()
2548 if (d->language_model_)
2549 return d->language_model_;
2551 QStandardItemModel * lang_model = new QStandardItemModel(this);
2552 lang_model->insertColumns(0, 3);
2553 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2554 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2555 Languages::const_iterator it = lyx::languages.begin();
2556 Languages::const_iterator end = lyx::languages.end();
2557 for (; it != end; ++it) {
2558 int current_row = lang_model->rowCount();
2559 lang_model->insertRows(current_row, 1);
2560 QModelIndex pl_item = lang_model->index(current_row, 0);
2561 QModelIndex sp_item = lang_model->index(current_row, 1);
2562 QModelIndex th_item = lang_model->index(current_row, 2);
2563 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2564 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2565 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2566 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2567 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2568 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2569 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2570 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2571 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2572 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2574 d->language_model_ = new QSortFilterProxyModel(this);
2575 d->language_model_->setSourceModel(lang_model);
2576 d->language_model_->setSortLocaleAware(true);
2577 return d->language_model_;
2581 void GuiApplication::restoreGuiSession()
2583 if (!lyxrc.load_session)
2586 Session & session = theSession();
2587 LastOpenedSection::LastOpened const & lastopened =
2588 session.lastOpened().getfiles();
2590 validateCurrentView();
2592 FileName active_file;
2593 // do not add to the lastfile list since these files are restored from
2594 // last session, and should be already there (regular files), or should
2595 // not be added at all (help files).
2596 for (size_t i = 0; i < lastopened.size(); ++i) {
2597 FileName const & file_name = lastopened[i].file_name;
2598 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2599 && current_view_->documentBufferView() != 0)) {
2600 boost::crc_32_type crc;
2601 string const & fname = file_name.absFileName();
2602 crc = for_each(fname.begin(), fname.end(), crc);
2603 createView(crc.checksum());
2605 current_view_->loadDocument(file_name, false);
2607 if (lastopened[i].active)
2608 active_file = file_name;
2611 // Restore last active buffer
2612 Buffer * buffer = theBufferList().getBuffer(active_file);
2613 if (buffer && current_view_)
2614 current_view_->setBuffer(buffer);
2616 // clear this list to save a few bytes of RAM
2617 session.lastOpened().clear();
2621 QString const GuiApplication::romanFontName()
2624 font.setStyleHint(QFont::Serif);
2625 font.setFamily("serif");
2627 return QFontInfo(font).family();
2631 QString const GuiApplication::sansFontName()
2634 font.setStyleHint(QFont::SansSerif);
2635 font.setFamily("sans");
2637 return QFontInfo(font).family();
2641 QString const GuiApplication::typewriterFontName()
2643 return QFontInfo(typewriterSystemFont()).family();
2648 // We cannot use QFont::fixedPitch() because it doesn't
2649 // return the fact but only if it is requested.
2650 static bool isFixedPitch(const QFont & font) {
2651 const QFontInfo fi(font);
2652 return fi.fixedPitch();
2657 QFont const GuiApplication::typewriterSystemFont()
2659 #if QT_VERSION >= 0x050200
2660 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2662 QFont font("monospace");
2664 if (!isFixedPitch(font)) {
2665 // try to enforce a real monospaced font
2666 font.setStyleHint(QFont::Monospace);
2667 if (!isFixedPitch(font)) {
2668 font.setStyleHint(QFont::TypeWriter);
2669 if (!isFixedPitch(font)) font.setFamily("courier");
2673 // On a Mac the result is too small and it's not practical to
2674 // rely on Qtconfig utility to change the system settings of Qt.
2675 font.setPointSize(12);
2681 void GuiApplication::handleRegularEvents()
2683 ForkedCallsController::handleCompletedProcesses();
2687 bool GuiApplication::event(QEvent * e)
2690 case QEvent::FileOpen: {
2691 // Open a file; this happens only on Mac OS X for now.
2693 // We do this asynchronously because on startup the batch
2694 // commands are not executed here yet and the gui is not ready
2696 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2697 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2698 processFuncRequestAsync(fr);
2703 return QApplication::event(e);
2708 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2711 return QApplication::notify(receiver, event);
2713 catch (ExceptionMessage const & e) {
2715 case ErrorException:
2717 setQuitOnLastWindowClosed(false);
2719 Alert::error(e.title_, e.details_);
2721 // Properly crash in debug mode in order to get a useful backtrace.
2724 // In release mode, try to exit gracefully.
2726 // FIXME: GCC 7 thinks we can fall through here. Can we?
2728 case BufferException: {
2729 if (!current_view_ || !current_view_->documentBufferView())
2731 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2732 docstring details = e.details_ + '\n';
2733 details += buf->emergencyWrite();
2734 theBufferList().release(buf);
2735 details += "\n" + _("The current document was closed.");
2736 Alert::error(e.title_, details);
2739 case WarningException:
2740 Alert::warning(e.title_, e.details_);
2744 catch (exception const & e) {
2745 docstring s = _("LyX has caught an exception, it will now "
2746 "attempt to save all unsaved documents and exit."
2748 s += from_ascii(e.what());
2749 Alert::error(_("Software exception Detected"), s);
2753 docstring s = _("LyX has caught some really weird exception, it will "
2754 "now attempt to save all unsaved documents and exit.");
2755 Alert::error(_("Software exception Detected"), s);
2763 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2765 QColor const & qcol = d->color_cache_.get(col);
2766 if (!qcol.isValid()) {
2772 rgbcol.r = qcol.red();
2773 rgbcol.g = qcol.green();
2774 rgbcol.b = qcol.blue();
2779 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2781 QColor const qcol(lcolor.getX11Name(col).c_str());
2782 if (!qcol.isValid()) {
2788 rgbcol.r = qcol.red();
2789 rgbcol.g = qcol.green();
2790 rgbcol.b = qcol.blue();
2795 string const GuiApplication::hexName(ColorCode col)
2797 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2801 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2803 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2804 d->socket_notifiers_[fd] = sn;
2805 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2809 void GuiApplication::socketDataReceived(int fd)
2811 d->socket_notifiers_[fd]->func_();
2815 void GuiApplication::unregisterSocketCallback(int fd)
2817 d->socket_notifiers_.take(fd)->setEnabled(false);
2821 void GuiApplication::commitData(QSessionManager & sm)
2823 /** The implementation is required to avoid an application exit
2824 ** when session state save is triggered by session manager.
2825 ** The default implementation sends a close event to all
2826 ** visible top level widgets when session managment allows
2828 ** We are changing that to check the state of each buffer in all
2829 ** views and ask the users what to do if buffers are dirty.
2830 ** Furthermore, we save the session state.
2831 ** We do NOT close the views here since the user still can cancel
2832 ** the logout process (see #9277); also, this would hide LyX from
2833 ** an OSes own session handling (application restoration).
2835 #ifdef QT_NO_SESSIONMANAGER
2837 #warning Qt is compiled without session manager
2839 #pragma message("warning: Qt is compiled without session manager")
2843 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2851 void GuiApplication::unregisterView(GuiView * gv)
2853 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2854 d->views_.remove(gv->id());
2855 if (current_view_ == gv)
2861 bool GuiApplication::closeAllViews()
2863 if (d->views_.empty())
2866 // When a view/window was closed before without quitting LyX, there
2867 // are already entries in the lastOpened list.
2868 theSession().lastOpened().clear();
2870 QList<GuiView *> const views = d->views_.values();
2871 for (GuiView * view : views) {
2872 if (!view->closeScheduled())
2881 bool GuiApplication::prepareAllViewsForLogout()
2883 if (d->views_.empty())
2886 QList<GuiView *> const views = d->views_.values();
2887 for (GuiView * view : views) {
2888 if (!view->prepareAllBuffersForLogout())
2896 GuiView & GuiApplication::view(int id) const
2898 LAPPERR(d->views_.contains(id));
2899 return *d->views_.value(id);
2903 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2905 QList<GuiView *> const views = d->views_.values();
2906 for (GuiView * view : views)
2907 view->hideDialog(name, inset);
2911 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2913 Buffer const * buffer_ = 0;
2914 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2915 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2916 if (Buffer const * ptr = (*it)->updateInset(inset))
2923 bool GuiApplication::searchMenu(FuncRequest const & func,
2924 docstring_list & names) const
2926 return d->menus_.searchMenu(func, names);
2930 // Ensure that a file is read only once (prevents include loops)
2931 static QStringList uifiles;
2932 // store which ui files define Toolbars
2933 static QStringList toolbar_uifiles;
2936 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2947 LexerKeyword uitags[] = {
2948 { "format", ui_format },
2949 { "include", ui_include },
2950 { "menuset", ui_menuset },
2951 { "toolbars", ui_toolbars },
2952 { "toolbarset", ui_toolbarset }
2956 lex.setFile(ui_path);
2958 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2962 if (lyxerr.debugging(Debug::PARSER))
2963 lex.printTable(lyxerr);
2966 // format before introduction of format tag
2967 unsigned int format = 0;
2968 while (lex.isOK()) {
2969 int const status = lex.lex();
2971 // we have to do this check here, outside the switch,
2972 // because otherwise we would start reading include files,
2973 // e.g., if the first tag we hit was an include tag.
2974 if (status == ui_format)
2976 format = lex.getInteger();
2980 // this will trigger unless the first tag we hit is a format
2981 // tag, with the right format.
2982 if (format != LFUN_FORMAT)
2983 return FormatMismatch;
2986 case Lexer::LEX_FEOF:
2991 QString const file = toqstr(lex.getString());
2992 bool const success = readUIFile(file, true);
2994 LYXERR0("Failed to read included file: " << fromqstr(file));
3001 d->menus_.read(lex);
3005 d->toolbars_.readToolbars(lex);
3009 d->toolbars_.readToolbarSettings(lex);
3010 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3014 if (!rtrim(lex.getString()).empty())
3015 lex.printError("LyX::ReadUIFile: "
3016 "Unknown menu tag: `$$Token'");
3018 LYXERR0("Error with status: " << status);
3024 return (error ? ReadError : ReadOK);
3028 bool GuiApplication::readUIFile(QString const & name, bool include)
3030 LYXERR(Debug::INIT, "About to read " << name << "...");
3034 ui_path = libFileSearch("ui", name, "inc");
3035 if (ui_path.empty())
3036 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3038 ui_path = libFileSearch("ui", name, "ui");
3041 if (ui_path.empty()) {
3042 static const QString defaultUIFile = "default";
3043 LYXERR(Debug::INIT, "Could not find " << name);
3045 Alert::warning(_("Could not find UI definition file"),
3046 bformat(_("Error while reading the included file\n%1$s\n"
3047 "Please check your installation."), qstring_to_ucs4(name)));
3050 if (name == defaultUIFile) {
3051 LYXERR(Debug::INIT, "Could not find default UI file!!");
3052 Alert::warning(_("Could not find default UI file"),
3053 _("LyX could not find the default UI file!\n"
3054 "Please check your installation."));
3057 Alert::warning(_("Could not find UI definition file"),
3058 bformat(_("Error while reading the configuration file\n%1$s\n"
3059 "Falling back to default.\n"
3060 "Please look under Tools>Preferences>User Interface and\n"
3061 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3062 return readUIFile(defaultUIFile, false);
3065 QString const uifile = toqstr(ui_path.absFileName());
3066 if (uifiles.contains(uifile)) {
3068 // We are reading again the top uifile so reset the safeguard:
3071 d->toolbars_.reset();
3073 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3074 << "Is this an include loop?");
3078 uifiles.push_back(uifile);
3080 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3082 ReturnValues retval = readUIFile(ui_path);
3084 if (retval == FormatMismatch) {
3085 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3086 TempFile tmp("convertXXXXXX.ui");
3087 FileName const tempfile = tmp.name();
3088 bool const success = prefs2prefs(ui_path, tempfile, true);
3090 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3091 " to format " << LFUN_FORMAT << ".");
3093 retval = readUIFile(tempfile);
3097 if (retval != ReadOK) {
3098 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3106 settings.beginGroup("ui_files");
3107 bool touched = false;
3108 for (int i = 0; i != uifiles.size(); ++i) {
3109 QFileInfo fi(uifiles[i]);
3110 QDateTime const date_value = fi.lastModified();
3111 QString const name_key = QString::number(i);
3112 // if an ui file which defines Toolbars has changed,
3113 // we have to reset the settings
3114 if (toolbar_uifiles.contains(uifiles[i])
3115 && (!settings.contains(name_key)
3116 || settings.value(name_key).toString() != uifiles[i]
3117 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3119 settings.setValue(name_key, uifiles[i]);
3120 settings.setValue(name_key + "/date", date_value);
3123 settings.endGroup();
3125 settings.remove("views");
3131 void GuiApplication::onLastWindowClosed()
3133 if (d->global_menubar_)
3134 d->global_menubar_->grabKeyboard();
3138 void GuiApplication::startLongOperation() {
3139 d->key_checker_.start();
3143 bool GuiApplication::longOperationCancelled() {
3144 return d->key_checker_.pressed();
3148 void GuiApplication::stopLongOperation() {
3149 d->key_checker_.stop();
3153 bool GuiApplication::longOperationStarted() {
3154 return d->key_checker_.started();
3158 ////////////////////////////////////////////////////////////////////////
3160 // X11 specific stuff goes here...
3163 bool GuiApplication::x11EventFilter(XEvent * xev)
3168 switch (xev->type) {
3169 case SelectionRequest: {
3170 if (xev->xselectionrequest.selection != XA_PRIMARY)
3172 LYXERR(Debug::SELECTION, "X requested selection.");
3173 BufferView * bv = current_view_->currentBufferView();
3175 docstring const sel = bv->requestSelection();
3177 d->selection_.put(sel);
3178 // Refresh the selection request timestamp.
3179 // We have to do this by ourselves as Qt seems
3180 // not doing that, maybe because of our
3181 // "persistent selection" implementation
3182 // (see comments in GuiSelection.cpp).
3183 XSelectionEvent nev;
3184 nev.type = SelectionNotify;
3185 nev.display = xev->xselectionrequest.display;
3186 nev.requestor = xev->xselectionrequest.requestor;
3187 nev.selection = xev->xselectionrequest.selection;
3188 nev.target = xev->xselectionrequest.target;
3189 nev.property = 0L; // None
3190 nev.time = CurrentTime;
3191 XSendEvent(QX11Info::display(),
3192 nev.requestor, False, 0,
3193 reinterpret_cast<XEvent *>(&nev));
3199 case SelectionClear: {
3200 if (xev->xselectionclear.selection != XA_PRIMARY)
3202 LYXERR(Debug::SELECTION, "Lost selection.");
3203 BufferView * bv = current_view_->currentBufferView();
3205 bv->clearSelection();
3211 #elif defined(QPA_XCB)
3212 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3213 void * message, long *)
3215 if (!current_view_ || eventType != "xcb_generic_event_t")
3218 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3220 switch (ev->response_type) {
3221 case XCB_SELECTION_REQUEST: {
3222 xcb_selection_request_event_t * srev =
3223 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3224 if (srev->selection != XCB_ATOM_PRIMARY)
3226 LYXERR(Debug::SELECTION, "X requested selection.");
3227 BufferView * bv = current_view_->currentBufferView();
3229 docstring const sel = bv->requestSelection();
3231 d->selection_.put(sel);
3232 #ifdef HAVE_QT5_X11_EXTRAS
3233 // Refresh the selection request timestamp.
3234 // We have to do this by ourselves as Qt seems
3235 // not doing that, maybe because of our
3236 // "persistent selection" implementation
3237 // (see comments in GuiSelection.cpp).
3238 xcb_selection_notify_event_t nev;
3239 nev.response_type = XCB_SELECTION_NOTIFY;
3240 nev.requestor = srev->requestor;
3241 nev.selection = srev->selection;
3242 nev.target = srev->target;
3243 nev.property = XCB_NONE;
3244 nev.time = XCB_CURRENT_TIME;
3245 xcb_connection_t * con = QX11Info::connection();
3246 xcb_send_event(con, 0, srev->requestor,
3247 XCB_EVENT_MASK_NO_EVENT,
3248 reinterpret_cast<char const *>(&nev));
3256 case XCB_SELECTION_CLEAR: {
3257 xcb_selection_clear_event_t * scev =
3258 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3259 if (scev->selection != XCB_ATOM_PRIMARY)
3261 LYXERR(Debug::SELECTION, "Lost selection.");
3262 BufferView * bv = current_view_->currentBufferView();
3264 bv->clearSelection();
3272 } // namespace frontend
3275 void hideDialogs(std::string const & name, Inset * inset)
3278 frontend::guiApp->hideDialogs(name, inset);
3282 ////////////////////////////////////////////////////////////////////
3286 ////////////////////////////////////////////////////////////////////
3288 frontend::FontLoader & theFontLoader()
3290 LAPPERR(frontend::guiApp);
3291 return frontend::guiApp->fontLoader();
3295 frontend::FontMetrics const & theFontMetrics(Font const & f)
3297 return theFontMetrics(f.fontInfo());
3301 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3303 LAPPERR(frontend::guiApp);
3304 return frontend::guiApp->fontLoader().metrics(f);
3308 ////////////////////////////////////////////////////////////////////
3312 ////////////////////////////////////////////////////////////////////
3314 frontend::Clipboard & theClipboard()
3316 LAPPERR(frontend::guiApp);
3317 return frontend::guiApp->clipboard();
3321 frontend::Selection & theSelection()
3323 LAPPERR(frontend::guiApp);
3324 return frontend::guiApp->selection();
3330 #include "moc_GuiApplication.cpp"