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 dr.screenUpdate(Update::Force | Update::FitCursor);
1639 case LFUN_BUFFER_NEW:
1640 validateCurrentView();
1642 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1643 createView(QString(), false); // keep hidden
1644 current_view_->newDocument(to_utf8(cmd.argument()), false);
1645 current_view_->show();
1646 setActiveWindow(current_view_);
1648 current_view_->newDocument(to_utf8(cmd.argument()), false);
1652 case LFUN_BUFFER_NEW_TEMPLATE:
1653 validateCurrentView();
1655 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1657 current_view_->newDocument(to_utf8(cmd.argument()), true);
1658 if (!current_view_->documentBufferView())
1659 current_view_->close();
1661 current_view_->newDocument(to_utf8(cmd.argument()), true);
1665 case LFUN_FILE_OPEN: {
1666 // FIXME: normally the code below is not needed, since getStatus makes sure that
1667 // current_view_ is not null.
1668 validateCurrentView();
1669 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1670 string const fname = to_utf8(cmd.argument());
1671 bool const is_open = FileName::isAbsolute(fname)
1672 && theBufferList().getBuffer(FileName(fname));
1674 || (!lyxrc.open_buffers_in_tabs
1675 && current_view_->documentBufferView() != 0
1677 // We want the ui session to be saved per document and not per
1678 // window number. The filename crc is a good enough identifier.
1679 boost::crc_32_type crc;
1680 crc = for_each(fname.begin(), fname.end(), crc);
1681 createView(crc.checksum());
1682 current_view_->openDocument(fname);
1683 if (!current_view_->documentBufferView())
1684 current_view_->close();
1685 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1686 current_view_->raise();
1687 current_view_->activateWindow();
1688 current_view_->showNormal();
1691 current_view_->openDocument(fname);
1692 if (cmd.origin() == FuncRequest::LYXSERVER) {
1693 current_view_->raise();
1694 current_view_->activateWindow();
1695 current_view_->showNormal();
1701 case LFUN_HELP_OPEN: {
1702 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1703 if (current_view_ == 0)
1705 string const arg = to_utf8(cmd.argument());
1707 current_view_->message(_("Missing argument"));
1710 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1712 fname = i18nLibFileSearch("examples", arg, "lyx");
1714 if (fname.empty()) {
1715 lyxerr << "LyX: unable to find documentation file `"
1716 << arg << "'. Bad installation?" << endl;
1719 current_view_->message(bformat(_("Opening help file %1$s..."),
1720 makeDisplayPath(fname.absFileName())));
1721 Buffer * buf = current_view_->loadDocument(fname, false);
1723 buf->setReadonly(!current_view_->develMode());
1727 case LFUN_SET_COLOR: {
1729 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1730 if (lyx_name.empty() || x11_name.empty()) {
1732 current_view_->message(
1733 _("Syntax: set-color <lyx_name> <x11_name>"));
1738 // FIXME: The graphics cache no longer has a changeDisplay method.
1739 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1740 bool const graphicsbg_changed =
1741 lyx_name == graphicsbg && x11_name != graphicsbg;
1742 if (graphicsbg_changed)
1743 graphics::GCache::get().changeDisplay(true);
1746 if (!lcolor.setColor(lyx_name, x11_name)) {
1748 current_view_->message(
1749 bformat(_("Set-color \"%1$s\" failed "
1750 "- color is undefined or "
1751 "may not be redefined"),
1752 from_utf8(lyx_name)));
1755 // Make sure we don't keep old colors in cache.
1756 d->color_cache_.clear();
1757 // Update the current view
1758 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1762 case LFUN_LYXRC_APPLY: {
1763 // reset active key sequences, since the bindings
1764 // are updated (bug 6064)
1766 LyXRC const lyxrc_orig = lyxrc;
1768 istringstream ss(to_utf8(cmd.argument()));
1769 bool const success = lyxrc.read(ss);
1772 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1773 << "Unable to read lyxrc data"
1778 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1780 // If the request comes from the minibuffer, then we can't reset
1781 // the GUI, since that would destory the minibuffer itself and
1782 // cause a crash, since we are currently in one of the methods of
1783 // GuiCommandBuffer. See bug #8540.
1784 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1787 // FIXME Unfortunately, that leaves a bug here, since we cannot
1788 // reset the GUI in this case. If the changes to lyxrc affected the
1789 // UI, then, nothing would happen. This seems fairly unlikely, but
1790 // it definitely is a bug.
1795 case LFUN_COMMAND_PREFIX:
1796 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1801 d->meta_fake_bit = NoModifier;
1802 GuiView * gv = currentView();
1803 if (gv && gv->currentBufferView())
1804 // cancel any selection
1805 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1806 dr.setMessage(from_ascii(N_("Cancel")));
1809 case LFUN_META_PREFIX:
1810 d->meta_fake_bit = AltModifier;
1811 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1814 // --- Menus -----------------------------------------------
1815 case LFUN_RECONFIGURE:
1816 // argument is any additional parameter to the configure.py command
1817 reconfigure(to_utf8(cmd.argument()));
1820 // --- lyxserver commands ----------------------------
1821 case LFUN_SERVER_GET_FILENAME: {
1822 if (current_view_ && current_view_->documentBufferView()) {
1823 docstring const fname = from_utf8(
1824 current_view_->documentBufferView()->buffer().absFileName());
1825 dr.setMessage(fname);
1826 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1828 dr.setMessage(docstring());
1829 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1834 case LFUN_SERVER_NOTIFY: {
1835 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1836 dr.setMessage(dispatch_buffer);
1837 theServer().notifyClient(to_utf8(dispatch_buffer));
1841 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1842 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1848 string rest = split(argument, countstr, ' ');
1849 int const count = convert<int>(countstr);
1850 // an arbitrary number to limit number of iterations
1851 int const max_iter = 10000;
1852 if (count > max_iter) {
1853 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1856 for (int i = 0; i < count; ++i)
1857 dispatch(lyxaction.lookupFunc(rest));
1862 case LFUN_COMMAND_SEQUENCE: {
1863 // argument contains ';'-terminated commands
1864 string arg = argument;
1865 // FIXME: this LFUN should also work without any view.
1866 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1867 ? &(current_view_->documentBufferView()->buffer()) : 0;
1869 buffer->undo().beginUndoGroup();
1870 while (!arg.empty()) {
1872 arg = split(arg, first, ';');
1873 FuncRequest func(lyxaction.lookupFunc(first));
1874 func.setOrigin(cmd.origin());
1877 // the buffer may have been closed by one action
1878 if (theBufferList().isLoaded(buffer))
1879 buffer->undo().endUndoGroup();
1883 case LFUN_BUFFER_FORALL: {
1884 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1886 map<Buffer *, GuiView *> views_lVisible;
1887 map<GuiView *, Buffer *> activeBuffers;
1889 QList<GuiView *> allViews = d->views_.values();
1891 // this for does not modify any buffer. It just collects info on local
1892 // visibility of buffers and on which buffer is active in each view.
1893 Buffer * const last = theBufferList().last();
1894 for(GuiView * view : allViews) {
1895 // all of the buffers might be locally hidden. That is, there is no
1897 if (!view || !view->currentBufferView())
1898 activeBuffers[view] = 0;
1900 activeBuffers[view] = &view->currentBufferView()->buffer();
1902 // find out if each is locally visible or locally hidden.
1903 // we don't use a for loop as the buffer list cycles.
1904 Buffer * b = theBufferList().first();
1906 bool const locallyVisible = view && view->workArea(*b);
1907 if (locallyVisible) {
1908 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1909 // only need to overwrite/add if we don't already know a buffer is globally
1910 // visible or we do know but we would prefer to dispatch LFUN from the
1911 // current view because of cursor position issues.
1912 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1913 views_lVisible[b] = view;
1917 b = theBufferList().next(b);
1921 GuiView * const homeView = currentView();
1922 Buffer * b = theBufferList().first();
1923 Buffer * nextBuf = 0;
1924 int numProcessed = 0;
1927 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1929 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1931 // first change to a view where b is locally visible, preferably current_view_.
1932 GuiView * const vLv = views_lVisible[b];
1934 lyx::dispatch(funcToRun);
1942 // put things back to how they were (if possible).
1943 for (GuiView * view : allViews) {
1944 Buffer * originalBuf = activeBuffers[view];
1945 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1946 if (theBufferList().isLoaded(originalBuf))
1947 view->setBuffer(originalBuf);
1949 homeView->setFocus();
1951 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1955 case LFUN_COMMAND_ALTERNATIVES: {
1956 // argument contains ';'-terminated commands
1957 string arg = argument;
1958 while (!arg.empty()) {
1960 arg = split(arg, first, ';');
1961 FuncRequest func(lyxaction.lookupFunc(first));
1962 func.setOrigin(cmd.origin());
1963 FuncStatus const stat = getStatus(func);
1964 if (stat.enabled()) {
1974 if (theTopLevelCmdDef().lock(argument, func)) {
1975 func.setOrigin(cmd.origin());
1977 theTopLevelCmdDef().release(argument);
1979 if (func.action() == LFUN_UNKNOWN_ACTION) {
1980 // unknown command definition
1981 lyxerr << "Warning: unknown command definition `"
1985 // recursion detected
1986 lyxerr << "Warning: Recursion in the command definition `"
1987 << argument << "' detected"
1994 case LFUN_PREFERENCES_SAVE:
1995 lyxrc.write(support::makeAbsPath("preferences",
1996 package().user_support().absFileName()), false);
1999 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2000 string const fname = addName(addPath(package().user_support().absFileName(),
2001 "templates/"), "defaults.lyx");
2002 Buffer defaults(fname);
2004 istringstream ss(argument);
2009 // We need to make sure that, after we recreat the DocumentClass,
2010 // which we do in readHeader, we apply it to the document itself.
2011 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2012 int const unknown_tokens = defaults.readHeader(lex);
2013 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2015 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2016 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2018 if (unknown_tokens != 0) {
2019 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2020 << unknown_tokens << " unknown token"
2021 << (unknown_tokens == 1 ? "" : "s")
2025 if (defaults.writeFile(FileName(defaults.absFileName())))
2026 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2027 makeDisplayPath(fname)));
2030 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2035 case LFUN_BOOKMARK_GOTO:
2036 // go to bookmark, open unopened file and switch to buffer if necessary
2037 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2038 dr.screenUpdate(Update::Force | Update::FitCursor);
2041 case LFUN_BOOKMARK_CLEAR:
2042 theSession().bookmarks().clear();
2045 case LFUN_DEBUG_LEVEL_SET:
2046 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2049 case LFUN_DIALOG_SHOW: {
2050 string const name = cmd.getArg(0);
2052 if ( name == "aboutlyx"
2054 || name == "texinfo"
2055 || name == "progress"
2056 || name == "compare")
2058 // work around: on Mac OS the application
2059 // is not terminated when closing the last view.
2060 // Create a new one to be able to dispatch the
2061 // LFUN_DIALOG_SHOW to this view.
2062 if (current_view_ == 0)
2068 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2071 current_view_->dispatch(cmd, dr);
2075 if (cmd.origin() == FuncRequest::LYXSERVER)
2076 updateCurrentView(cmd, dr);
2080 docstring GuiApplication::viewStatusMessage()
2082 // When meta-fake key is pressed, show the key sequence so far + "M-".
2083 if (d->meta_fake_bit != NoModifier)
2084 return d->keyseq.print(KeySequence::ForGui) + "M-";
2086 // Else, when a non-complete key sequence is pressed,
2087 // show the available options.
2088 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2089 return d->keyseq.printOptions(true);
2095 void GuiApplication::handleKeyFunc(FuncCode action)
2099 if (d->keyseq.length())
2101 GuiView * gv = currentView();
2102 LASSERT(gv && gv->currentBufferView(), return);
2103 BufferView * bv = gv->currentBufferView();
2104 bv->getIntl().getTransManager().deadkey(
2105 c, get_accent(action).accent, bv->cursor().innerText(),
2107 // Need to clear, in case the minibuffer calls these
2110 // copied verbatim from do_accent_char
2111 bv->cursor().resetAnchor();
2115 //Keep this in sync with GuiApplication::processKeySym below
2116 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2117 KeyModifier state) const
2119 // Do nothing if we have nothing
2120 if (!keysym.isOK() || keysym.isModifier())
2122 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2124 FuncRequest func = seq.addkey(keysym, state);
2125 // When not cancel or meta-fake, do the normal lookup.
2126 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2128 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2130 // Maybe user can only reach the key via holding down shift.
2131 // Let's see. But only if shift is the only modifier
2132 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2133 // If addkey looked up a command and did not find further commands then
2134 // seq has been reset at this point
2135 func = seq.addkey(keysym, NoModifier);
2137 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2138 << seq.print(KeySequence::Portable) << ']');
2139 return func.action() != LFUN_UNKNOWN_ACTION;
2143 //Keep this in sync with GuiApplication::queryKeySym above
2144 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2146 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2148 // Do nothing if we have nothing (JMarc)
2149 if (!keysym.isOK() || keysym.isModifier()) {
2151 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2153 current_view_->restartCaret();
2157 char_type encoded_last_key = keysym.getUCSEncoded();
2159 // Do a one-deep top-level lookup for
2160 // cancel and meta-fake keys. RVDK_PATCH_5
2161 d->cancel_meta_seq.reset();
2163 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2164 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2166 // When not cancel or meta-fake, do the normal lookup.
2167 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2168 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2169 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2170 // remove Caps Lock and Mod2 as a modifiers
2171 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2172 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2175 // Dont remove this unless you know what you are doing.
2176 d->meta_fake_bit = NoModifier;
2178 // Can this happen now ?
2179 if (func.action() == LFUN_NOACTION)
2180 func = FuncRequest(LFUN_COMMAND_PREFIX);
2182 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2183 << d->keyseq.print(KeySequence::Portable) << ']');
2185 // already here we know if it any point in going further
2186 // why not return already here if action == -1 and
2187 // num_bytes == 0? (Lgb)
2189 if (d->keyseq.length() > 1 && current_view_)
2190 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2193 // Maybe user can only reach the key via holding down shift.
2194 // Let's see. But only if shift is the only modifier
2195 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2196 LYXERR(Debug::KEY, "Trying without shift");
2197 // If addkey looked up a command and did not find further commands then
2198 // seq has been reset at this point
2199 func = d->keyseq.addkey(keysym, NoModifier);
2200 LYXERR(Debug::KEY, "Action now " << func.action());
2203 if (func.action() == LFUN_UNKNOWN_ACTION) {
2204 // We didn't match any of the key sequences.
2205 // See if it's normal insertable text not already
2206 // covered by a binding
2207 if (keysym.isText() && d->keyseq.length() == 1) {
2208 // Non-printable characters (such as ASCII control characters)
2209 // must not be inserted (#5704)
2210 if (!isPrintable(encoded_last_key)) {
2211 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2213 current_view_->restartCaret();
2216 // The following modifier check is not needed on Mac.
2217 // The keysym is either not text or it is different
2218 // from the non-modifier keysym. See #9875 for the
2219 // broken alt-modifier effect of having this code active.
2220 #if !defined(Q_OS_MAC)
2221 // If a non-Shift Modifier is used we have a non-bound key sequence
2222 // (such as Alt+j = j). This should be omitted (#5575).
2223 // On Windows, AltModifier and ControlModifier are both
2224 // set when AltGr is pressed. Therefore, in order to not
2225 // break AltGr-bound symbols (see #5575 for details),
2226 // unbound Ctrl+Alt key sequences are allowed.
2227 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2228 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2229 && !(state & AltModifier && state & ControlModifier)
2233 if (current_view_) {
2234 current_view_->message(_("Unknown function."));
2235 current_view_->restartCaret();
2240 // Since all checks above were passed, we now really have text that
2241 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2242 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2244 LYXERR(Debug::KEY, "isText() is true, inserting.");
2245 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2247 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2248 if (current_view_) {
2249 current_view_->message(_("Unknown function."));
2250 current_view_->restartCaret();
2256 if (func.action() == LFUN_SELF_INSERT) {
2257 if (encoded_last_key != 0) {
2258 docstring const arg(1, encoded_last_key);
2259 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2260 FuncRequest::KEYBOARD));
2261 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2264 processFuncRequest(func);
2268 void GuiApplication::processFuncRequest(FuncRequest const & func)
2270 lyx::dispatch(func);
2274 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2276 addToFuncRequestQueue(func);
2277 processFuncRequestQueueAsync();
2281 void GuiApplication::processFuncRequestQueue()
2283 while (!d->func_request_queue_.empty()) {
2284 processFuncRequest(d->func_request_queue_.front());
2285 d->func_request_queue_.pop();
2290 void GuiApplication::processFuncRequestQueueAsync()
2292 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2296 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2298 d->func_request_queue_.push(func);
2302 void GuiApplication::resetGui()
2304 // Set the language defined by the user.
2308 if (!readUIFile(toqstr(lyxrc.ui_file)))
2309 // Gives some error box here.
2312 if (d->global_menubar_)
2313 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2315 QHash<int, GuiView *>::iterator it;
2316 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2319 gv->setLayoutDirection(layoutDirection());
2323 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2327 void GuiApplication::createView(int view_id)
2329 createView(QString(), true, view_id);
2333 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2336 // release the keyboard which might have been grabed by the global
2337 // menubar on Mac to catch shortcuts even without any GuiView.
2338 if (d->global_menubar_)
2339 d->global_menubar_->releaseKeyboard();
2343 while (d->views_.find(id) != d->views_.end())
2346 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2347 GuiView * view = new GuiView(id);
2348 // `view' is the new current_view_. Tell coverity that is is not 0.
2349 LATTEST(current_view_);
2351 d->views_[id] = view;
2355 setActiveWindow(view);
2358 if (!geometry_arg.isEmpty()) {
2359 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2363 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2364 re.indexIn(geometry_arg);
2365 w = re.cap(1).toInt();
2366 h = re.cap(2).toInt();
2367 x = re.cap(3).toInt();
2368 y = re.cap(4).toInt();
2369 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2370 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2371 // Set initial geometry such that we can get the frame size.
2372 view->setGeometry(x, y, w, h);
2373 int framewidth = view->geometry().x() - view->x();
2374 int titleheight = view->geometry().y() - view->y();
2375 // Negative displacements must be interpreted as distances
2376 // from the right or bottom screen borders.
2377 if (sx == '-' || sy == '-') {
2378 QRect rec = QApplication::desktop()->screenGeometry();
2380 x += rec.width() - w - framewidth;
2382 y += rec.height() - h - titleheight;
2383 view->setGeometry(x, y, w, h);
2385 // Make sure that the left and top frame borders are visible.
2386 if (view->x() < 0 || view->y() < 0) {
2391 view->setGeometry(x, y, w, h);
2399 bool GuiApplication::unhide(Buffer * buf)
2403 currentView()->setBuffer(buf, false);
2408 Clipboard & GuiApplication::clipboard()
2410 return d->clipboard_;
2414 Selection & GuiApplication::selection()
2416 return d->selection_;
2420 FontLoader & GuiApplication::fontLoader()
2422 return d->font_loader_;
2426 Toolbars const & GuiApplication::toolbars() const
2428 return d->toolbars_;
2432 Toolbars & GuiApplication::toolbars()
2434 return d->toolbars_;
2438 Menus const & GuiApplication::menus() const
2444 Menus & GuiApplication::menus()
2450 QList<int> GuiApplication::viewIds() const
2452 return d->views_.keys();
2456 ColorCache & GuiApplication::colorCache()
2458 return d->color_cache_;
2462 int GuiApplication::exec()
2464 // asynchronously handle batch commands. This event will be in
2465 // the event queue in front of other asynchronous events. Hence,
2466 // we can assume in the latter that the gui is setup already.
2467 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2469 return QApplication::exec();
2473 void GuiApplication::exit(int status)
2475 QApplication::exit(status);
2479 void GuiApplication::setGuiLanguage()
2483 // install translation file for Qt built-in dialogs
2484 QString const language_name = QString("qt_") + theLocale.name();
2485 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2486 // Short-named translator can be loaded from a long name, but not the
2487 // opposite. Therefore, long name should be used without truncation.
2488 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2489 if (!d->qt_trans_.load(language_name,
2490 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2491 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2494 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2498 switch (theLocale.language()) {
2499 case QLocale::Arabic :
2500 case QLocale::Hebrew :
2501 case QLocale::Persian :
2502 case QLocale::Urdu :
2503 setLayoutDirection(Qt::RightToLeft);
2506 setLayoutDirection(Qt::LeftToRight);
2511 void GuiApplication::execBatchCommands()
2516 if (!readUIFile(toqstr(lyxrc.ui_file)))
2517 // Gives some error box here.
2521 #if QT_VERSION > 0x040600
2522 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2524 #if QT_VERSION > 0x050100
2525 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2527 // Create the global default menubar which is shown for the dialogs
2528 // and if no GuiView is visible.
2529 // This must be done after the session was recovered to know the "last files".
2530 d->global_menubar_ = new QMenuBar(0);
2531 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2534 lyx::execBatchCommands();
2538 QAbstractItemModel * GuiApplication::languageModel()
2540 if (d->language_model_)
2541 return d->language_model_;
2543 QStandardItemModel * lang_model = new QStandardItemModel(this);
2544 lang_model->insertColumns(0, 3);
2545 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2546 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2547 Languages::const_iterator it = lyx::languages.begin();
2548 Languages::const_iterator end = lyx::languages.end();
2549 for (; it != end; ++it) {
2550 int current_row = lang_model->rowCount();
2551 lang_model->insertRows(current_row, 1);
2552 QModelIndex pl_item = lang_model->index(current_row, 0);
2553 QModelIndex sp_item = lang_model->index(current_row, 1);
2554 QModelIndex th_item = lang_model->index(current_row, 2);
2555 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2556 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2557 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2558 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2559 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2560 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2561 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2562 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2563 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2564 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2566 d->language_model_ = new QSortFilterProxyModel(this);
2567 d->language_model_->setSourceModel(lang_model);
2568 d->language_model_->setSortLocaleAware(true);
2569 return d->language_model_;
2573 void GuiApplication::restoreGuiSession()
2575 if (!lyxrc.load_session)
2578 Session & session = theSession();
2579 LastOpenedSection::LastOpened const & lastopened =
2580 session.lastOpened().getfiles();
2582 validateCurrentView();
2584 FileName active_file;
2585 // do not add to the lastfile list since these files are restored from
2586 // last session, and should be already there (regular files), or should
2587 // not be added at all (help files).
2588 for (size_t i = 0; i < lastopened.size(); ++i) {
2589 FileName const & file_name = lastopened[i].file_name;
2590 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2591 && current_view_->documentBufferView() != 0)) {
2592 boost::crc_32_type crc;
2593 string const & fname = file_name.absFileName();
2594 crc = for_each(fname.begin(), fname.end(), crc);
2595 createView(crc.checksum());
2597 current_view_->loadDocument(file_name, false);
2599 if (lastopened[i].active)
2600 active_file = file_name;
2603 // Restore last active buffer
2604 Buffer * buffer = theBufferList().getBuffer(active_file);
2605 if (buffer && current_view_)
2606 current_view_->setBuffer(buffer);
2608 // clear this list to save a few bytes of RAM
2609 session.lastOpened().clear();
2613 QString const GuiApplication::romanFontName()
2616 font.setStyleHint(QFont::Serif);
2617 font.setFamily("serif");
2619 return QFontInfo(font).family();
2623 QString const GuiApplication::sansFontName()
2626 font.setStyleHint(QFont::SansSerif);
2627 font.setFamily("sans");
2629 return QFontInfo(font).family();
2633 QString const GuiApplication::typewriterFontName()
2635 return QFontInfo(typewriterSystemFont()).family();
2640 // We cannot use QFont::fixedPitch() because it doesn't
2641 // return the fact but only if it is requested.
2642 static bool isFixedPitch(const QFont & font) {
2643 const QFontInfo fi(font);
2644 return fi.fixedPitch();
2649 QFont const GuiApplication::typewriterSystemFont()
2651 #if QT_VERSION >= 0x050200
2652 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2654 QFont font("monospace");
2656 if (!isFixedPitch(font)) {
2657 // try to enforce a real monospaced font
2658 font.setStyleHint(QFont::Monospace);
2659 if (!isFixedPitch(font)) {
2660 font.setStyleHint(QFont::TypeWriter);
2661 if (!isFixedPitch(font)) font.setFamily("courier");
2665 // On a Mac the result is too small and it's not practical to
2666 // rely on Qtconfig utility to change the system settings of Qt.
2667 font.setPointSize(12);
2673 void GuiApplication::handleRegularEvents()
2675 ForkedCallsController::handleCompletedProcesses();
2679 bool GuiApplication::event(QEvent * e)
2682 case QEvent::FileOpen: {
2683 // Open a file; this happens only on Mac OS X for now.
2685 // We do this asynchronously because on startup the batch
2686 // commands are not executed here yet and the gui is not ready
2688 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2689 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2690 processFuncRequestAsync(fr);
2695 return QApplication::event(e);
2700 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2703 return QApplication::notify(receiver, event);
2705 catch (ExceptionMessage const & e) {
2707 case ErrorException:
2709 setQuitOnLastWindowClosed(false);
2711 Alert::error(e.title_, e.details_);
2713 // Properly crash in debug mode in order to get a useful backtrace.
2716 // In release mode, try to exit gracefully.
2718 // FIXME: GCC 7 thinks we can fall through here. Can we?
2720 case BufferException: {
2721 if (!current_view_ || !current_view_->documentBufferView())
2723 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2724 docstring details = e.details_ + '\n';
2725 details += buf->emergencyWrite();
2726 theBufferList().release(buf);
2727 details += "\n" + _("The current document was closed.");
2728 Alert::error(e.title_, details);
2731 case WarningException:
2732 Alert::warning(e.title_, e.details_);
2736 catch (exception const & e) {
2737 docstring s = _("LyX has caught an exception, it will now "
2738 "attempt to save all unsaved documents and exit."
2740 s += from_ascii(e.what());
2741 Alert::error(_("Software exception Detected"), s);
2745 docstring s = _("LyX has caught some really weird exception, it will "
2746 "now attempt to save all unsaved documents and exit.");
2747 Alert::error(_("Software exception Detected"), s);
2755 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2757 QColor const & qcol = d->color_cache_.get(col);
2758 if (!qcol.isValid()) {
2764 rgbcol.r = qcol.red();
2765 rgbcol.g = qcol.green();
2766 rgbcol.b = qcol.blue();
2771 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2773 QColor const qcol(lcolor.getX11Name(col).c_str());
2774 if (!qcol.isValid()) {
2780 rgbcol.r = qcol.red();
2781 rgbcol.g = qcol.green();
2782 rgbcol.b = qcol.blue();
2787 string const GuiApplication::hexName(ColorCode col)
2789 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2793 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2795 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2796 d->socket_notifiers_[fd] = sn;
2797 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2801 void GuiApplication::socketDataReceived(int fd)
2803 d->socket_notifiers_[fd]->func_();
2807 void GuiApplication::unregisterSocketCallback(int fd)
2809 d->socket_notifiers_.take(fd)->setEnabled(false);
2813 void GuiApplication::commitData(QSessionManager & sm)
2815 /** The implementation is required to avoid an application exit
2816 ** when session state save is triggered by session manager.
2817 ** The default implementation sends a close event to all
2818 ** visible top level widgets when session managment allows
2820 ** We are changing that to check the state of each buffer in all
2821 ** views and ask the users what to do if buffers are dirty.
2822 ** Furthermore, we save the session state.
2823 ** We do NOT close the views here since the user still can cancel
2824 ** the logout process (see #9277); also, this would hide LyX from
2825 ** an OSes own session handling (application restoration).
2827 #ifdef QT_NO_SESSIONMANAGER
2829 #warning Qt is compiled without session manager
2831 #pragma message("warning: Qt is compiled without session manager")
2835 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2843 void GuiApplication::unregisterView(GuiView * gv)
2845 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2846 d->views_.remove(gv->id());
2847 if (current_view_ == gv)
2853 bool GuiApplication::closeAllViews()
2855 if (d->views_.empty())
2858 // When a view/window was closed before without quitting LyX, there
2859 // are already entries in the lastOpened list.
2860 theSession().lastOpened().clear();
2862 QList<GuiView *> const views = d->views_.values();
2863 for (GuiView * view : views) {
2864 if (!view->closeScheduled())
2873 bool GuiApplication::prepareAllViewsForLogout()
2875 if (d->views_.empty())
2878 QList<GuiView *> const views = d->views_.values();
2879 for (GuiView * view : views) {
2880 if (!view->prepareAllBuffersForLogout())
2888 GuiView & GuiApplication::view(int id) const
2890 LAPPERR(d->views_.contains(id));
2891 return *d->views_.value(id);
2895 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2897 QList<GuiView *> const views = d->views_.values();
2898 for (GuiView * view : views)
2899 view->hideDialog(name, inset);
2903 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2905 Buffer const * buffer_ = 0;
2906 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2907 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2908 if (Buffer const * ptr = (*it)->updateInset(inset))
2915 bool GuiApplication::searchMenu(FuncRequest const & func,
2916 docstring_list & names) const
2918 return d->menus_.searchMenu(func, names);
2922 // Ensure that a file is read only once (prevents include loops)
2923 static QStringList uifiles;
2924 // store which ui files define Toolbars
2925 static QStringList toolbar_uifiles;
2928 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2939 LexerKeyword uitags[] = {
2940 { "format", ui_format },
2941 { "include", ui_include },
2942 { "menuset", ui_menuset },
2943 { "toolbars", ui_toolbars },
2944 { "toolbarset", ui_toolbarset }
2948 lex.setFile(ui_path);
2950 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2954 if (lyxerr.debugging(Debug::PARSER))
2955 lex.printTable(lyxerr);
2958 // format before introduction of format tag
2959 unsigned int format = 0;
2960 while (lex.isOK()) {
2961 int const status = lex.lex();
2963 // we have to do this check here, outside the switch,
2964 // because otherwise we would start reading include files,
2965 // e.g., if the first tag we hit was an include tag.
2966 if (status == ui_format)
2968 format = lex.getInteger();
2972 // this will trigger unless the first tag we hit is a format
2973 // tag, with the right format.
2974 if (format != LFUN_FORMAT)
2975 return FormatMismatch;
2978 case Lexer::LEX_FEOF:
2983 QString const file = toqstr(lex.getString());
2984 bool const success = readUIFile(file, true);
2986 LYXERR0("Failed to read included file: " << fromqstr(file));
2993 d->menus_.read(lex);
2997 d->toolbars_.readToolbars(lex);
3001 d->toolbars_.readToolbarSettings(lex);
3002 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3006 if (!rtrim(lex.getString()).empty())
3007 lex.printError("LyX::ReadUIFile: "
3008 "Unknown menu tag: `$$Token'");
3010 LYXERR0("Error with status: " << status);
3016 return (error ? ReadError : ReadOK);
3020 bool GuiApplication::readUIFile(QString const & name, bool include)
3022 LYXERR(Debug::INIT, "About to read " << name << "...");
3026 ui_path = libFileSearch("ui", name, "inc");
3027 if (ui_path.empty())
3028 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3030 ui_path = libFileSearch("ui", name, "ui");
3033 if (ui_path.empty()) {
3034 static const QString defaultUIFile = "default";
3035 LYXERR(Debug::INIT, "Could not find " << name);
3037 Alert::warning(_("Could not find UI definition file"),
3038 bformat(_("Error while reading the included file\n%1$s\n"
3039 "Please check your installation."), qstring_to_ucs4(name)));
3042 if (name == defaultUIFile) {
3043 LYXERR(Debug::INIT, "Could not find default UI file!!");
3044 Alert::warning(_("Could not find default UI file"),
3045 _("LyX could not find the default UI file!\n"
3046 "Please check your installation."));
3049 Alert::warning(_("Could not find UI definition file"),
3050 bformat(_("Error while reading the configuration file\n%1$s\n"
3051 "Falling back to default.\n"
3052 "Please look under Tools>Preferences>User Interface and\n"
3053 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3054 return readUIFile(defaultUIFile, false);
3057 QString const uifile = toqstr(ui_path.absFileName());
3058 if (uifiles.contains(uifile)) {
3060 // We are reading again the top uifile so reset the safeguard:
3063 d->toolbars_.reset();
3065 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3066 << "Is this an include loop?");
3070 uifiles.push_back(uifile);
3072 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3074 ReturnValues retval = readUIFile(ui_path);
3076 if (retval == FormatMismatch) {
3077 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3078 TempFile tmp("convertXXXXXX.ui");
3079 FileName const tempfile = tmp.name();
3080 bool const success = prefs2prefs(ui_path, tempfile, true);
3082 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3083 " to format " << LFUN_FORMAT << ".");
3085 retval = readUIFile(tempfile);
3089 if (retval != ReadOK) {
3090 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3098 settings.beginGroup("ui_files");
3099 bool touched = false;
3100 for (int i = 0; i != uifiles.size(); ++i) {
3101 QFileInfo fi(uifiles[i]);
3102 QDateTime const date_value = fi.lastModified();
3103 QString const name_key = QString::number(i);
3104 // if an ui file which defines Toolbars has changed,
3105 // we have to reset the settings
3106 if (toolbar_uifiles.contains(uifiles[i])
3107 && (!settings.contains(name_key)
3108 || settings.value(name_key).toString() != uifiles[i]
3109 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3111 settings.setValue(name_key, uifiles[i]);
3112 settings.setValue(name_key + "/date", date_value);
3115 settings.endGroup();
3117 settings.remove("views");
3123 void GuiApplication::onLastWindowClosed()
3125 if (d->global_menubar_)
3126 d->global_menubar_->grabKeyboard();
3130 void GuiApplication::startLongOperation() {
3131 d->key_checker_.start();
3135 bool GuiApplication::longOperationCancelled() {
3136 return d->key_checker_.pressed();
3140 void GuiApplication::stopLongOperation() {
3141 d->key_checker_.stop();
3145 bool GuiApplication::longOperationStarted() {
3146 return d->key_checker_.started();
3150 ////////////////////////////////////////////////////////////////////////
3152 // X11 specific stuff goes here...
3155 bool GuiApplication::x11EventFilter(XEvent * xev)
3160 switch (xev->type) {
3161 case SelectionRequest: {
3162 if (xev->xselectionrequest.selection != XA_PRIMARY)
3164 LYXERR(Debug::SELECTION, "X requested selection.");
3165 BufferView * bv = current_view_->currentBufferView();
3167 docstring const sel = bv->requestSelection();
3169 d->selection_.put(sel);
3170 // Refresh the selection request timestamp.
3171 // We have to do this by ourselves as Qt seems
3172 // not doing that, maybe because of our
3173 // "persistent selection" implementation
3174 // (see comments in GuiSelection.cpp).
3175 XSelectionEvent nev;
3176 nev.type = SelectionNotify;
3177 nev.display = xev->xselectionrequest.display;
3178 nev.requestor = xev->xselectionrequest.requestor;
3179 nev.selection = xev->xselectionrequest.selection;
3180 nev.target = xev->xselectionrequest.target;
3181 nev.property = 0L; // None
3182 nev.time = CurrentTime;
3183 XSendEvent(QX11Info::display(),
3184 nev.requestor, False, 0,
3185 reinterpret_cast<XEvent *>(&nev));
3191 case SelectionClear: {
3192 if (xev->xselectionclear.selection != XA_PRIMARY)
3194 LYXERR(Debug::SELECTION, "Lost selection.");
3195 BufferView * bv = current_view_->currentBufferView();
3197 bv->clearSelection();
3203 #elif defined(QPA_XCB)
3204 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3205 void * message, long *)
3207 if (!current_view_ || eventType != "xcb_generic_event_t")
3210 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3212 switch (ev->response_type) {
3213 case XCB_SELECTION_REQUEST: {
3214 xcb_selection_request_event_t * srev =
3215 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3216 if (srev->selection != XCB_ATOM_PRIMARY)
3218 LYXERR(Debug::SELECTION, "X requested selection.");
3219 BufferView * bv = current_view_->currentBufferView();
3221 docstring const sel = bv->requestSelection();
3223 d->selection_.put(sel);
3224 #ifdef HAVE_QT5_X11_EXTRAS
3225 // Refresh the selection request timestamp.
3226 // We have to do this by ourselves as Qt seems
3227 // not doing that, maybe because of our
3228 // "persistent selection" implementation
3229 // (see comments in GuiSelection.cpp).
3230 xcb_selection_notify_event_t nev;
3231 nev.response_type = XCB_SELECTION_NOTIFY;
3232 nev.requestor = srev->requestor;
3233 nev.selection = srev->selection;
3234 nev.target = srev->target;
3235 nev.property = XCB_NONE;
3236 nev.time = XCB_CURRENT_TIME;
3237 xcb_connection_t * con = QX11Info::connection();
3238 xcb_send_event(con, 0, srev->requestor,
3239 XCB_EVENT_MASK_NO_EVENT,
3240 reinterpret_cast<char const *>(&nev));
3248 case XCB_SELECTION_CLEAR: {
3249 xcb_selection_clear_event_t * scev =
3250 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3251 if (scev->selection != XCB_ATOM_PRIMARY)
3253 LYXERR(Debug::SELECTION, "Lost selection.");
3254 BufferView * bv = current_view_->currentBufferView();
3256 bv->clearSelection();
3264 } // namespace frontend
3267 void hideDialogs(std::string const & name, Inset * inset)
3270 frontend::guiApp->hideDialogs(name, inset);
3274 ////////////////////////////////////////////////////////////////////
3278 ////////////////////////////////////////////////////////////////////
3280 frontend::FontLoader & theFontLoader()
3282 LAPPERR(frontend::guiApp);
3283 return frontend::guiApp->fontLoader();
3287 frontend::FontMetrics const & theFontMetrics(Font const & f)
3289 return theFontMetrics(f.fontInfo());
3293 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3295 LAPPERR(frontend::guiApp);
3296 return frontend::guiApp->fontLoader().metrics(f);
3300 ////////////////////////////////////////////////////////////////////
3304 ////////////////////////////////////////////////////////////////////
3306 frontend::Clipboard & theClipboard()
3308 LAPPERR(frontend::guiApp);
3309 return frontend::guiApp->clipboard();
3313 frontend::Selection & theSelection()
3315 LAPPERR(frontend::guiApp);
3316 return frontend::guiApp->selection();
3322 #include "moc_GuiApplication.cpp"