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>
126 #elif defined(QPA_XCB)
128 #ifdef HAVE_QT5_X11_EXTRAS
129 #include <QtX11Extras/QX11Info>
133 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
134 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
135 #if (QT_VERSION < 0x050000)
136 #include <QWindowsMime>
137 #define QWINDOWSMIME QWindowsMime
140 #define QWINDOWSMIME QWinMime
150 #include <QMacPasteboardMime>
153 #include <boost/crc.hpp>
160 using namespace lyx::support;
163 static void initializeResources()
165 static bool initialized = false;
167 Q_INIT_RESOURCE(Resources);
175 frontend::Application * createApplication(int & argc, char * argv[])
177 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
178 // prune -geometry argument(s) by shifting
179 // the following ones 2 places down.
180 for (int i = 0 ; i < argc ; ++i) {
181 if (strcmp(argv[i], "-geometry") == 0) {
182 int const remove = (i+1) < argc ? 2 : 1;
184 for (int j = i; j < argc; ++j)
185 argv[j] = argv[j + remove];
191 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
192 // On Windows, allow bringing the LyX window to top
193 AllowSetForegroundWindow(ASFW_ANY);
196 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
197 // I'd rather do that in the constructor, but I do not think that
198 // the palette is accessible there.
199 guiApp->colorCache().setPalette(guiApp->palette());
208 if (lyxrc.gui_language == "auto") {
209 theLocale = QLocale::system();
210 code = fromqstr(theLocale.name());
212 Language const * l = languages.getLanguage(lyxrc.gui_language);
213 code = l ? l->code() : "C";
214 theLocale = QLocale(toqstr(code));
216 // Qt tries to outsmart us and transforms en_US to C.
217 Messages::guiLanguage((code == "C") ? "en_US" : code);
218 QLocale::setDefault(theLocale);
219 setlocale(LC_NUMERIC, "C");
226 /// Return the list of loadable formats.
227 vector<string> loadableImageFormats()
231 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
233 LYXERR(Debug::GRAPHICS,
234 "\nThe image loader can load the following directly:\n");
236 if (qt_formats.empty())
237 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
239 bool jpeg_found = false;
240 bool jpg_found = false;
241 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
243 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
245 string ext = ascii_lowercase((const char *) *it);
253 else if (ext == "jpg") {
258 else if (lyxrc.use_converter_cache &&
259 (ext == "svg" || ext == "svgz") &&
260 theConverters().isReachable("svg", "png"))
261 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
262 // the SVG as in the output. However we require that the converter
263 // cache is enabled since this is expensive. We also require that
264 // an explicit svg->png converter is defined, since the default
265 // converter could produce bad quality as well. This assumes that
266 // png can always be loaded.
275 ////////////////////////////////////////////////////////////////////////
277 // Icon loading support code
279 ////////////////////////////////////////////////////////////////////////
289 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
291 return lhs.key < rhs.key;
297 CompareKey(QString const & name) : name_(name) {}
298 bool operator()(ImgMap const & other) const { return other.key == name_; }
304 // this must be sorted alphabetically
305 // Upper case comes before lower case
306 // Please don't change the formatting, this list is parsed by
307 // development/tools/generate_symbols_images.py.
308 ImgMap sorted_img_map[] = {
309 { "Arrownot", "arrownot2"},
310 { "Arrowvert", "arrowvert2"},
311 { "Bowtie", "bowtie2" },
313 { "Bumpeq", "bumpeq2" },
314 { "CIRCLE", "circle3" },
316 { "CheckedBox", "checkedbox2" },
317 { "Circle", "circle2" },
318 { "Colonapprox", "colonapprox2" },
319 { "Coloneq", "coloneq2" },
320 { "Coloneqq", "coloneqq2" },
321 { "Colonsim", "colonsim2" },
323 { "DOWNarrow", "downarrow3" },
324 { "Delta", "delta2" },
325 { "Diamond", "diamond2" },
326 { "Doteq", "doteq2" },
327 { "Downarrow", "downarrow2" },
328 { "Eqcolon", "eqcolon2" },
329 { "Eqqcolon", "eqqcolon2" },
330 { "Gamma", "gamma2" },
332 { "LEFTCIRCLE", "leftcircle3" },
333 { "LEFTarrow", "leftarrow3" },
334 { "LEFTcircle", "leftcircle4" },
336 { "Lambda", "lambda2" },
338 { "Leftarrow", "leftarrow2" },
339 { "Leftcircle", "leftcircle2" },
340 { "Leftrightarrow", "leftrightarrow2" },
341 { "Longarrownot", "longarrownot2"},
342 { "Longleftarrow", "longleftarrow2" },
343 { "Longleftrightarrow", "longleftrightarrow2" },
344 { "Longmapsfrom", "longmapsfrom2"},
345 { "Longmapsto", "longmapsto2"},
346 { "Longrightarrow", "longrightarrow2" },
347 { "Mapsfrom", "mapsfrom2"},
348 { "Mapsfromchar", "mapsfromchar2"},
349 { "Mapsto", "mapsto2"},
350 { "Mapstochar", "mapstochar2"},
351 { "Omega", "omega2" },
356 { "RIGHTCIRCLE", "rightcircle3" },
357 { "RIGHTarrow", "rightarrow3" },
358 { "RIGHTcircle", "rightcircle4" },
360 { "Rightarrow", "rightarrow2" },
361 { "Rightcircle", "rightcircle2" },
362 { "Sigma", "sigma2" },
363 { "Square", "square2" },
364 { "Subset", "subset2" },
365 { "Supset", "supset2" },
366 { "Theta", "theta2" },
367 { "Thorn", "thorn2" },
368 { "UParrow", "uparrow3" },
369 { "Uparrow", "uparrow2" },
370 { "Updownarrow", "updownarrow2" },
371 { "Upsilon", "upsilon2" },
372 { "Vdash", "vdash3" },
377 { "lVert", "vert2" },
379 { "nLeftarrow", "nleftarrow2" },
380 { "nLeftrightarrow", "nleftrightarrow2" },
381 { "nRightarrow", "nrightarrow2" },
382 { "nVDash", "nvdash3" },
383 { "nVdash", "nvdash4" },
384 { "nvDash", "nvdash2" },
385 { "rVert", "vert2" },
387 { "textrm \\AA", "textrm_AA"},
388 { "textrm \\O", "textrm_O"},
389 { "vDash", "vdash2" },
390 { "varDelta", "vardelta2" },
391 { "varGamma", "vargamma2" },
392 { "varLambda", "varlambda2" },
393 { "varOmega", "varomega2" },
394 { "varPhi", "varphi2" },
395 { "varPi", "varpi2" },
396 { "varPsi", "varpsi2" },
397 { "varSigma", "varsigma2" },
398 { "varTheta", "vartheta2" },
399 { "varUpsilon", "varupsilon2" },
400 { "varXi", "varxi2" }
404 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
406 // This list specifies which system's theme icon is related to which lyx
407 // command. It was based on:
408 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
409 // this must be sorted alphabetically
410 // Upper case comes before lower case
411 ImgMap sorted_theme_icon_map[] = {
412 { "bookmark-goto 0", "go-jump" },
413 { "buffer-new", "document-new" },
414 { "buffer-write", "document-save" },
415 { "buffer-write-as", "document-save-as" },
416 { "buffer-zoom-in", "zoom-in" },
417 { "buffer-zoom-out", "zoom-out" },
418 { "copy", "edit-copy" },
419 { "cut", "edit-cut" },
420 { "depth-decrement", "format-indent-less" },
421 { "depth-increment", "format-indent-more" },
422 { "dialog-show spellchecker", "tools-check-spelling" },
423 { "dialog-show-new-inset graphics", "insert-image" },
424 { "dialog-toggle findreplaceadv", "edit-find-replace" },
425 { "file-open", "document-open" },
426 { "font-bold", "format-text-bold" },
427 { "font-ital", "format-text-italic" },
428 { "font-strikeout", "format-text-strikethrough" },
429 { "font-underline", "format-text-underline" },
430 { "lyx-quit", "application-exit" },
431 { "paste", "edit-paste" },
432 { "redo", "edit-redo" },
433 { "undo", "edit-undo" },
434 { "window-close", "window-close" },
435 { "window-new", "window-new" }
438 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
441 QString findImg(QString const & name)
443 ImgMap const * const begin = sorted_img_map;
444 ImgMap const * const end = begin + nr_sorted_img_map;
445 LATTEST(sorted(begin, end));
447 ImgMap const * const it = find_if(begin, end, CompareKey(name));
451 img_name = it->value;
454 img_name.replace('_', "underscore");
455 img_name.replace(' ', '_');
457 // This way we can have "math-delim { }" on the toolbar.
458 img_name.replace('(', "lparen");
459 img_name.replace(')', "rparen");
460 img_name.replace('[', "lbracket");
461 img_name.replace(']', "rbracket");
462 img_name.replace('{', "lbrace");
463 img_name.replace('}', "rbrace");
464 img_name.replace('|', "bars");
465 img_name.replace(',', "thinspace");
466 img_name.replace(':', "mediumspace");
467 img_name.replace(';', "thickspace");
468 img_name.replace('!', "negthinspace");
471 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
472 << "Looking for math icon called \"" << img_name << '"');
479 QString themeIconName(QString const & action)
481 ImgMap const * const begin = sorted_theme_icon_map;
482 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
483 LASSERT(sorted(begin, end), /**/);
485 ImgMap const * const it = find_if(begin, end, CompareKey(action));
493 QString iconName(FuncRequest const & f, bool unknown)
495 initializeResources();
499 switch (f.action()) {
500 case LFUN_MATH_INSERT:
501 if (!f.argument().empty()) {
503 name1 = findImg(toqstr(f.argument()).mid(1));
506 case LFUN_MATH_DELIM:
507 case LFUN_MATH_BIGDELIM:
509 name1 = findImg(toqstr(f.argument()));
513 name1 = toqstr(f.argument());
515 case LFUN_COMMAND_ALTERNATIVES: {
516 // use the first of the alternative commands
518 docstring dummy = split(f.argument(), firstcom, ';');
519 name1 = toqstr(firstcom);
520 name1.replace(' ', '_');
524 name2 = toqstr(lyxaction.getActionName(f.action()));
527 if (!f.argument().empty()) {
528 name1 = name2 + ' ' + toqstr(f.argument());
529 name1.replace(' ', '_');
530 name1.replace('\\', "backslash");
534 QStringList imagedirs;
535 imagedirs << "images/" << "images/ipa/";
536 search_mode mode = theGuiApp()->imageSearchMode();
537 for (int i = 0; i < imagedirs.size(); ++i) {
538 QString imagedir = imagedirs.at(i) + path;
539 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
541 return toqstr(fname.absFileName());
543 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
545 return toqstr(fname.absFileName());
548 path = ":/images/" + path;
551 LYXERR0("Directory " << path << " not found in resource!");
554 if (res.exists(name1 + ".svgz"))
555 return path + name1 + ".svgz";
556 else if (res.exists(name1 + ".png"))
557 return path + name1 + ".png";
559 if (res.exists(name2 + ".svgz"))
560 return path + name2 + ".svgz";
561 else if (res.exists(name2 + ".png"))
562 return path + name2 + ".png";
564 LYXERR(Debug::GUI, "Cannot find icon with filename "
565 << "\"" << name1 << ".{svgz,png}\""
567 << "\"" << name2 << ".{svgz,png}\""
569 << lyxaction.getActionName(f.action())
570 << '(' << to_utf8(f.argument()) << ")\"");
573 QString imagedir = "images/";
574 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
576 return toqstr(fname.absFileName());
577 return QString(":/images/unknown.svgz");
584 bool getPixmap(QPixmap & pixmap, QString const & path)
586 return pixmap.load(path);
590 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
592 QString imagedir = path;
593 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
594 QString fpath = toqstr(fname.absFileName());
595 QPixmap pixmap = QPixmap();
597 if (getPixmap(pixmap, fpath)) {
601 QStringList exts = ext.split(",");
602 fpath = ":/" + path + name + ".";
603 for (int i = 0; i < exts.size(); ++i) {
604 if (getPixmap(pixmap, fpath + exts.at(i))) {
609 bool const list = ext.contains(",");
610 LYXERR0("Cannot load pixmap \""
611 << path << name << "." << (list ? "{" : "") << ext
612 << (list ? "}" : "") << "\", please verify resource system!");
618 QIcon getIcon(FuncRequest const & f, bool unknown)
620 #if (QT_VERSION >= 0x040600)
621 if (lyxrc.use_system_theme_icons) {
622 // use the icons from system theme that are available
623 QString action = toqstr(lyxaction.getActionName(f.action()));
624 if (!f.argument().empty())
625 action += " " + toqstr(f.argument());
626 QString const theme_icon = themeIconName(action);
627 if (QIcon::hasThemeIcon(theme_icon)) {
628 QIcon const thmicn = QIcon::fromTheme(theme_icon);
629 if (!thmicn.isNull())
635 QString icon = iconName(f, unknown);
639 //LYXERR(Debug::GUI, "Found icon: " << icon);
640 QPixmap pixmap = QPixmap();
641 if (!getPixmap(pixmap,icon)) {
642 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
646 return QIcon(pixmap);
650 ////////////////////////////////////////////////////////////////////////
652 // LyX server support code.
654 ////////////////////////////////////////////////////////////////////////
656 class SocketNotifier : public QSocketNotifier
659 /// connect a connection notification from the LyXServerSocket
660 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
661 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
665 /// The callback function
666 Application::SocketCallback func_;
670 ////////////////////////////////////////////////////////////////////////
672 // Mac specific stuff goes here...
674 ////////////////////////////////////////////////////////////////////////
676 class MenuTranslator : public QTranslator
679 MenuTranslator(QObject * parent)
680 : QTranslator(parent)
683 #if QT_VERSION >= 0x050000
684 virtual QString translate(const char * /* context */,
685 const char *sourceText,
686 const char * /* disambiguation */ = 0, int /* n */ = -1) const
688 QString translate(const char * /*context*/,
689 const char * sourceText,
690 const char * /*comment*/ = 0) const
693 string const s = sourceText;
694 if (s == N_("About %1") || s == N_("Preferences")
695 || s == N_("Reconfigure") || s == N_("Quit %1"))
703 // QMacPasteboardMimeGraphics can only be compiled on Mac.
705 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
708 QMacPasteboardMimeGraphics()
709 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
712 QString convertorName() { return "Graphics"; }
714 QString flavorFor(QString const & mime)
716 LYXERR(Debug::ACTION, "flavorFor " << mime);
717 if (mime == pdfMimeType())
718 return QLatin1String("com.adobe.pdf");
722 QString mimeFor(QString flav)
724 LYXERR(Debug::ACTION, "mimeFor " << flav);
725 if (flav == QLatin1String("com.adobe.pdf"))
726 return pdfMimeType();
730 bool canConvert(QString const & mime, QString flav)
732 return mimeFor(flav) == mime;
735 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
739 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
743 QList<QByteArray> convertFromMime(QString const & /*mime*/,
744 QVariant data, QString /*flav*/)
746 QList<QByteArray> ret;
747 ret.append(data.toByteArray());
753 ///////////////////////////////////////////////////////////////
755 // You can find more platform specific stuff at the end of this file...
757 ///////////////////////////////////////////////////////////////
759 ////////////////////////////////////////////////////////////////////////
760 // Windows specific stuff goes here...
762 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
763 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
764 // QWindowsMimeMetafile can only be compiled on Windows.
766 static FORMATETC cfFromMime(QString const & mimetype)
769 if (mimetype == emfMimeType()) {
770 formatetc.cfFormat = CF_ENHMETAFILE;
771 formatetc.tymed = TYMED_ENHMF;
772 } else if (mimetype == wmfMimeType()) {
773 formatetc.cfFormat = CF_METAFILEPICT;
774 formatetc.tymed = TYMED_MFPICT;
777 formatetc.dwAspect = DVASPECT_CONTENT;
778 formatetc.lindex = -1;
783 class QWindowsMimeMetafile : public QWINDOWSMIME {
785 QWindowsMimeMetafile() {}
787 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
788 QMimeData const * /*mimedata*/) const
793 bool canConvertToMime(QString const & mimetype,
794 IDataObject * pDataObj) const
796 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
798 FORMATETC formatetc = cfFromMime(mimetype);
799 return pDataObj->QueryGetData(&formatetc) == S_OK;
802 bool convertFromMime(FORMATETC const & /*formatetc*/,
803 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
808 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
809 QVariant::Type /*preferredType*/) const
812 if (!canConvertToMime(mimetype, pDataObj))
815 FORMATETC formatetc = cfFromMime(mimetype);
817 if (pDataObj->GetData(&formatetc, &s) != S_OK)
821 if (s.tymed == TYMED_ENHMF) {
822 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
823 data.resize(dataSize);
824 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
825 (LPBYTE)data.data());
826 } else if (s.tymed == TYMED_MFPICT) {
827 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
828 data.resize(dataSize);
829 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
830 (LPBYTE)data.data());
833 ReleaseStgMedium(&s);
839 QVector<FORMATETC> formatsForMime(QString const & mimetype,
840 QMimeData const * /*mimedata*/) const
842 QVector<FORMATETC> formats;
843 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
844 formats += cfFromMime(mimetype);
848 QString mimeForFormat(FORMATETC const & formatetc) const
850 switch (formatetc.cfFormat) {
852 return emfMimeType();
853 case CF_METAFILEPICT:
854 return wmfMimeType();
864 /// Allows to check whether ESC was pressed during a long operation
865 class KeyChecker : public QObject {
870 KeyChecker() : pressed_(false), started_(false) {}
873 QCoreApplication::instance()->installEventFilter(this);
878 QCoreApplication::instance()->removeEventFilter(this);
882 QCoreApplication::processEvents();
885 bool started() const {
888 bool eventFilter(QObject *obj, QEvent *event) {
889 LYXERR(Debug::ACTION, "Event Type: " << event->type());
890 switch (event->type()) {
894 case QEvent::UpdateRequest:
895 case QEvent::CursorChange:
896 case QEvent::ActionChanged:
897 case QEvent::EnabledChange:
898 case QEvent::SockAct:
901 case QEvent::ToolTipChange:
902 case QEvent::LayoutRequest:
903 case QEvent::MetaCall:
904 return QObject::eventFilter(obj, event);
906 // FIXME Blocking all these events is a bad idea.
907 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
908 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
916 ////////////////////////////////////////////////////////////////////////
917 // GuiApplication::Private definition and implementation.
918 ////////////////////////////////////////////////////////////////////////
920 struct GuiApplication::Private
922 Private(): language_model_(0), meta_fake_bit(NoModifier),
925 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
926 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
927 /// WMF Mime handler for Windows clipboard.
928 wmf_mime_ = new QWindowsMimeMetafile;
931 initKeySequences(&theTopLevelKeymap());
934 void initKeySequences(KeyMap * kb)
936 keyseq = KeySequence(kb, kb);
937 cancel_meta_seq = KeySequence(kb, kb);
941 QSortFilterProxyModel * language_model_;
943 GuiClipboard clipboard_;
945 GuiSelection selection_;
947 FontLoader font_loader_;
949 ColorCache color_cache_;
951 QTranslator qt_trans_;
953 QHash<int, SocketNotifier *> socket_notifiers_;
957 /// The global instance
960 /// this timer is used for any regular events one wants to
961 /// perform. at present it is used to check if forked processes
963 QTimer general_timer_;
965 /// delayed FuncRequests
966 std::queue<FuncRequest> func_request_queue_;
971 KeySequence cancel_meta_seq;
973 KeyModifier meta_fake_bit;
975 /// The result of last dispatch action
976 DispatchResult dispatch_result_;
978 /// Multiple views container.
980 * Warning: This must not be a smart pointer as the destruction of the
981 * object is handled by Qt when the view is closed
982 * \sa Qt::WA_DeleteOnClose attribute.
984 QHash<int, GuiView *> views_;
986 /// Only used on mac.
987 QMenuBar * global_menubar_;
990 /// Linkback mime handler for MacOSX.
991 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
994 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
995 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
996 /// WMF Mime handler for Windows clipboard.
997 QWindowsMimeMetafile * wmf_mime_;
1001 /// Allows to check whether ESC was pressed during a long operation
1002 KeyChecker key_checker_;
1006 GuiApplication * guiApp;
1008 GuiApplication::~GuiApplication()
1011 closeAllLinkBackLinks();
1017 GuiApplication::GuiApplication(int & argc, char ** argv)
1018 : QApplication(argc, argv), current_view_(0),
1019 d(new GuiApplication::Private)
1021 QString app_name = "LyX";
1022 QCoreApplication::setOrganizationName(app_name);
1023 QCoreApplication::setOrganizationDomain("lyx.org");
1024 QCoreApplication::setApplicationName(lyx_package);
1025 #if QT_VERSION >= 0x050000
1026 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1029 qsrand(QDateTime::currentDateTime().toTime_t());
1031 // Install translator for GUI elements.
1032 installTranslator(&d->qt_trans_);
1035 // Enable reception of XCB events.
1036 installNativeEventFilter(this);
1039 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1040 // lyxrc setting for this in order to let the application stay resident.
1041 // But then we need some kind of dock icon, at least on Windows.
1043 if (lyxrc.quit_on_last_window_closed)
1044 setQuitOnLastWindowClosed(false);
1047 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1048 // seems to be the default case for applications like LyX.
1049 setQuitOnLastWindowClosed(false);
1050 // This allows to translate the strings that appear in the LyX menu.
1051 /// A translator suitable for the entries in the LyX menu.
1052 /// Only needed with Qt/Mac.
1053 installTranslator(new MenuTranslator(this));
1058 #if defined(Q_WS_X11) || defined(QPA_XCB)
1059 // doubleClickInterval() is 400 ms on X11 which is just too long.
1060 // On Windows and Mac OS X, the operating system's value is used.
1061 // On Microsoft Windows, calling this function sets the double
1062 // click interval for all applications. So we don't!
1063 QApplication::setDoubleClickInterval(300);
1066 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1068 // needs to be done before reading lyxrc
1070 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1074 // Set the cache to 5120 kilobytes which corresponds to screen size of
1075 // 1280 by 1024 pixels with a color depth of 32 bits.
1076 QPixmapCache::setCacheLimit(5120);
1078 // Initialize RC Fonts
1079 if (lyxrc.roman_font_name.empty())
1080 lyxrc.roman_font_name = fromqstr(romanFontName());
1082 if (lyxrc.sans_font_name.empty())
1083 lyxrc.sans_font_name = fromqstr(sansFontName());
1085 if (lyxrc.typewriter_font_name.empty())
1086 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1088 d->general_timer_.setInterval(500);
1089 connect(&d->general_timer_, SIGNAL(timeout()),
1090 this, SLOT(handleRegularEvents()));
1091 d->general_timer_.start();
1093 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1094 // This is clearly not enough in a time where we use threads for
1095 // document preview and/or export. 20 should be OK.
1096 QThreadPool::globalInstance()->setMaxThreadCount(20);
1098 // make sure tooltips are formatted
1099 installEventFilter(new ToolTipFormatter(this));
1103 GuiApplication * theGuiApp()
1105 return dynamic_cast<GuiApplication *>(theApp());
1109 double GuiApplication::pixelRatio() const
1111 #if QT_VERSION >= 0x050000
1112 return qt_scale_factor * devicePixelRatio();
1119 void GuiApplication::clearSession()
1126 docstring Application::iconName(FuncRequest const & f, bool unknown)
1128 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1132 docstring Application::mathIcon(docstring const & c)
1134 return qstring_to_ucs4(findImg(toqstr(c)));
1138 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1142 BufferView * bv = 0;
1143 BufferView * doc_bv = 0;
1145 if (cmd.action() == LFUN_NOACTION) {
1146 status.message(from_utf8(N_("Nothing to do")));
1147 status.setEnabled(false);
1150 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1151 status.setUnknown(true);
1152 status.message(from_utf8(N_("Unknown action")));
1153 status.setEnabled(false);
1156 // Does the GuiApplication know something?
1157 else if (getStatus(cmd, status)) { }
1159 // If we do not have a GuiView, then other functions are disabled
1160 else if (!current_view_)
1161 status.setEnabled(false);
1163 // Does the GuiView know something?
1164 else if (current_view_->getStatus(cmd, status)) { }
1166 // In LyX/Mac, when a dialog is open, the menus of the
1167 // application can still be accessed without giving focus to
1168 // the main window. In this case, we want to disable the menu
1169 // entries that are buffer or view-related.
1170 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1172 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1173 status.setEnabled(false);
1176 // If we do not have a BufferView, then other functions are disabled
1177 else if (!(bv = current_view_->currentBufferView()))
1178 status.setEnabled(false);
1180 // Does the current BufferView know something?
1181 else if (bv->getStatus(cmd, status)) { }
1183 // Does the current Buffer know something?
1184 else if (bv->buffer().getStatus(cmd, status)) { }
1186 // If we do not have a document BufferView, different from the
1187 // current BufferView, then other functions are disabled
1188 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1189 status.setEnabled(false);
1191 // Does the document Buffer know something?
1192 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1195 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1196 status.message(from_utf8(N_("Command not handled")));
1197 status.setEnabled(false);
1200 // the default error message if we disable the command
1201 if (!status.enabled() && status.message().empty())
1202 status.message(from_utf8(N_("Command disabled")));
1208 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1210 // I would really like to avoid having this switch and rather try to
1211 // encode this in the function itself.
1212 // -- And I'd rather let an inset decide which LFUNs it is willing
1213 // to handle (Andre')
1215 switch (cmd.action()) {
1217 // This could be used for the no-GUI version. The GUI version is handled in
1218 // GuiView::getStatus(). See above.
1220 case LFUN_BUFFER_WRITE:
1221 case LFUN_BUFFER_WRITE_AS: {
1222 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1223 enable = b && (b->isUnnamed() || !b->isClean());
1228 case LFUN_BOOKMARK_GOTO: {
1229 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1230 enable = theSession().bookmarks().isValid(num);
1234 case LFUN_BOOKMARK_CLEAR:
1235 enable = theSession().bookmarks().hasValid();
1238 // this one is difficult to get right. As a half-baked
1239 // solution, we consider only the first action of the sequence
1240 case LFUN_COMMAND_SEQUENCE: {
1241 // argument contains ';'-terminated commands
1242 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1243 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1244 func.setOrigin(cmd.origin());
1245 flag = getStatus(func);
1249 // we want to check if at least one of these is enabled
1250 case LFUN_COMMAND_ALTERNATIVES: {
1251 // argument contains ';'-terminated commands
1252 string arg = to_utf8(cmd.argument());
1253 while (!arg.empty()) {
1255 arg = split(arg, first, ';');
1256 FuncRequest func(lyxaction.lookupFunc(first));
1257 func.setOrigin(cmd.origin());
1258 flag = getStatus(func);
1259 // if this one is enabled, the whole thing is
1268 string name = to_utf8(cmd.argument());
1269 if (theTopLevelCmdDef().lock(name, func)) {
1270 func.setOrigin(cmd.origin());
1271 flag = getStatus(func);
1272 theTopLevelCmdDef().release(name);
1274 // catch recursion or unknown command
1275 // definition. all operations until the
1276 // recursion or unknown command definition
1277 // occurs are performed, so set the state to
1284 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1286 case LFUN_PREFERENCES_SAVE:
1287 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1288 case LFUN_DEBUG_LEVEL_SET:
1289 // these are handled in our dispatch()
1292 case LFUN_WINDOW_CLOSE:
1293 enable = d->views_.size() > 0;
1296 case LFUN_BUFFER_NEW:
1297 case LFUN_BUFFER_NEW_TEMPLATE:
1298 case LFUN_FILE_OPEN:
1299 case LFUN_HELP_OPEN:
1300 case LFUN_SCREEN_FONT_UPDATE:
1301 case LFUN_SET_COLOR:
1302 case LFUN_WINDOW_NEW:
1304 case LFUN_LYXRC_APPLY:
1305 case LFUN_COMMAND_PREFIX:
1307 case LFUN_META_PREFIX:
1308 case LFUN_RECONFIGURE:
1309 case LFUN_SERVER_GET_FILENAME:
1310 case LFUN_SERVER_NOTIFY:
1314 case LFUN_BUFFER_FORALL: {
1315 if (theBufferList().empty()) {
1316 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1317 flag.setEnabled(false);
1321 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1322 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1323 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1324 flag.setEnabled(false);
1329 case LFUN_DIALOG_SHOW: {
1330 string const name = cmd.getArg(0);
1331 return name == "aboutlyx"
1333 || name == "texinfo"
1334 || name == "progress"
1335 || name == "compare";
1343 flag.setEnabled(false);
1347 /// make a post-dispatch status message
1348 static docstring makeDispatchMessage(docstring const & msg,
1349 FuncRequest const & cmd)
1351 const bool verbose = (cmd.origin() == FuncRequest::MENU
1352 || cmd.origin() == FuncRequest::TOOLBAR
1353 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1355 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1356 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1360 docstring dispatch_msg = msg;
1361 if (!dispatch_msg.empty())
1362 dispatch_msg += ' ';
1364 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1366 bool argsadded = false;
1368 if (!cmd.argument().empty()) {
1369 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1370 comname += ' ' + cmd.argument();
1374 docstring const shortcuts = theTopLevelKeymap().
1375 printBindings(cmd, KeySequence::ForGui);
1377 if (!shortcuts.empty())
1378 comname += ": " + shortcuts;
1379 else if (!argsadded && !cmd.argument().empty())
1380 comname += ' ' + cmd.argument();
1382 if (!comname.empty()) {
1383 comname = rtrim(comname);
1384 dispatch_msg += '(' + rtrim(comname) + ')';
1386 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1387 return dispatch_msg;
1391 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1393 Buffer * buffer = 0;
1394 if (current_view_ && current_view_->currentBufferView()) {
1395 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1396 buffer = ¤t_view_->currentBufferView()->buffer();
1398 buffer->undo().beginUndoGroup();
1402 // redraw the screen at the end (first of the two drawing steps).
1403 // This is done unless explicitly requested otherwise
1404 dr.screenUpdate(Update::FitCursor);
1406 updateCurrentView(cmd, dr);
1408 // the buffer may have been closed by one action
1409 if (theBufferList().isLoaded(buffer))
1410 buffer->undo().endUndoGroup();
1412 d->dispatch_result_ = dr;
1413 return d->dispatch_result_;
1417 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1422 BufferView * bv = current_view_->currentBufferView();
1424 if (dr.needBufferUpdate()) {
1425 bv->cursor().clearBufferUpdate();
1426 bv->buffer().updateBuffer();
1427 } else if (dr.needChangesUpdate()) {
1428 // updateBuffer() already updates the change-tracking presence flag
1429 bv->buffer().updateChangesPresent();
1431 // BufferView::update() updates the ViewMetricsInfo and
1432 // also initializes the position cache for all insets in
1433 // (at least partially) visible top-level paragraphs.
1434 // We will redraw the screen only if needed.
1435 bv->processUpdateFlags(dr.screenUpdate());
1437 // Do we have a selection?
1438 theSelection().haveSelection(bv->cursor().selection());
1441 current_view_->restartCaret();
1443 if (dr.needMessageUpdate()) {
1444 // Some messages may already be translated, so we cannot use _()
1445 current_view_->message(makeDispatchMessage(
1446 translateIfPossible(dr.message()), cmd));
1451 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1452 bool switchToBuffer)
1454 if (!theSession().bookmarks().isValid(idx))
1456 BookmarksSection::Bookmark const & bm =
1457 theSession().bookmarks().bookmark(idx);
1458 LASSERT(!bm.filename.empty(), return);
1459 string const file = bm.filename.absFileName();
1460 // if the file is not opened, open it.
1461 if (!theBufferList().exists(bm.filename)) {
1463 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1467 // open may fail, so we need to test it again
1468 if (!theBufferList().exists(bm.filename))
1471 // bm can be changed when saving
1472 BookmarksSection::Bookmark tmp = bm;
1474 // Special case idx == 0 used for back-from-back jump navigation
1476 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1478 // if the current buffer is not that one, switch to it.
1479 BufferView * doc_bv = current_view_ ?
1480 current_view_->documentBufferView() : 0;
1481 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1482 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1483 if (switchToBuffer) {
1484 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1487 doc_bv = current_view_->documentBufferView();
1492 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1493 if (!doc_bv || !doc_bv->moveToPosition(
1494 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1497 Cursor & cur = doc_bv->cursor();
1498 if (old && cur != *old)
1499 notifyCursorLeavesOrEnters(*old, cur);
1505 // Cursor jump succeeded!
1506 pit_type new_pit = cur.pit();
1507 pos_type new_pos = cur.pos();
1508 int new_id = cur.paragraph().id();
1510 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1511 // see http://www.lyx.org/trac/ticket/3092
1512 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1513 || bm.top_id != new_id) {
1514 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1515 new_pit, new_pos, new_id);
1519 // This function runs "configure" and then rereads lyx.defaults to
1520 // reconfigure the automatic settings.
1521 void GuiApplication::reconfigure(string const & option)
1523 // emit message signal.
1525 current_view_->message(_("Running configure..."));
1527 // Run configure in user lyx directory
1528 string const lock_file = package().getConfigureLockName();
1529 int fd = fileLock(lock_file.c_str());
1530 int const ret = package().reconfigureUserLyXDir(option);
1531 // emit message signal.
1533 current_view_->message(_("Reloading configuration..."));
1534 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1535 // Re-read packages.lst
1536 LaTeXPackages::getAvailable();
1537 fileUnlock(fd, lock_file.c_str());
1540 Alert::information(_("System reconfiguration failed"),
1541 _("The system reconfiguration has failed.\n"
1542 "Default textclass is used but LyX may\n"
1543 "not be able to work properly.\n"
1544 "Please reconfigure again if needed."));
1546 Alert::information(_("System reconfigured"),
1547 _("The system has been reconfigured.\n"
1548 "You need to restart LyX to make use of any\n"
1549 "updated document class specifications."));
1552 void GuiApplication::validateCurrentView()
1554 if (!d->views_.empty() && !current_view_) {
1555 // currently at least one view exists but no view has the focus.
1556 // choose the last view to make it current.
1557 // a view without any open document is preferred.
1558 GuiView * candidate = 0;
1559 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1560 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1561 for (; it != end; ++it) {
1563 if (!candidate->documentBufferView())
1566 setCurrentView(candidate);
1570 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1572 string const argument = to_utf8(cmd.argument());
1573 FuncCode const action = cmd.action();
1575 LYXERR(Debug::ACTION, "cmd: " << cmd);
1577 // we have not done anything wrong yet.
1580 FuncStatus const flag = getStatus(cmd);
1581 if (!flag.enabled()) {
1582 // We cannot use this function here
1583 LYXERR(Debug::ACTION, "action "
1584 << lyxaction.getActionName(action)
1585 << " [" << action << "] is disabled at this location");
1586 dr.setMessage(flag.message());
1588 dr.dispatched(false);
1589 dr.screenUpdate(Update::None);
1590 dr.clearBufferUpdate();
1594 if (cmd.origin() == FuncRequest::LYXSERVER) {
1595 if (current_view_ && current_view_->currentBufferView())
1596 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1597 // we will also need to redraw the screen at the end
1598 dr.screenUpdate(Update::FitCursor);
1601 // Assumes that the action will be dispatched.
1602 dr.dispatched(true);
1604 switch (cmd.action()) {
1606 case LFUN_WINDOW_NEW:
1607 createView(toqstr(cmd.argument()));
1610 case LFUN_WINDOW_CLOSE:
1611 // update bookmark pit of the current buffer before window close
1612 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1613 gotoBookmark(i+1, false, false);
1614 // clear the last opened list, because
1615 // maybe this will end the session
1616 theSession().lastOpened().clear();
1617 // check for valid current_view_
1618 validateCurrentView();
1620 current_view_->closeScheduled();
1624 // quitting is triggered by the gui code
1625 // (leaving the event loop).
1627 current_view_->message(from_utf8(N_("Exiting.")));
1628 if (closeAllViews())
1632 case LFUN_SCREEN_FONT_UPDATE: {
1633 // handle the screen font changes.
1634 d->font_loader_.update();
1635 // Backup current_view_
1636 GuiView * view = current_view_;
1637 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1638 // to skip the refresh.
1640 theBufferList().changed(false);
1641 // Restore current_view_
1642 current_view_ = view;
1646 case LFUN_BUFFER_NEW:
1647 validateCurrentView();
1649 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1650 createView(QString(), false); // keep hidden
1651 current_view_->newDocument(to_utf8(cmd.argument()), false);
1652 current_view_->show();
1653 setActiveWindow(current_view_);
1655 current_view_->newDocument(to_utf8(cmd.argument()), false);
1659 case LFUN_BUFFER_NEW_TEMPLATE:
1660 validateCurrentView();
1662 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1664 current_view_->newDocument(to_utf8(cmd.argument()), true);
1665 if (!current_view_->documentBufferView())
1666 current_view_->close();
1668 current_view_->newDocument(to_utf8(cmd.argument()), true);
1672 case LFUN_FILE_OPEN: {
1673 // FIXME: normally the code below is not needed, since getStatus makes sure that
1674 // current_view_ is not null.
1675 validateCurrentView();
1676 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1677 string const fname = to_utf8(cmd.argument());
1678 bool const is_open = FileName::isAbsolute(fname)
1679 && theBufferList().getBuffer(FileName(fname));
1681 || (!lyxrc.open_buffers_in_tabs
1682 && current_view_->documentBufferView() != 0
1684 // We want the ui session to be saved per document and not per
1685 // window number. The filename crc is a good enough identifier.
1686 boost::crc_32_type crc;
1687 crc = for_each(fname.begin(), fname.end(), crc);
1688 createView(crc.checksum());
1689 current_view_->openDocument(fname);
1690 if (!current_view_->documentBufferView())
1691 current_view_->close();
1692 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1693 current_view_->raise();
1694 current_view_->activateWindow();
1695 current_view_->showNormal();
1698 current_view_->openDocument(fname);
1699 if (cmd.origin() == FuncRequest::LYXSERVER) {
1700 current_view_->raise();
1701 current_view_->activateWindow();
1702 current_view_->showNormal();
1708 case LFUN_HELP_OPEN: {
1709 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1710 if (current_view_ == 0)
1712 string const arg = to_utf8(cmd.argument());
1714 current_view_->message(_("Missing argument"));
1717 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1719 fname = i18nLibFileSearch("examples", arg, "lyx");
1721 if (fname.empty()) {
1722 lyxerr << "LyX: unable to find documentation file `"
1723 << arg << "'. Bad installation?" << endl;
1726 current_view_->message(bformat(_("Opening help file %1$s..."),
1727 makeDisplayPath(fname.absFileName())));
1728 Buffer * buf = current_view_->loadDocument(fname, false);
1730 buf->setReadonly(!current_view_->develMode());
1734 case LFUN_SET_COLOR: {
1736 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1737 if (lyx_name.empty() || x11_name.empty()) {
1739 current_view_->message(
1740 _("Syntax: set-color <lyx_name> <x11_name>"));
1745 // FIXME: The graphics cache no longer has a changeDisplay method.
1746 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1747 bool const graphicsbg_changed =
1748 lyx_name == graphicsbg && x11_name != graphicsbg;
1749 if (graphicsbg_changed)
1750 graphics::GCache::get().changeDisplay(true);
1753 if (!lcolor.setColor(lyx_name, x11_name)) {
1755 current_view_->message(
1756 bformat(_("Set-color \"%1$s\" failed "
1757 "- color is undefined or "
1758 "may not be redefined"),
1759 from_utf8(lyx_name)));
1762 // Make sure we don't keep old colors in cache.
1763 d->color_cache_.clear();
1764 // Update the current view
1765 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1769 case LFUN_LYXRC_APPLY: {
1770 // reset active key sequences, since the bindings
1771 // are updated (bug 6064)
1773 LyXRC const lyxrc_orig = lyxrc;
1775 istringstream ss(to_utf8(cmd.argument()));
1776 bool const success = lyxrc.read(ss);
1779 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1780 << "Unable to read lyxrc data"
1785 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1787 // If the request comes from the minibuffer, then we can't reset
1788 // the GUI, since that would destory the minibuffer itself and
1789 // cause a crash, since we are currently in one of the methods of
1790 // GuiCommandBuffer. See bug #8540.
1791 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1794 // FIXME Unfortunately, that leaves a bug here, since we cannot
1795 // reset the GUI in this case. If the changes to lyxrc affected the
1796 // UI, then, nothing would happen. This seems fairly unlikely, but
1797 // it definitely is a bug.
1802 case LFUN_COMMAND_PREFIX:
1803 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1808 d->meta_fake_bit = NoModifier;
1809 GuiView * gv = currentView();
1810 if (gv && gv->currentBufferView())
1811 // cancel any selection
1812 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1813 dr.setMessage(from_ascii(N_("Cancel")));
1816 case LFUN_META_PREFIX:
1817 d->meta_fake_bit = AltModifier;
1818 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1821 // --- Menus -----------------------------------------------
1822 case LFUN_RECONFIGURE:
1823 // argument is any additional parameter to the configure.py command
1824 reconfigure(to_utf8(cmd.argument()));
1827 // --- lyxserver commands ----------------------------
1828 case LFUN_SERVER_GET_FILENAME: {
1829 if (current_view_ && current_view_->documentBufferView()) {
1830 docstring const fname = from_utf8(
1831 current_view_->documentBufferView()->buffer().absFileName());
1832 dr.setMessage(fname);
1833 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1835 dr.setMessage(docstring());
1836 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1841 case LFUN_SERVER_NOTIFY: {
1842 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1843 dr.setMessage(dispatch_buffer);
1844 theServer().notifyClient(to_utf8(dispatch_buffer));
1848 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1849 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1855 string rest = split(argument, countstr, ' ');
1856 int const count = convert<int>(countstr);
1857 // an arbitrary number to limit number of iterations
1858 int const max_iter = 10000;
1859 if (count > max_iter) {
1860 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1863 for (int i = 0; i < count; ++i)
1864 dispatch(lyxaction.lookupFunc(rest));
1869 case LFUN_COMMAND_SEQUENCE: {
1870 // argument contains ';'-terminated commands
1871 string arg = argument;
1872 // FIXME: this LFUN should also work without any view.
1873 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1874 ? &(current_view_->documentBufferView()->buffer()) : 0;
1876 buffer->undo().beginUndoGroup();
1877 while (!arg.empty()) {
1879 arg = split(arg, first, ';');
1880 FuncRequest func(lyxaction.lookupFunc(first));
1881 func.setOrigin(cmd.origin());
1884 // the buffer may have been closed by one action
1885 if (theBufferList().isLoaded(buffer))
1886 buffer->undo().endUndoGroup();
1890 case LFUN_BUFFER_FORALL: {
1891 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1893 map<Buffer *, GuiView *> views_lVisible;
1894 map<GuiView *, Buffer *> activeBuffers;
1896 QList<GuiView *> allViews = d->views_.values();
1898 // this for does not modify any buffer. It just collects info on local
1899 // visibility of buffers and on which buffer is active in each view.
1900 Buffer * const last = theBufferList().last();
1901 for(GuiView * view : allViews) {
1902 // all of the buffers might be locally hidden. That is, there is no
1904 if (!view || !view->currentBufferView())
1905 activeBuffers[view] = 0;
1907 activeBuffers[view] = &view->currentBufferView()->buffer();
1909 // find out if each is locally visible or locally hidden.
1910 // we don't use a for loop as the buffer list cycles.
1911 Buffer * b = theBufferList().first();
1913 bool const locallyVisible = view && view->workArea(*b);
1914 if (locallyVisible) {
1915 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1916 // only need to overwrite/add if we don't already know a buffer is globally
1917 // visible or we do know but we would prefer to dispatch LFUN from the
1918 // current view because of cursor position issues.
1919 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1920 views_lVisible[b] = view;
1924 b = theBufferList().next(b);
1928 GuiView * const homeView = currentView();
1929 Buffer * b = theBufferList().first();
1930 Buffer * nextBuf = 0;
1931 int numProcessed = 0;
1934 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1936 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1938 // first change to a view where b is locally visible, preferably current_view_.
1939 GuiView * const vLv = views_lVisible[b];
1941 lyx::dispatch(funcToRun);
1949 // put things back to how they were (if possible).
1950 for (GuiView * view : allViews) {
1951 Buffer * originalBuf = activeBuffers[view];
1952 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1953 if (theBufferList().isLoaded(originalBuf))
1954 view->setBuffer(originalBuf);
1956 homeView->setFocus();
1958 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1962 case LFUN_COMMAND_ALTERNATIVES: {
1963 // argument contains ';'-terminated commands
1964 string arg = argument;
1965 while (!arg.empty()) {
1967 arg = split(arg, first, ';');
1968 FuncRequest func(lyxaction.lookupFunc(first));
1969 func.setOrigin(cmd.origin());
1970 FuncStatus const stat = getStatus(func);
1971 if (stat.enabled()) {
1981 if (theTopLevelCmdDef().lock(argument, func)) {
1982 func.setOrigin(cmd.origin());
1984 theTopLevelCmdDef().release(argument);
1986 if (func.action() == LFUN_UNKNOWN_ACTION) {
1987 // unknown command definition
1988 lyxerr << "Warning: unknown command definition `"
1992 // recursion detected
1993 lyxerr << "Warning: Recursion in the command definition `"
1994 << argument << "' detected"
2001 case LFUN_PREFERENCES_SAVE:
2002 lyxrc.write(support::makeAbsPath("preferences",
2003 package().user_support().absFileName()), false);
2006 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2007 string const fname = addName(addPath(package().user_support().absFileName(),
2008 "templates/"), "defaults.lyx");
2009 Buffer defaults(fname);
2011 istringstream ss(argument);
2016 // We need to make sure that, after we recreat the DocumentClass,
2017 // which we do in readHeader, we apply it to the document itself.
2018 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2019 int const unknown_tokens = defaults.readHeader(lex);
2020 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2022 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2023 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2025 if (unknown_tokens != 0) {
2026 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2027 << unknown_tokens << " unknown token"
2028 << (unknown_tokens == 1 ? "" : "s")
2032 if (defaults.writeFile(FileName(defaults.absFileName())))
2033 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2034 makeDisplayPath(fname)));
2037 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2042 case LFUN_BOOKMARK_GOTO:
2043 // go to bookmark, open unopened file and switch to buffer if necessary
2044 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2045 dr.screenUpdate(Update::Force | Update::FitCursor);
2048 case LFUN_BOOKMARK_CLEAR:
2049 theSession().bookmarks().clear();
2052 case LFUN_DEBUG_LEVEL_SET:
2053 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2056 case LFUN_DIALOG_SHOW: {
2057 string const name = cmd.getArg(0);
2059 if ( name == "aboutlyx"
2061 || name == "texinfo"
2062 || name == "progress"
2063 || name == "compare")
2065 // work around: on Mac OS the application
2066 // is not terminated when closing the last view.
2067 // Create a new one to be able to dispatch the
2068 // LFUN_DIALOG_SHOW to this view.
2069 if (current_view_ == 0)
2075 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2078 current_view_->dispatch(cmd, dr);
2082 if (cmd.origin() == FuncRequest::LYXSERVER)
2083 updateCurrentView(cmd, dr);
2087 docstring GuiApplication::viewStatusMessage()
2089 // When meta-fake key is pressed, show the key sequence so far + "M-".
2090 if (d->meta_fake_bit != NoModifier)
2091 return d->keyseq.print(KeySequence::ForGui) + "M-";
2093 // Else, when a non-complete key sequence is pressed,
2094 // show the available options.
2095 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2096 return d->keyseq.printOptions(true);
2102 void GuiApplication::handleKeyFunc(FuncCode action)
2106 if (d->keyseq.length())
2108 GuiView * gv = currentView();
2109 LASSERT(gv && gv->currentBufferView(), return);
2110 BufferView * bv = gv->currentBufferView();
2111 bv->getIntl().getTransManager().deadkey(
2112 c, get_accent(action).accent, bv->cursor().innerText(),
2114 // Need to clear, in case the minibuffer calls these
2117 // copied verbatim from do_accent_char
2118 bv->cursor().resetAnchor();
2122 //Keep this in sync with GuiApplication::processKeySym below
2123 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2124 KeyModifier state) const
2126 // Do nothing if we have nothing
2127 if (!keysym.isOK() || keysym.isModifier())
2129 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2131 FuncRequest func = seq.addkey(keysym, state);
2132 // When not cancel or meta-fake, do the normal lookup.
2133 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2135 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2137 // Maybe user can only reach the key via holding down shift.
2138 // Let's see. But only if shift is the only modifier
2139 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2140 // If addkey looked up a command and did not find further commands then
2141 // seq has been reset at this point
2142 func = seq.addkey(keysym, NoModifier);
2144 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2145 << seq.print(KeySequence::Portable) << ']');
2146 return func.action() != LFUN_UNKNOWN_ACTION;
2150 //Keep this in sync with GuiApplication::queryKeySym above
2151 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2153 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2155 // Do nothing if we have nothing (JMarc)
2156 if (!keysym.isOK() || keysym.isModifier()) {
2158 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2160 current_view_->restartCaret();
2164 char_type encoded_last_key = keysym.getUCSEncoded();
2166 // Do a one-deep top-level lookup for
2167 // cancel and meta-fake keys. RVDK_PATCH_5
2168 d->cancel_meta_seq.reset();
2170 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2171 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2173 // When not cancel or meta-fake, do the normal lookup.
2174 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2175 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2176 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2177 // remove Caps Lock and Mod2 as a modifiers
2178 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2179 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2182 // Dont remove this unless you know what you are doing.
2183 d->meta_fake_bit = NoModifier;
2185 // Can this happen now ?
2186 if (func.action() == LFUN_NOACTION)
2187 func = FuncRequest(LFUN_COMMAND_PREFIX);
2189 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2190 << d->keyseq.print(KeySequence::Portable) << ']');
2192 // already here we know if it any point in going further
2193 // why not return already here if action == -1 and
2194 // num_bytes == 0? (Lgb)
2196 if (d->keyseq.length() > 1 && current_view_)
2197 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2200 // Maybe user can only reach the key via holding down shift.
2201 // Let's see. But only if shift is the only modifier
2202 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2203 LYXERR(Debug::KEY, "Trying without shift");
2204 // If addkey looked up a command and did not find further commands then
2205 // seq has been reset at this point
2206 func = d->keyseq.addkey(keysym, NoModifier);
2207 LYXERR(Debug::KEY, "Action now " << func.action());
2210 if (func.action() == LFUN_UNKNOWN_ACTION) {
2211 // We didn't match any of the key sequences.
2212 // See if it's normal insertable text not already
2213 // covered by a binding
2214 if (keysym.isText() && d->keyseq.length() == 1) {
2215 // Non-printable characters (such as ASCII control characters)
2216 // must not be inserted (#5704)
2217 if (!isPrintable(encoded_last_key)) {
2218 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2220 current_view_->restartCaret();
2223 // The following modifier check is not needed on Mac.
2224 // The keysym is either not text or it is different
2225 // from the non-modifier keysym. See #9875 for the
2226 // broken alt-modifier effect of having this code active.
2227 #if !defined(Q_OS_MAC)
2228 // If a non-Shift Modifier is used we have a non-bound key sequence
2229 // (such as Alt+j = j). This should be omitted (#5575).
2230 // On Windows, AltModifier and ControlModifier are both
2231 // set when AltGr is pressed. Therefore, in order to not
2232 // break AltGr-bound symbols (see #5575 for details),
2233 // unbound Ctrl+Alt key sequences are allowed.
2234 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2235 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2236 && !(state & AltModifier && state & ControlModifier)
2240 if (current_view_) {
2241 current_view_->message(_("Unknown function."));
2242 current_view_->restartCaret();
2247 // Since all checks above were passed, we now really have text that
2248 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2249 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2251 LYXERR(Debug::KEY, "isText() is true, inserting.");
2252 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2254 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2255 if (current_view_) {
2256 current_view_->message(_("Unknown function."));
2257 current_view_->restartCaret();
2263 if (func.action() == LFUN_SELF_INSERT) {
2264 if (encoded_last_key != 0) {
2265 docstring const arg(1, encoded_last_key);
2266 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2267 FuncRequest::KEYBOARD));
2268 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2271 processFuncRequest(func);
2275 void GuiApplication::processFuncRequest(FuncRequest const & func)
2277 lyx::dispatch(func);
2281 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2283 addToFuncRequestQueue(func);
2284 processFuncRequestQueueAsync();
2288 void GuiApplication::processFuncRequestQueue()
2290 while (!d->func_request_queue_.empty()) {
2291 processFuncRequest(d->func_request_queue_.front());
2292 d->func_request_queue_.pop();
2297 void GuiApplication::processFuncRequestQueueAsync()
2299 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2303 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2305 d->func_request_queue_.push(func);
2309 void GuiApplication::resetGui()
2311 // Set the language defined by the user.
2315 if (!readUIFile(toqstr(lyxrc.ui_file)))
2316 // Gives some error box here.
2319 if (d->global_menubar_)
2320 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2322 QHash<int, GuiView *>::iterator it;
2323 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2326 gv->setLayoutDirection(layoutDirection());
2330 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2334 void GuiApplication::createView(int view_id)
2336 createView(QString(), true, view_id);
2340 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2343 // release the keyboard which might have been grabed by the global
2344 // menubar on Mac to catch shortcuts even without any GuiView.
2345 if (d->global_menubar_)
2346 d->global_menubar_->releaseKeyboard();
2350 while (d->views_.find(id) != d->views_.end())
2353 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2354 GuiView * view = new GuiView(id);
2355 // `view' is the new current_view_. Tell coverity that is is not 0.
2356 LATTEST(current_view_);
2358 d->views_[id] = view;
2362 setActiveWindow(view);
2365 if (!geometry_arg.isEmpty()) {
2366 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2370 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2371 re.indexIn(geometry_arg);
2372 w = re.cap(1).toInt();
2373 h = re.cap(2).toInt();
2374 x = re.cap(3).toInt();
2375 y = re.cap(4).toInt();
2376 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2377 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2378 // Set initial geometry such that we can get the frame size.
2379 view->setGeometry(x, y, w, h);
2380 int framewidth = view->geometry().x() - view->x();
2381 int titleheight = view->geometry().y() - view->y();
2382 // Negative displacements must be interpreted as distances
2383 // from the right or bottom screen borders.
2384 if (sx == '-' || sy == '-') {
2385 QRect rec = QApplication::desktop()->screenGeometry();
2387 x += rec.width() - w - framewidth;
2389 y += rec.height() - h - titleheight;
2390 view->setGeometry(x, y, w, h);
2392 // Make sure that the left and top frame borders are visible.
2393 if (view->x() < 0 || view->y() < 0) {
2398 view->setGeometry(x, y, w, h);
2406 bool GuiApplication::unhide(Buffer * buf)
2410 currentView()->setBuffer(buf, false);
2415 Clipboard & GuiApplication::clipboard()
2417 return d->clipboard_;
2421 Selection & GuiApplication::selection()
2423 return d->selection_;
2427 FontLoader & GuiApplication::fontLoader()
2429 return d->font_loader_;
2433 Toolbars const & GuiApplication::toolbars() const
2435 return d->toolbars_;
2439 Toolbars & GuiApplication::toolbars()
2441 return d->toolbars_;
2445 Menus const & GuiApplication::menus() const
2451 Menus & GuiApplication::menus()
2457 QList<int> GuiApplication::viewIds() const
2459 return d->views_.keys();
2463 ColorCache & GuiApplication::colorCache()
2465 return d->color_cache_;
2469 int GuiApplication::exec()
2471 // asynchronously handle batch commands. This event will be in
2472 // the event queue in front of other asynchronous events. Hence,
2473 // we can assume in the latter that the gui is setup already.
2474 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2476 return QApplication::exec();
2480 void GuiApplication::exit(int status)
2482 QApplication::exit(status);
2486 void GuiApplication::setGuiLanguage()
2490 // install translation file for Qt built-in dialogs
2491 QString const language_name = QString("qt_") + theLocale.name();
2492 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2493 // Short-named translator can be loaded from a long name, but not the
2494 // opposite. Therefore, long name should be used without truncation.
2495 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2496 if (!d->qt_trans_.load(language_name,
2497 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2498 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2501 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2505 switch (theLocale.language()) {
2506 case QLocale::Arabic :
2507 case QLocale::Hebrew :
2508 case QLocale::Persian :
2509 case QLocale::Urdu :
2510 setLayoutDirection(Qt::RightToLeft);
2513 setLayoutDirection(Qt::LeftToRight);
2518 void GuiApplication::execBatchCommands()
2523 if (!readUIFile(toqstr(lyxrc.ui_file)))
2524 // Gives some error box here.
2528 #if QT_VERSION > 0x040600
2529 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2531 #if QT_VERSION > 0x050100
2532 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2534 // Create the global default menubar which is shown for the dialogs
2535 // and if no GuiView is visible.
2536 // This must be done after the session was recovered to know the "last files".
2537 d->global_menubar_ = new QMenuBar(0);
2538 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2541 lyx::execBatchCommands();
2545 QAbstractItemModel * GuiApplication::languageModel()
2547 if (d->language_model_)
2548 return d->language_model_;
2550 QStandardItemModel * lang_model = new QStandardItemModel(this);
2551 lang_model->insertColumns(0, 3);
2552 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2553 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2554 Languages::const_iterator it = lyx::languages.begin();
2555 Languages::const_iterator end = lyx::languages.end();
2556 for (; it != end; ++it) {
2557 int current_row = lang_model->rowCount();
2558 lang_model->insertRows(current_row, 1);
2559 QModelIndex pl_item = lang_model->index(current_row, 0);
2560 QModelIndex sp_item = lang_model->index(current_row, 1);
2561 QModelIndex th_item = lang_model->index(current_row, 2);
2562 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2563 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2564 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2565 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2566 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2567 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2568 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2569 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2570 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2571 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2573 d->language_model_ = new QSortFilterProxyModel(this);
2574 d->language_model_->setSourceModel(lang_model);
2575 d->language_model_->setSortLocaleAware(true);
2576 return d->language_model_;
2580 void GuiApplication::restoreGuiSession()
2582 if (!lyxrc.load_session)
2585 Session & session = theSession();
2586 LastOpenedSection::LastOpened const & lastopened =
2587 session.lastOpened().getfiles();
2589 validateCurrentView();
2591 FileName active_file;
2592 // do not add to the lastfile list since these files are restored from
2593 // last session, and should be already there (regular files), or should
2594 // not be added at all (help files).
2595 for (size_t i = 0; i < lastopened.size(); ++i) {
2596 FileName const & file_name = lastopened[i].file_name;
2597 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2598 && current_view_->documentBufferView() != 0)) {
2599 boost::crc_32_type crc;
2600 string const & fname = file_name.absFileName();
2601 crc = for_each(fname.begin(), fname.end(), crc);
2602 createView(crc.checksum());
2604 current_view_->loadDocument(file_name, false);
2606 if (lastopened[i].active)
2607 active_file = file_name;
2610 // Restore last active buffer
2611 Buffer * buffer = theBufferList().getBuffer(active_file);
2612 if (buffer && current_view_)
2613 current_view_->setBuffer(buffer);
2615 // clear this list to save a few bytes of RAM
2616 session.lastOpened().clear();
2620 QString const GuiApplication::romanFontName()
2623 font.setStyleHint(QFont::Serif);
2624 font.setFamily("serif");
2626 return QFontInfo(font).family();
2630 QString const GuiApplication::sansFontName()
2633 font.setStyleHint(QFont::SansSerif);
2634 font.setFamily("sans");
2636 return QFontInfo(font).family();
2640 QString const GuiApplication::typewriterFontName()
2642 return QFontInfo(typewriterSystemFont()).family();
2647 // We cannot use QFont::fixedPitch() because it doesn't
2648 // return the fact but only if it is requested.
2649 static bool isFixedPitch(const QFont & font) {
2650 const QFontInfo fi(font);
2651 return fi.fixedPitch();
2656 QFont const GuiApplication::typewriterSystemFont()
2658 #if QT_VERSION >= 0x050200
2659 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2661 QFont font("monospace");
2663 if (!isFixedPitch(font)) {
2664 // try to enforce a real monospaced font
2665 font.setStyleHint(QFont::Monospace);
2666 if (!isFixedPitch(font)) {
2667 font.setStyleHint(QFont::TypeWriter);
2668 if (!isFixedPitch(font)) font.setFamily("courier");
2672 // On a Mac the result is too small and it's not practical to
2673 // rely on Qtconfig utility to change the system settings of Qt.
2674 font.setPointSize(12);
2680 void GuiApplication::handleRegularEvents()
2682 ForkedCallsController::handleCompletedProcesses();
2686 bool GuiApplication::event(QEvent * e)
2689 case QEvent::FileOpen: {
2690 // Open a file; this happens only on Mac OS X for now.
2692 // We do this asynchronously because on startup the batch
2693 // commands are not executed here yet and the gui is not ready
2695 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2696 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2697 processFuncRequestAsync(fr);
2702 return QApplication::event(e);
2707 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2710 return QApplication::notify(receiver, event);
2712 catch (ExceptionMessage const & e) {
2714 case ErrorException:
2716 setQuitOnLastWindowClosed(false);
2718 Alert::error(e.title_, e.details_);
2720 // Properly crash in debug mode in order to get a useful backtrace.
2723 // In release mode, try to exit gracefully.
2725 // FIXME: GCC 7 thinks we can fall through here. Can we?
2727 case BufferException: {
2728 if (!current_view_ || !current_view_->documentBufferView())
2730 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2731 docstring details = e.details_ + '\n';
2732 details += buf->emergencyWrite();
2733 theBufferList().release(buf);
2734 details += "\n" + _("The current document was closed.");
2735 Alert::error(e.title_, details);
2738 case WarningException:
2739 Alert::warning(e.title_, e.details_);
2743 catch (exception const & e) {
2744 docstring s = _("LyX has caught an exception, it will now "
2745 "attempt to save all unsaved documents and exit."
2747 s += from_ascii(e.what());
2748 Alert::error(_("Software exception Detected"), s);
2752 docstring s = _("LyX has caught some really weird exception, it will "
2753 "now attempt to save all unsaved documents and exit.");
2754 Alert::error(_("Software exception Detected"), s);
2762 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2764 QColor const & qcol = d->color_cache_.get(col);
2765 if (!qcol.isValid()) {
2771 rgbcol.r = qcol.red();
2772 rgbcol.g = qcol.green();
2773 rgbcol.b = qcol.blue();
2778 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2780 QColor const qcol(lcolor.getX11Name(col).c_str());
2781 if (!qcol.isValid()) {
2787 rgbcol.r = qcol.red();
2788 rgbcol.g = qcol.green();
2789 rgbcol.b = qcol.blue();
2794 string const GuiApplication::hexName(ColorCode col)
2796 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2800 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2802 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2803 d->socket_notifiers_[fd] = sn;
2804 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2808 void GuiApplication::socketDataReceived(int fd)
2810 d->socket_notifiers_[fd]->func_();
2814 void GuiApplication::unregisterSocketCallback(int fd)
2816 d->socket_notifiers_.take(fd)->setEnabled(false);
2820 void GuiApplication::commitData(QSessionManager & sm)
2822 /** The implementation is required to avoid an application exit
2823 ** when session state save is triggered by session manager.
2824 ** The default implementation sends a close event to all
2825 ** visible top level widgets when session managment allows
2827 ** We are changing that to check the state of each buffer in all
2828 ** views and ask the users what to do if buffers are dirty.
2829 ** Furthermore, we save the session state.
2830 ** We do NOT close the views here since the user still can cancel
2831 ** the logout process (see #9277); also, this would hide LyX from
2832 ** an OSes own session handling (application restoration).
2834 #ifdef QT_NO_SESSIONMANAGER
2836 #warning Qt is compiled without session manager
2838 #pragma message("warning: Qt is compiled without session manager")
2842 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2850 void GuiApplication::unregisterView(GuiView * gv)
2852 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2853 d->views_.remove(gv->id());
2854 if (current_view_ == gv)
2860 bool GuiApplication::closeAllViews()
2862 if (d->views_.empty())
2865 // When a view/window was closed before without quitting LyX, there
2866 // are already entries in the lastOpened list.
2867 theSession().lastOpened().clear();
2869 QList<GuiView *> const views = d->views_.values();
2870 for (GuiView * view : views) {
2871 if (!view->closeScheduled())
2880 bool GuiApplication::prepareAllViewsForLogout()
2882 if (d->views_.empty())
2885 QList<GuiView *> const views = d->views_.values();
2886 for (GuiView * view : views) {
2887 if (!view->prepareAllBuffersForLogout())
2895 GuiView & GuiApplication::view(int id) const
2897 LAPPERR(d->views_.contains(id));
2898 return *d->views_.value(id);
2902 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2904 QList<GuiView *> const views = d->views_.values();
2905 for (GuiView * view : views)
2906 view->hideDialog(name, inset);
2910 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2912 Buffer const * buffer_ = 0;
2913 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2914 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2915 if (Buffer const * ptr = (*it)->updateInset(inset))
2922 bool GuiApplication::searchMenu(FuncRequest const & func,
2923 docstring_list & names) const
2925 return d->menus_.searchMenu(func, names);
2929 // Ensure that a file is read only once (prevents include loops)
2930 static QStringList uifiles;
2931 // store which ui files define Toolbars
2932 static QStringList toolbar_uifiles;
2935 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2946 LexerKeyword uitags[] = {
2947 { "format", ui_format },
2948 { "include", ui_include },
2949 { "menuset", ui_menuset },
2950 { "toolbars", ui_toolbars },
2951 { "toolbarset", ui_toolbarset }
2955 lex.setFile(ui_path);
2957 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2961 if (lyxerr.debugging(Debug::PARSER))
2962 lex.printTable(lyxerr);
2965 // format before introduction of format tag
2966 unsigned int format = 0;
2967 while (lex.isOK()) {
2968 int const status = lex.lex();
2970 // we have to do this check here, outside the switch,
2971 // because otherwise we would start reading include files,
2972 // e.g., if the first tag we hit was an include tag.
2973 if (status == ui_format)
2975 format = lex.getInteger();
2979 // this will trigger unless the first tag we hit is a format
2980 // tag, with the right format.
2981 if (format != LFUN_FORMAT)
2982 return FormatMismatch;
2985 case Lexer::LEX_FEOF:
2990 QString const file = toqstr(lex.getString());
2991 bool const success = readUIFile(file, true);
2993 LYXERR0("Failed to read included file: " << fromqstr(file));
3000 d->menus_.read(lex);
3004 d->toolbars_.readToolbars(lex);
3008 d->toolbars_.readToolbarSettings(lex);
3009 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3013 if (!rtrim(lex.getString()).empty())
3014 lex.printError("LyX::ReadUIFile: "
3015 "Unknown menu tag: `$$Token'");
3017 LYXERR0("Error with status: " << status);
3023 return (error ? ReadError : ReadOK);
3027 bool GuiApplication::readUIFile(QString const & name, bool include)
3029 LYXERR(Debug::INIT, "About to read " << name << "...");
3033 ui_path = libFileSearch("ui", name, "inc");
3034 if (ui_path.empty())
3035 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3037 ui_path = libFileSearch("ui", name, "ui");
3040 if (ui_path.empty()) {
3041 static const QString defaultUIFile = "default";
3042 LYXERR(Debug::INIT, "Could not find " << name);
3044 Alert::warning(_("Could not find UI definition file"),
3045 bformat(_("Error while reading the included file\n%1$s\n"
3046 "Please check your installation."), qstring_to_ucs4(name)));
3049 if (name == defaultUIFile) {
3050 LYXERR(Debug::INIT, "Could not find default UI file!!");
3051 Alert::warning(_("Could not find default UI file"),
3052 _("LyX could not find the default UI file!\n"
3053 "Please check your installation."));
3056 Alert::warning(_("Could not find UI definition file"),
3057 bformat(_("Error while reading the configuration file\n%1$s\n"
3058 "Falling back to default.\n"
3059 "Please look under Tools>Preferences>User Interface and\n"
3060 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3061 return readUIFile(defaultUIFile, false);
3064 QString const uifile = toqstr(ui_path.absFileName());
3065 if (uifiles.contains(uifile)) {
3067 // We are reading again the top uifile so reset the safeguard:
3070 d->toolbars_.reset();
3072 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3073 << "Is this an include loop?");
3077 uifiles.push_back(uifile);
3079 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3081 ReturnValues retval = readUIFile(ui_path);
3083 if (retval == FormatMismatch) {
3084 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3085 TempFile tmp("convertXXXXXX.ui");
3086 FileName const tempfile = tmp.name();
3087 bool const success = prefs2prefs(ui_path, tempfile, true);
3089 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3090 " to format " << LFUN_FORMAT << ".");
3092 retval = readUIFile(tempfile);
3096 if (retval != ReadOK) {
3097 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3105 settings.beginGroup("ui_files");
3106 bool touched = false;
3107 for (int i = 0; i != uifiles.size(); ++i) {
3108 QFileInfo fi(uifiles[i]);
3109 QDateTime const date_value = fi.lastModified();
3110 QString const name_key = QString::number(i);
3111 // if an ui file which defines Toolbars has changed,
3112 // we have to reset the settings
3113 if (toolbar_uifiles.contains(uifiles[i])
3114 && (!settings.contains(name_key)
3115 || settings.value(name_key).toString() != uifiles[i]
3116 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3118 settings.setValue(name_key, uifiles[i]);
3119 settings.setValue(name_key + "/date", date_value);
3122 settings.endGroup();
3124 settings.remove("views");
3130 void GuiApplication::onLastWindowClosed()
3132 if (d->global_menubar_)
3133 d->global_menubar_->grabKeyboard();
3137 void GuiApplication::startLongOperation() {
3138 d->key_checker_.start();
3142 bool GuiApplication::longOperationCancelled() {
3143 return d->key_checker_.pressed();
3147 void GuiApplication::stopLongOperation() {
3148 d->key_checker_.stop();
3152 bool GuiApplication::longOperationStarted() {
3153 return d->key_checker_.started();
3157 ////////////////////////////////////////////////////////////////////////
3159 // X11 specific stuff goes here...
3162 bool GuiApplication::x11EventFilter(XEvent * xev)
3167 switch (xev->type) {
3168 case SelectionRequest: {
3169 if (xev->xselectionrequest.selection != XA_PRIMARY)
3171 LYXERR(Debug::SELECTION, "X requested selection.");
3172 BufferView * bv = current_view_->currentBufferView();
3174 docstring const sel = bv->requestSelection();
3176 d->selection_.put(sel);
3177 // Refresh the selection request timestamp.
3178 // We have to do this by ourselves as Qt seems
3179 // not doing that, maybe because of our
3180 // "persistent selection" implementation
3181 // (see comments in GuiSelection.cpp).
3182 XSelectionEvent nev;
3183 nev.type = SelectionNotify;
3184 nev.display = xev->xselectionrequest.display;
3185 nev.requestor = xev->xselectionrequest.requestor;
3186 nev.selection = xev->xselectionrequest.selection;
3187 nev.target = xev->xselectionrequest.target;
3188 nev.property = 0L; // None
3189 nev.time = CurrentTime;
3190 XSendEvent(QX11Info::display(),
3191 nev.requestor, False, 0,
3192 reinterpret_cast<XEvent *>(&nev));
3198 case SelectionClear: {
3199 if (xev->xselectionclear.selection != XA_PRIMARY)
3201 LYXERR(Debug::SELECTION, "Lost selection.");
3202 BufferView * bv = current_view_->currentBufferView();
3204 bv->clearSelection();
3210 #elif defined(QPA_XCB)
3211 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3212 void * message, long *)
3214 if (!current_view_ || eventType != "xcb_generic_event_t")
3217 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3219 switch (ev->response_type) {
3220 case XCB_SELECTION_REQUEST: {
3221 xcb_selection_request_event_t * srev =
3222 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3223 if (srev->selection != XCB_ATOM_PRIMARY)
3225 LYXERR(Debug::SELECTION, "X requested selection.");
3226 BufferView * bv = current_view_->currentBufferView();
3228 docstring const sel = bv->requestSelection();
3230 d->selection_.put(sel);
3231 #ifdef HAVE_QT5_X11_EXTRAS
3232 // Refresh the selection request timestamp.
3233 // We have to do this by ourselves as Qt seems
3234 // not doing that, maybe because of our
3235 // "persistent selection" implementation
3236 // (see comments in GuiSelection.cpp).
3237 xcb_selection_notify_event_t nev;
3238 nev.response_type = XCB_SELECTION_NOTIFY;
3239 nev.requestor = srev->requestor;
3240 nev.selection = srev->selection;
3241 nev.target = srev->target;
3242 nev.property = XCB_NONE;
3243 nev.time = XCB_CURRENT_TIME;
3244 xcb_connection_t * con = QX11Info::connection();
3245 xcb_send_event(con, 0, srev->requestor,
3246 XCB_EVENT_MASK_NO_EVENT,
3247 reinterpret_cast<char const *>(&nev));
3255 case XCB_SELECTION_CLEAR: {
3256 xcb_selection_clear_event_t * scev =
3257 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3258 if (scev->selection != XCB_ATOM_PRIMARY)
3260 LYXERR(Debug::SELECTION, "Lost selection.");
3261 BufferView * bv = current_view_->currentBufferView();
3263 bv->clearSelection();
3271 } // namespace frontend
3274 void hideDialogs(std::string const & name, Inset * inset)
3277 frontend::guiApp->hideDialogs(name, inset);
3281 ////////////////////////////////////////////////////////////////////
3285 ////////////////////////////////////////////////////////////////////
3287 frontend::FontLoader & theFontLoader()
3289 LAPPERR(frontend::guiApp);
3290 return frontend::guiApp->fontLoader();
3294 frontend::FontMetrics const & theFontMetrics(Font const & f)
3296 return theFontMetrics(f.fontInfo());
3300 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3302 LAPPERR(frontend::guiApp);
3303 return frontend::guiApp->fontLoader().metrics(f);
3307 ////////////////////////////////////////////////////////////////////
3311 ////////////////////////////////////////////////////////////////////
3313 frontend::Clipboard & theClipboard()
3315 LAPPERR(frontend::guiApp);
3316 return frontend::guiApp->clipboard();
3320 frontend::Selection & theSelection()
3322 LAPPERR(frontend::guiApp);
3323 return frontend::guiApp->selection();
3329 #include "moc_GuiApplication.cpp"