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)
130 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
131 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
132 #if (QT_VERSION < 0x050000)
133 #include <QWindowsMime>
134 #define QWINDOWSMIME QWindowsMime
137 #define QWINDOWSMIME QWinMime
147 #include <QMacPasteboardMime>
150 #include <boost/crc.hpp>
157 using namespace lyx::support;
160 static void initializeResources()
162 static bool initialized = false;
164 Q_INIT_RESOURCE(Resources);
172 frontend::Application * createApplication(int & argc, char * argv[])
174 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
175 // prune -geometry argument(s) by shifting
176 // the following ones 2 places down.
177 for (int i = 0 ; i < argc ; ++i) {
178 if (strcmp(argv[i], "-geometry") == 0) {
179 int const remove = (i+1) < argc ? 2 : 1;
181 for (int j = i; j < argc; ++j)
182 argv[j] = argv[j + remove];
187 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
188 // I'd rather do that in the constructor, but I do not think that
189 // the palette is accessible there.
190 guiApp->colorCache().setPalette(guiApp->palette());
199 if (lyxrc.gui_language == "auto") {
200 theLocale = QLocale::system();
201 code = fromqstr(theLocale.name());
203 Language const * l = languages.getLanguage(lyxrc.gui_language);
204 code = l ? l->code() : "C";
205 theLocale = QLocale(toqstr(code));
207 // Qt tries to outsmart us and transforms en_US to C.
208 Messages::guiLanguage((code == "C") ? "en_US" : code);
209 QLocale::setDefault(theLocale);
210 setlocale(LC_NUMERIC, "C");
217 /// Return the list of loadable formats.
218 vector<string> loadableImageFormats()
222 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
224 LYXERR(Debug::GRAPHICS,
225 "\nThe image loader can load the following directly:\n");
227 if (qt_formats.empty())
228 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
230 bool jpeg_found = false;
231 bool jpg_found = false;
232 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
234 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
236 string ext = ascii_lowercase((const char *) *it);
244 else if (ext == "jpg") {
249 else if (lyxrc.use_converter_cache &&
250 (ext == "svg" || ext == "svgz") &&
251 theConverters().isReachable("svg", "png"))
252 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
253 // the SVG as in the output. However we require that the converter
254 // cache is enabled since this is expensive. We also require that
255 // an explicit svg->png converter is defined, since the default
256 // converter could produce bad quality as well. This assumes that
257 // png can always be loaded.
266 ////////////////////////////////////////////////////////////////////////
268 // Icon loading support code
270 ////////////////////////////////////////////////////////////////////////
280 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
282 return lhs.key < rhs.key;
288 CompareKey(QString const & name) : name_(name) {}
289 bool operator()(ImgMap const & other) const { return other.key == name_; }
295 // this must be sorted alphabetically
296 // Upper case comes before lower case
297 // Please don't change the formatting, this list is parsed by
298 // development/tools/generate_symbols_images.py.
299 ImgMap sorted_img_map[] = {
300 { "Arrownot", "arrownot2"},
301 { "Arrowvert", "arrowvert2"},
302 { "Bowtie", "bowtie2" },
304 { "Bumpeq", "bumpeq2" },
305 { "CIRCLE", "circle3" },
307 { "CheckedBox", "checkedbox2" },
308 { "Circle", "circle2" },
309 { "Colonapprox", "colonapprox2" },
310 { "Coloneq", "coloneq2" },
311 { "Coloneqq", "coloneqq2" },
312 { "Colonsim", "colonsim2" },
314 { "DOWNarrow", "downarrow3" },
315 { "Delta", "delta2" },
316 { "Diamond", "diamond2" },
317 { "Doteq", "doteq2" },
318 { "Downarrow", "downarrow2" },
319 { "Eqcolon", "eqcolon2" },
320 { "Eqqcolon", "eqqcolon2" },
321 { "Gamma", "gamma2" },
323 { "LEFTCIRCLE", "leftcircle3" },
324 { "LEFTarrow", "leftarrow3" },
325 { "LEFTcircle", "leftcircle4" },
327 { "Lambda", "lambda2" },
329 { "Leftarrow", "leftarrow2" },
330 { "Leftcircle", "leftcircle2" },
331 { "Leftrightarrow", "leftrightarrow2" },
332 { "Longarrownot", "longarrownot2"},
333 { "Longleftarrow", "longleftarrow2" },
334 { "Longleftrightarrow", "longleftrightarrow2" },
335 { "Longmapsfrom", "longmapsfrom2"},
336 { "Longmapsto", "longmapsto2"},
337 { "Longrightarrow", "longrightarrow2" },
338 { "Mapsfrom", "mapsfrom2"},
339 { "Mapsfromchar", "mapsfromchar2"},
340 { "Mapsto", "mapsto2"},
341 { "Mapstochar", "mapstochar2"},
342 { "Omega", "omega2" },
347 { "RIGHTCIRCLE", "rightcircle3" },
348 { "RIGHTarrow", "rightarrow3" },
349 { "RIGHTcircle", "rightcircle4" },
351 { "Rightarrow", "rightarrow2" },
352 { "Rightcircle", "rightcircle2" },
353 { "Sigma", "sigma2" },
354 { "Square", "square2" },
355 { "Subset", "subset2" },
356 { "Supset", "supset2" },
357 { "Theta", "theta2" },
358 { "Thorn", "thorn2" },
359 { "UParrow", "uparrow3" },
360 { "Uparrow", "uparrow2" },
361 { "Updownarrow", "updownarrow2" },
362 { "Upsilon", "upsilon2" },
363 { "Vdash", "vdash3" },
368 { "lVert", "vert2" },
370 { "nLeftarrow", "nleftarrow2" },
371 { "nLeftrightarrow", "nleftrightarrow2" },
372 { "nRightarrow", "nrightarrow2" },
373 { "nVDash", "nvdash3" },
374 { "nVdash", "nvdash4" },
375 { "nvDash", "nvdash2" },
376 { "rVert", "vert2" },
378 { "textrm \\AA", "textrm_AA"},
379 { "textrm \\O", "textrm_O"},
380 { "vDash", "vdash2" },
381 { "varDelta", "vardelta2" },
382 { "varGamma", "vargamma2" },
383 { "varLambda", "varlambda2" },
384 { "varOmega", "varomega2" },
385 { "varPhi", "varphi2" },
386 { "varPi", "varpi2" },
387 { "varPsi", "varpsi2" },
388 { "varSigma", "varsigma2" },
389 { "varTheta", "vartheta2" },
390 { "varUpsilon", "varupsilon2" },
391 { "varXi", "varxi2" }
395 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
397 // This list specifies which system's theme icon is related to which lyx
398 // command. It was based on:
399 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
400 // this must be sorted alphabetically
401 // Upper case comes before lower case
402 ImgMap sorted_theme_icon_map[] = {
403 { "bookmark-goto 0", "go-jump" },
404 { "buffer-new", "document-new" },
405 { "buffer-write", "document-save" },
406 { "buffer-write-as", "document-save-as" },
407 { "buffer-zoom-in", "zoom-in" },
408 { "buffer-zoom-out", "zoom-out" },
409 { "copy", "edit-copy" },
410 { "cut", "edit-cut" },
411 { "depth-decrement", "format-indent-less" },
412 { "depth-increment", "format-indent-more" },
413 { "dialog-show spellchecker", "tools-check-spelling" },
414 { "dialog-show-new-inset graphics", "insert-image" },
415 { "dialog-toggle findreplaceadv", "edit-find-replace" },
416 { "file-open", "document-open" },
417 { "font-bold", "format-text-bold" },
418 { "font-ital", "format-text-italic" },
419 { "font-strikeout", "format-text-strikethrough" },
420 { "font-underline", "format-text-underline" },
421 { "lyx-quit", "application-exit" },
422 { "paste", "edit-paste" },
423 { "redo", "edit-redo" },
424 { "undo", "edit-undo" },
425 { "window-close", "window-close" },
426 { "window-new", "window-new" }
429 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
432 QString findImg(QString const & name)
434 ImgMap const * const begin = sorted_img_map;
435 ImgMap const * const end = begin + nr_sorted_img_map;
436 LATTEST(sorted(begin, end));
438 ImgMap const * const it = find_if(begin, end, CompareKey(name));
442 img_name = it->value;
445 img_name.replace('_', "underscore");
446 img_name.replace(' ', '_');
448 // This way we can have "math-delim { }" on the toolbar.
449 img_name.replace('(', "lparen");
450 img_name.replace(')', "rparen");
451 img_name.replace('[', "lbracket");
452 img_name.replace(']', "rbracket");
453 img_name.replace('{', "lbrace");
454 img_name.replace('}', "rbrace");
455 img_name.replace('|', "bars");
456 img_name.replace(',', "thinspace");
457 img_name.replace(':', "mediumspace");
458 img_name.replace(';', "thickspace");
459 img_name.replace('!', "negthinspace");
462 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
463 << "Looking for math icon called \"" << img_name << '"');
470 QString themeIconName(QString const & action)
472 ImgMap const * const begin = sorted_theme_icon_map;
473 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
474 LASSERT(sorted(begin, end), /**/);
476 ImgMap const * const it = find_if(begin, end, CompareKey(action));
484 QString iconName(FuncRequest const & f, bool unknown)
486 initializeResources();
490 switch (f.action()) {
491 case LFUN_MATH_INSERT:
492 if (!f.argument().empty()) {
494 name1 = findImg(toqstr(f.argument()).mid(1));
497 case LFUN_MATH_DELIM:
498 case LFUN_MATH_BIGDELIM:
500 name1 = findImg(toqstr(f.argument()));
504 name1 = toqstr(f.argument());
506 case LFUN_COMMAND_ALTERNATIVES: {
507 // use the first of the alternative commands
509 docstring dummy = split(f.argument(), firstcom, ';');
510 name1 = toqstr(firstcom);
511 name1.replace(' ', '_');
515 name2 = toqstr(lyxaction.getActionName(f.action()));
518 if (!f.argument().empty()) {
519 name1 = name2 + ' ' + toqstr(f.argument());
520 name1.replace(' ', '_');
521 name1.replace('\\', "backslash");
525 QStringList imagedirs;
526 imagedirs << "images/" << "images/ipa/";
527 search_mode mode = theGuiApp()->imageSearchMode();
528 for (int i = 0; i < imagedirs.size(); ++i) {
529 QString imagedir = imagedirs.at(i) + path;
530 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
532 return toqstr(fname.absFileName());
534 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
536 return toqstr(fname.absFileName());
539 path = ":/images/" + path;
542 LYXERR0("Directory " << path << " not found in resource!");
545 if (res.exists(name1 + ".svgz"))
546 return path + name1 + ".svgz";
547 else if (res.exists(name1 + ".png"))
548 return path + name1 + ".png";
550 if (res.exists(name2 + ".svgz"))
551 return path + name2 + ".svgz";
552 else if (res.exists(name2 + ".png"))
553 return path + name2 + ".png";
555 LYXERR(Debug::GUI, "Cannot find icon with filename "
556 << "\"" << name1 << ".{svgz,png}\""
558 << "\"" << name2 << ".{svgz,png}\""
560 << lyxaction.getActionName(f.action())
561 << '(' << to_utf8(f.argument()) << ")\"");
564 QString imagedir = "images/";
565 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
567 return toqstr(fname.absFileName());
568 return QString(":/images/unknown.svgz");
575 bool getPixmap(QPixmap & pixmap, QString const & path)
577 return pixmap.load(path);
581 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
583 QString imagedir = path;
584 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
585 QString fpath = toqstr(fname.absFileName());
586 QPixmap pixmap = QPixmap();
588 if (getPixmap(pixmap, fpath)) {
592 QStringList exts = ext.split(",");
593 fpath = ":/" + path + name + ".";
594 for (int i = 0; i < exts.size(); ++i) {
595 if (getPixmap(pixmap, fpath + exts.at(i))) {
600 bool const list = ext.contains(",");
601 LYXERR0("Cannot load pixmap \""
602 << path << name << "." << (list ? "{" : "") << ext
603 << (list ? "}" : "") << "\", please verify resource system!");
609 QIcon getIcon(FuncRequest const & f, bool unknown)
611 #if (QT_VERSION >= 0x040600)
612 if (lyxrc.use_system_theme_icons) {
613 // use the icons from system theme that are available
614 QString action = toqstr(lyxaction.getActionName(f.action()));
615 if (!f.argument().empty())
616 action += " " + toqstr(f.argument());
617 QString const theme_icon = themeIconName(action);
618 if (QIcon::hasThemeIcon(theme_icon)) {
619 QIcon const thmicn = QIcon::fromTheme(theme_icon);
620 if (!thmicn.isNull())
626 QString icon = iconName(f, unknown);
630 //LYXERR(Debug::GUI, "Found icon: " << icon);
631 QPixmap pixmap = QPixmap();
632 if (!getPixmap(pixmap,icon)) {
633 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
637 return QIcon(pixmap);
641 ////////////////////////////////////////////////////////////////////////
643 // LyX server support code.
645 ////////////////////////////////////////////////////////////////////////
647 class SocketNotifier : public QSocketNotifier
650 /// connect a connection notification from the LyXServerSocket
651 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
652 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
656 /// The callback function
657 Application::SocketCallback func_;
661 ////////////////////////////////////////////////////////////////////////
663 // Mac specific stuff goes here...
665 ////////////////////////////////////////////////////////////////////////
667 class MenuTranslator : public QTranslator
670 MenuTranslator(QObject * parent)
671 : QTranslator(parent)
674 #if QT_VERSION >= 0x050000
675 virtual QString translate(const char * /* context */,
676 const char *sourceText,
677 const char * /* disambiguation */ = 0, int /* n */ = -1) const
679 QString translate(const char * /*context*/,
680 const char * sourceText,
681 const char * /*comment*/ = 0) const
684 string const s = sourceText;
685 if (s == N_("About %1") || s == N_("Preferences")
686 || s == N_("Reconfigure") || s == N_("Quit %1"))
694 // QMacPasteboardMimeGraphics can only be compiled on Mac.
696 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
699 QMacPasteboardMimeGraphics()
700 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
703 QString convertorName() { return "Graphics"; }
705 QString flavorFor(QString const & mime)
707 LYXERR(Debug::ACTION, "flavorFor " << mime);
708 if (mime == pdfMimeType())
709 return QLatin1String("com.adobe.pdf");
713 QString mimeFor(QString flav)
715 LYXERR(Debug::ACTION, "mimeFor " << flav);
716 if (flav == QLatin1String("com.adobe.pdf"))
717 return pdfMimeType();
721 bool canConvert(QString const & mime, QString flav)
723 return mimeFor(flav) == mime;
726 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
730 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
734 QList<QByteArray> convertFromMime(QString const & /*mime*/,
735 QVariant data, QString /*flav*/)
737 QList<QByteArray> ret;
738 ret.append(data.toByteArray());
744 ///////////////////////////////////////////////////////////////
746 // You can find more platform specific stuff at the end of this file...
748 ///////////////////////////////////////////////////////////////
750 ////////////////////////////////////////////////////////////////////////
751 // Windows specific stuff goes here...
753 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
754 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
755 // QWindowsMimeMetafile can only be compiled on Windows.
757 static FORMATETC cfFromMime(QString const & mimetype)
760 if (mimetype == emfMimeType()) {
761 formatetc.cfFormat = CF_ENHMETAFILE;
762 formatetc.tymed = TYMED_ENHMF;
763 } else if (mimetype == wmfMimeType()) {
764 formatetc.cfFormat = CF_METAFILEPICT;
765 formatetc.tymed = TYMED_MFPICT;
768 formatetc.dwAspect = DVASPECT_CONTENT;
769 formatetc.lindex = -1;
774 class QWindowsMimeMetafile : public QWINDOWSMIME {
776 QWindowsMimeMetafile() {}
778 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
779 QMimeData const * /*mimedata*/) const
784 bool canConvertToMime(QString const & mimetype,
785 IDataObject * pDataObj) const
787 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
789 FORMATETC formatetc = cfFromMime(mimetype);
790 return pDataObj->QueryGetData(&formatetc) == S_OK;
793 bool convertFromMime(FORMATETC const & /*formatetc*/,
794 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
799 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
800 QVariant::Type /*preferredType*/) const
803 if (!canConvertToMime(mimetype, pDataObj))
806 FORMATETC formatetc = cfFromMime(mimetype);
808 if (pDataObj->GetData(&formatetc, &s) != S_OK)
812 if (s.tymed == TYMED_ENHMF) {
813 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
814 data.resize(dataSize);
815 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
816 (LPBYTE)data.data());
817 } else if (s.tymed == TYMED_MFPICT) {
818 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
819 data.resize(dataSize);
820 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
821 (LPBYTE)data.data());
824 ReleaseStgMedium(&s);
830 QVector<FORMATETC> formatsForMime(QString const & mimetype,
831 QMimeData const * /*mimedata*/) const
833 QVector<FORMATETC> formats;
834 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
835 formats += cfFromMime(mimetype);
839 QString mimeForFormat(FORMATETC const & formatetc) const
841 switch (formatetc.cfFormat) {
843 return emfMimeType();
844 case CF_METAFILEPICT:
845 return wmfMimeType();
855 /// Allows to check whether ESC was pressed during a long operation
856 class KeyChecker : public QObject {
861 KeyChecker() : pressed_(false), started_(false) {}
864 QCoreApplication::instance()->installEventFilter(this);
869 QCoreApplication::instance()->removeEventFilter(this);
873 QCoreApplication::processEvents();
876 bool started() const {
879 bool eventFilter(QObject *obj, QEvent *event) {
880 LYXERR(Debug::ACTION, "Event Type: " << event->type());
881 switch (event->type()) {
885 case QEvent::UpdateRequest:
886 case QEvent::CursorChange:
887 case QEvent::ActionChanged:
888 case QEvent::EnabledChange:
889 case QEvent::SockAct:
892 case QEvent::ToolTipChange:
893 case QEvent::LayoutRequest:
894 case QEvent::MetaCall:
895 return QObject::eventFilter(obj, event);
897 // FIXME Blocking all these events is a bad idea.
898 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
899 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
907 ////////////////////////////////////////////////////////////////////////
908 // GuiApplication::Private definition and implementation.
909 ////////////////////////////////////////////////////////////////////////
911 struct GuiApplication::Private
913 Private(): language_model_(0), meta_fake_bit(NoModifier),
916 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
917 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
918 /// WMF Mime handler for Windows clipboard.
919 wmf_mime_ = new QWindowsMimeMetafile;
922 initKeySequences(&theTopLevelKeymap());
925 void initKeySequences(KeyMap * kb)
927 keyseq = KeySequence(kb, kb);
928 cancel_meta_seq = KeySequence(kb, kb);
932 QSortFilterProxyModel * language_model_;
934 GuiClipboard clipboard_;
936 GuiSelection selection_;
938 FontLoader font_loader_;
940 ColorCache color_cache_;
942 QTranslator qt_trans_;
944 QHash<int, SocketNotifier *> socket_notifiers_;
948 /// The global instance
951 /// this timer is used for any regular events one wants to
952 /// perform. at present it is used to check if forked processes
954 QTimer general_timer_;
956 /// delayed FuncRequests
957 std::queue<FuncRequest> func_request_queue_;
962 KeySequence cancel_meta_seq;
964 KeyModifier meta_fake_bit;
966 /// The result of last dispatch action
967 DispatchResult dispatch_result_;
969 /// Multiple views container.
971 * Warning: This must not be a smart pointer as the destruction of the
972 * object is handled by Qt when the view is closed
973 * \sa Qt::WA_DeleteOnClose attribute.
975 QHash<int, GuiView *> views_;
977 /// Only used on mac.
978 QMenuBar * global_menubar_;
981 /// Linkback mime handler for MacOSX.
982 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
985 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
986 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
987 /// WMF Mime handler for Windows clipboard.
988 QWindowsMimeMetafile * wmf_mime_;
992 /// Allows to check whether ESC was pressed during a long operation
993 KeyChecker key_checker_;
997 GuiApplication * guiApp;
999 GuiApplication::~GuiApplication()
1002 closeAllLinkBackLinks();
1008 GuiApplication::GuiApplication(int & argc, char ** argv)
1009 : QApplication(argc, argv), current_view_(0),
1010 d(new GuiApplication::Private)
1012 QString app_name = "LyX";
1013 QCoreApplication::setOrganizationName(app_name);
1014 QCoreApplication::setOrganizationDomain("lyx.org");
1015 QCoreApplication::setApplicationName(lyx_package);
1017 qsrand(QDateTime::currentDateTime().toTime_t());
1019 // Install translator for GUI elements.
1020 installTranslator(&d->qt_trans_);
1023 // Enable reception of XCB events.
1024 installNativeEventFilter(this);
1027 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1028 // lyxrc setting for this in order to let the application stay resident.
1029 // But then we need some kind of dock icon, at least on Windows.
1031 if (lyxrc.quit_on_last_window_closed)
1032 setQuitOnLastWindowClosed(false);
1035 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1036 // seems to be the default case for applications like LyX.
1037 setQuitOnLastWindowClosed(false);
1038 // This allows to translate the strings that appear in the LyX menu.
1039 /// A translator suitable for the entries in the LyX menu.
1040 /// Only needed with Qt/Mac.
1041 installTranslator(new MenuTranslator(this));
1046 #if defined(Q_WS_X11) || defined(QPA_XCB)
1047 // doubleClickInterval() is 400 ms on X11 which is just too long.
1048 // On Windows and Mac OS X, the operating system's value is used.
1049 // On Microsoft Windows, calling this function sets the double
1050 // click interval for all applications. So we don't!
1051 QApplication::setDoubleClickInterval(300);
1054 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1056 // needs to be done before reading lyxrc
1058 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1062 // Set the cache to 5120 kilobytes which corresponds to screen size of
1063 // 1280 by 1024 pixels with a color depth of 32 bits.
1064 QPixmapCache::setCacheLimit(5120);
1066 // Initialize RC Fonts
1067 if (lyxrc.roman_font_name.empty())
1068 lyxrc.roman_font_name = fromqstr(romanFontName());
1070 if (lyxrc.sans_font_name.empty())
1071 lyxrc.sans_font_name = fromqstr(sansFontName());
1073 if (lyxrc.typewriter_font_name.empty())
1074 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1076 d->general_timer_.setInterval(500);
1077 connect(&d->general_timer_, SIGNAL(timeout()),
1078 this, SLOT(handleRegularEvents()));
1079 d->general_timer_.start();
1081 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1082 // This is clearly not enough in a time where we use threads for
1083 // document preview and/or export. 20 should be OK.
1084 QThreadPool::globalInstance()->setMaxThreadCount(20);
1086 // make sure tooltips are formatted
1087 installEventFilter(new ToolTipFormatter(this));
1091 GuiApplication * theGuiApp()
1093 return dynamic_cast<GuiApplication *>(theApp());
1097 double GuiApplication::pixelRatio() const
1099 #if QT_VERSION >= 0x050000
1100 return devicePixelRatio();
1107 void GuiApplication::clearSession()
1114 docstring Application::iconName(FuncRequest const & f, bool unknown)
1116 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1120 docstring Application::mathIcon(docstring const & c)
1122 return qstring_to_ucs4(findImg(toqstr(c)));
1126 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1130 BufferView * bv = 0;
1131 BufferView * doc_bv = 0;
1133 if (cmd.action() == LFUN_NOACTION) {
1134 status.message(from_utf8(N_("Nothing to do")));
1135 status.setEnabled(false);
1138 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1139 status.setUnknown(true);
1140 status.message(from_utf8(N_("Unknown action")));
1141 status.setEnabled(false);
1144 // Does the GuiApplication know something?
1145 else if (getStatus(cmd, status)) { }
1147 // If we do not have a GuiView, then other functions are disabled
1148 else if (!current_view_)
1149 status.setEnabled(false);
1151 // Does the GuiView know something?
1152 else if (current_view_->getStatus(cmd, status)) { }
1154 // In LyX/Mac, when a dialog is open, the menus of the
1155 // application can still be accessed without giving focus to
1156 // the main window. In this case, we want to disable the menu
1157 // entries that are buffer or view-related.
1158 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1160 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1161 status.setEnabled(false);
1164 // If we do not have a BufferView, then other functions are disabled
1165 else if (!(bv = current_view_->currentBufferView()))
1166 status.setEnabled(false);
1168 // Does the current BufferView know something?
1169 else if (bv->getStatus(cmd, status)) { }
1171 // Does the current Buffer know something?
1172 else if (bv->buffer().getStatus(cmd, status)) { }
1174 // If we do not have a document BufferView, different from the
1175 // current BufferView, then other functions are disabled
1176 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1177 status.setEnabled(false);
1179 // Does the document Buffer know something?
1180 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1183 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1184 status.message(from_utf8(N_("Command not handled")));
1185 status.setEnabled(false);
1188 // the default error message if we disable the command
1189 if (!status.enabled() && status.message().empty())
1190 status.message(from_utf8(N_("Command disabled")));
1196 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1198 // I would really like to avoid having this switch and rather try to
1199 // encode this in the function itself.
1200 // -- And I'd rather let an inset decide which LFUNs it is willing
1201 // to handle (Andre')
1203 switch (cmd.action()) {
1205 // This could be used for the no-GUI version. The GUI version is handled in
1206 // GuiView::getStatus(). See above.
1208 case LFUN_BUFFER_WRITE:
1209 case LFUN_BUFFER_WRITE_AS: {
1210 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1211 enable = b && (b->isUnnamed() || !b->isClean());
1216 case LFUN_BOOKMARK_GOTO: {
1217 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1218 enable = theSession().bookmarks().isValid(num);
1222 case LFUN_BOOKMARK_CLEAR:
1223 enable = theSession().bookmarks().hasValid();
1226 // this one is difficult to get right. As a half-baked
1227 // solution, we consider only the first action of the sequence
1228 case LFUN_COMMAND_SEQUENCE: {
1229 // argument contains ';'-terminated commands
1230 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1231 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1232 func.setOrigin(cmd.origin());
1233 flag = getStatus(func);
1237 // we want to check if at least one of these is enabled
1238 case LFUN_COMMAND_ALTERNATIVES: {
1239 // argument contains ';'-terminated commands
1240 string arg = to_utf8(cmd.argument());
1241 while (!arg.empty()) {
1243 arg = split(arg, first, ';');
1244 FuncRequest func(lyxaction.lookupFunc(first));
1245 func.setOrigin(cmd.origin());
1246 flag = getStatus(func);
1247 // if this one is enabled, the whole thing is
1256 string name = to_utf8(cmd.argument());
1257 if (theTopLevelCmdDef().lock(name, func)) {
1258 func.setOrigin(cmd.origin());
1259 flag = getStatus(func);
1260 theTopLevelCmdDef().release(name);
1262 // catch recursion or unknown command
1263 // definition. all operations until the
1264 // recursion or unknown command definition
1265 // occurs are performed, so set the state to
1272 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1274 case LFUN_PREFERENCES_SAVE:
1275 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1276 case LFUN_DEBUG_LEVEL_SET:
1277 // these are handled in our dispatch()
1280 case LFUN_WINDOW_CLOSE:
1281 enable = d->views_.size() > 0;
1284 case LFUN_BUFFER_NEW:
1285 case LFUN_BUFFER_NEW_TEMPLATE:
1286 case LFUN_FILE_OPEN:
1287 case LFUN_HELP_OPEN:
1288 case LFUN_SCREEN_FONT_UPDATE:
1289 case LFUN_SET_COLOR:
1290 case LFUN_WINDOW_NEW:
1292 case LFUN_LYXRC_APPLY:
1293 case LFUN_COMMAND_PREFIX:
1295 case LFUN_META_PREFIX:
1296 case LFUN_RECONFIGURE:
1297 case LFUN_SERVER_GET_FILENAME:
1298 case LFUN_SERVER_NOTIFY:
1302 case LFUN_BUFFER_FORALL: {
1303 if (theBufferList().empty()) {
1304 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1305 flag.setEnabled(false);
1309 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1310 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1311 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1312 flag.setEnabled(false);
1317 case LFUN_DIALOG_SHOW: {
1318 string const name = cmd.getArg(0);
1319 return name == "aboutlyx"
1321 || name == "texinfo"
1322 || name == "progress"
1323 || name == "compare";
1331 flag.setEnabled(false);
1335 /// make a post-dispatch status message
1336 static docstring makeDispatchMessage(docstring const & msg,
1337 FuncRequest const & cmd)
1339 const bool verbose = (cmd.origin() == FuncRequest::MENU
1340 || cmd.origin() == FuncRequest::TOOLBAR
1341 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1343 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1344 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1348 docstring dispatch_msg = msg;
1349 if (!dispatch_msg.empty())
1350 dispatch_msg += ' ';
1352 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1354 bool argsadded = false;
1356 if (!cmd.argument().empty()) {
1357 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1358 comname += ' ' + cmd.argument();
1362 docstring const shortcuts = theTopLevelKeymap().
1363 printBindings(cmd, KeySequence::ForGui);
1365 if (!shortcuts.empty())
1366 comname += ": " + shortcuts;
1367 else if (!argsadded && !cmd.argument().empty())
1368 comname += ' ' + cmd.argument();
1370 if (!comname.empty()) {
1371 comname = rtrim(comname);
1372 dispatch_msg += '(' + rtrim(comname) + ')';
1374 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1375 return dispatch_msg;
1379 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1381 Buffer * buffer = 0;
1382 if (current_view_ && current_view_->currentBufferView()) {
1383 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1384 buffer = ¤t_view_->currentBufferView()->buffer();
1386 buffer->undo().beginUndoGroup();
1390 // redraw the screen at the end (first of the two drawing steps).
1391 // This is done unless explicitly requested otherwise
1392 dr.screenUpdate(Update::FitCursor);
1394 updateCurrentView(cmd, dr);
1396 // the buffer may have been closed by one action
1397 if (theBufferList().isLoaded(buffer))
1398 buffer->undo().endUndoGroup();
1400 d->dispatch_result_ = dr;
1401 return d->dispatch_result_;
1405 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1410 BufferView * bv = current_view_->currentBufferView();
1412 if (dr.needBufferUpdate()) {
1413 bv->cursor().clearBufferUpdate();
1414 bv->buffer().updateBuffer();
1415 } else if (dr.needChangesUpdate()) {
1416 // updateBuffer() already updates the change-tracking presence flag
1417 bv->buffer().updateChangesPresent();
1419 // BufferView::update() updates the ViewMetricsInfo and
1420 // also initializes the position cache for all insets in
1421 // (at least partially) visible top-level paragraphs.
1422 // We will redraw the screen only if needed.
1423 bv->processUpdateFlags(dr.screenUpdate());
1425 // Do we have a selection?
1426 theSelection().haveSelection(bv->cursor().selection());
1429 current_view_->restartCursor();
1431 if (dr.needMessageUpdate()) {
1432 // Some messages may already be translated, so we cannot use _()
1433 current_view_->message(makeDispatchMessage(
1434 translateIfPossible(dr.message()), cmd));
1439 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1440 bool switchToBuffer)
1442 if (!theSession().bookmarks().isValid(idx))
1444 BookmarksSection::Bookmark const & bm =
1445 theSession().bookmarks().bookmark(idx);
1446 LASSERT(!bm.filename.empty(), return);
1447 string const file = bm.filename.absFileName();
1448 // if the file is not opened, open it.
1449 if (!theBufferList().exists(bm.filename)) {
1451 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1455 // open may fail, so we need to test it again
1456 if (!theBufferList().exists(bm.filename))
1459 // bm can be changed when saving
1460 BookmarksSection::Bookmark tmp = bm;
1462 // Special case idx == 0 used for back-from-back jump navigation
1464 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1466 // if the current buffer is not that one, switch to it.
1467 BufferView * doc_bv = current_view_ ?
1468 current_view_->documentBufferView() : 0;
1469 // FIXME It's possible that doc_bv is null!!
1470 // See coverity #102061
1471 Cursor const old = doc_bv->cursor();
1472 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1473 if (switchToBuffer) {
1474 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1477 doc_bv = current_view_->documentBufferView();
1482 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1483 if (!doc_bv->moveToPosition(
1484 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1487 Cursor & cur = doc_bv->cursor();
1489 notifyCursorLeavesOrEnters(old, cur);
1495 // Cursor jump succeeded!
1496 pit_type new_pit = cur.pit();
1497 pos_type new_pos = cur.pos();
1498 int new_id = cur.paragraph().id();
1500 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1501 // see http://www.lyx.org/trac/ticket/3092
1502 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1503 || bm.top_id != new_id) {
1504 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1505 new_pit, new_pos, new_id);
1509 // This function runs "configure" and then rereads lyx.defaults to
1510 // reconfigure the automatic settings.
1511 void GuiApplication::reconfigure(string const & option)
1513 // emit message signal.
1515 current_view_->message(_("Running configure..."));
1517 // Run configure in user lyx directory
1518 string const lock_file = package().getConfigureLockName();
1519 int fd = fileLock(lock_file.c_str());
1520 int const ret = package().reconfigureUserLyXDir(option);
1521 // emit message signal.
1523 current_view_->message(_("Reloading configuration..."));
1524 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1525 // Re-read packages.lst
1526 LaTeXPackages::getAvailable();
1527 fileUnlock(fd, lock_file.c_str());
1530 Alert::information(_("System reconfiguration failed"),
1531 _("The system reconfiguration has failed.\n"
1532 "Default textclass is used but LyX may\n"
1533 "not be able to work properly.\n"
1534 "Please reconfigure again if needed."));
1536 Alert::information(_("System reconfigured"),
1537 _("The system has been reconfigured.\n"
1538 "You need to restart LyX to make use of any\n"
1539 "updated document class specifications."));
1542 void GuiApplication::validateCurrentView()
1544 if (!d->views_.empty() && !current_view_) {
1545 // currently at least one view exists but no view has the focus.
1546 // choose the last view to make it current.
1547 // a view without any open document is preferred.
1548 GuiView * candidate = 0;
1549 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1550 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1551 for (; it != end; ++it) {
1553 if (!candidate->documentBufferView())
1556 setCurrentView(candidate);
1560 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1562 string const argument = to_utf8(cmd.argument());
1563 FuncCode const action = cmd.action();
1565 LYXERR(Debug::ACTION, "cmd: " << cmd);
1567 // we have not done anything wrong yet.
1570 FuncStatus const flag = getStatus(cmd);
1571 if (!flag.enabled()) {
1572 // We cannot use this function here
1573 LYXERR(Debug::ACTION, "action "
1574 << lyxaction.getActionName(action)
1575 << " [" << action << "] is disabled at this location");
1576 dr.setMessage(flag.message());
1578 dr.dispatched(false);
1579 dr.screenUpdate(Update::None);
1580 dr.clearBufferUpdate();
1584 if (cmd.origin() == FuncRequest::LYXSERVER) {
1585 if (current_view_ && current_view_->currentBufferView())
1586 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1587 // we will also need to redraw the screen at the end
1588 dr.screenUpdate(Update::FitCursor);
1591 // Assumes that the action will be dispatched.
1592 dr.dispatched(true);
1594 switch (cmd.action()) {
1596 case LFUN_WINDOW_NEW:
1597 createView(toqstr(cmd.argument()));
1600 case LFUN_WINDOW_CLOSE:
1601 // update bookmark pit of the current buffer before window close
1602 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1603 gotoBookmark(i+1, false, false);
1604 // clear the last opened list, because
1605 // maybe this will end the session
1606 theSession().lastOpened().clear();
1607 // check for valid current_view_
1608 validateCurrentView();
1610 current_view_->closeScheduled();
1614 // quitting is triggered by the gui code
1615 // (leaving the event loop).
1617 current_view_->message(from_utf8(N_("Exiting.")));
1618 if (closeAllViews())
1622 case LFUN_SCREEN_FONT_UPDATE: {
1623 // handle the screen font changes.
1624 d->font_loader_.update();
1625 // Backup current_view_
1626 GuiView * view = current_view_;
1627 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1628 // to skip the refresh.
1630 theBufferList().changed(false);
1631 // Restore current_view_
1632 current_view_ = view;
1636 case LFUN_BUFFER_NEW:
1637 validateCurrentView();
1638 if (d->views_.empty()
1639 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1640 createView(QString(), false); // keep hidden
1641 current_view_->newDocument(to_utf8(cmd.argument()), false);
1642 current_view_->show();
1643 setActiveWindow(current_view_);
1645 current_view_->newDocument(to_utf8(cmd.argument()), false);
1649 case LFUN_BUFFER_NEW_TEMPLATE:
1650 validateCurrentView();
1651 if (d->views_.empty()
1652 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1654 current_view_->newDocument(to_utf8(cmd.argument()), true);
1655 if (!current_view_->documentBufferView())
1656 current_view_->close();
1658 current_view_->newDocument(to_utf8(cmd.argument()), true);
1662 case LFUN_FILE_OPEN: {
1663 validateCurrentView();
1664 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1665 string const fname = to_utf8(cmd.argument());
1666 bool const is_open = FileName::isAbsolute(fname)
1667 && theBufferList().getBuffer(FileName(fname));
1668 if (d->views_.empty()
1669 || (!lyxrc.open_buffers_in_tabs
1670 && current_view_->documentBufferView() != 0
1672 // We want the ui session to be saved per document and not per
1673 // window number. The filename crc is a good enough identifier.
1674 boost::crc_32_type crc;
1675 crc = for_each(fname.begin(), fname.end(), crc);
1676 createView(crc.checksum());
1677 // we know current_view_ is non-null, because createView sets it.
1678 // but let's make sure
1679 LASSERT(current_view_, break);
1680 current_view_->openDocument(fname);
1681 if (!current_view_->documentBufferView())
1682 current_view_->close();
1684 current_view_->raise();
1685 current_view_->activateWindow();
1686 current_view_->showNormal();
1689 // we know !d->views.empty(), so this should be ok
1690 // but let's make sure
1691 LASSERT(current_view_, break);
1692 current_view_->openDocument(fname);
1693 current_view_->raise();
1694 current_view_->activateWindow();
1695 current_view_->showNormal();
1700 case LFUN_HELP_OPEN: {
1701 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1702 if (current_view_ == 0)
1704 string const arg = to_utf8(cmd.argument());
1706 current_view_->message(_("Missing argument"));
1709 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1711 fname = i18nLibFileSearch("examples", arg, "lyx");
1713 if (fname.empty()) {
1714 lyxerr << "LyX: unable to find documentation file `"
1715 << arg << "'. Bad installation?" << endl;
1718 current_view_->message(bformat(_("Opening help file %1$s..."),
1719 makeDisplayPath(fname.absFileName())));
1720 Buffer * buf = current_view_->loadDocument(fname, false);
1722 #ifndef DEVEL_VERSION
1724 buf->setReadonly(true);
1731 case LFUN_SET_COLOR: {
1733 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1734 if (lyx_name.empty() || x11_name.empty()) {
1736 current_view_->message(
1737 _("Syntax: set-color <lyx_name> <x11_name>"));
1742 // FIXME: The graphics cache no longer has a changeDisplay method.
1743 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1744 bool const graphicsbg_changed =
1745 lyx_name == graphicsbg && x11_name != graphicsbg;
1746 if (graphicsbg_changed)
1747 graphics::GCache::get().changeDisplay(true);
1750 if (!lcolor.setColor(lyx_name, x11_name)) {
1752 current_view_->message(
1753 bformat(_("Set-color \"%1$s\" failed "
1754 "- color is undefined or "
1755 "may not be redefined"),
1756 from_utf8(lyx_name)));
1759 // Make sure we don't keep old colors in cache.
1760 d->color_cache_.clear();
1761 // Update the current view
1762 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1766 case LFUN_LYXRC_APPLY: {
1767 // reset active key sequences, since the bindings
1768 // are updated (bug 6064)
1770 LyXRC const lyxrc_orig = lyxrc;
1772 istringstream ss(to_utf8(cmd.argument()));
1773 bool const success = lyxrc.read(ss);
1776 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1777 << "Unable to read lyxrc data"
1782 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1784 // If the request comes from the minibuffer, then we can't reset
1785 // the GUI, since that would destory the minibuffer itself and
1786 // cause a crash, since we are currently in one of the methods of
1787 // GuiCommandBuffer. See bug #8540.
1788 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1791 // FIXME Unfortunately, that leaves a bug here, since we cannot
1792 // reset the GUI in this case. If the changes to lyxrc affected the
1793 // UI, then, nothing would happen. This seems fairly unlikely, but
1794 // it definitely is a bug.
1799 case LFUN_COMMAND_PREFIX:
1800 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1805 d->meta_fake_bit = NoModifier;
1806 GuiView * gv = currentView();
1807 if (gv && gv->currentBufferView())
1808 // cancel any selection
1809 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1810 dr.setMessage(from_ascii(N_("Cancel")));
1813 case LFUN_META_PREFIX:
1814 d->meta_fake_bit = AltModifier;
1815 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1818 // --- Menus -----------------------------------------------
1819 case LFUN_RECONFIGURE:
1820 // argument is any additional parameter to the configure.py command
1821 reconfigure(to_utf8(cmd.argument()));
1824 // --- lyxserver commands ----------------------------
1825 case LFUN_SERVER_GET_FILENAME: {
1826 if (current_view_ && current_view_->documentBufferView()) {
1827 docstring const fname = from_utf8(
1828 current_view_->documentBufferView()->buffer().absFileName());
1829 dr.setMessage(fname);
1830 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1832 dr.setMessage(docstring());
1833 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1838 case LFUN_SERVER_NOTIFY: {
1839 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1840 dr.setMessage(dispatch_buffer);
1841 theServer().notifyClient(to_utf8(dispatch_buffer));
1845 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1846 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1852 string rest = split(argument, countstr, ' ');
1853 istringstream is(countstr);
1856 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1857 for (int i = 0; i < count; ++i)
1858 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)
2069 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2072 current_view_->dispatch(cmd, dr);
2076 if (cmd.origin() == FuncRequest::LYXSERVER)
2077 updateCurrentView(cmd, dr);
2081 docstring GuiApplication::viewStatusMessage()
2083 // When meta-fake key is pressed, show the key sequence so far + "M-".
2084 if (d->meta_fake_bit != NoModifier)
2085 return d->keyseq.print(KeySequence::ForGui) + "M-";
2087 // Else, when a non-complete key sequence is pressed,
2088 // show the available options.
2089 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2090 return d->keyseq.printOptions(true);
2096 void GuiApplication::handleKeyFunc(FuncCode action)
2100 if (d->keyseq.length())
2102 GuiView * gv = currentView();
2103 LASSERT(gv && gv->currentBufferView(), return);
2104 BufferView * bv = gv->currentBufferView();
2105 bv->getIntl().getTransManager().deadkey(
2106 c, get_accent(action).accent, bv->cursor().innerText(),
2108 // Need to clear, in case the minibuffer calls these
2111 // copied verbatim from do_accent_char
2112 bv->cursor().resetAnchor();
2116 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2118 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2120 // Do nothing if we have nothing (JMarc)
2121 if (!keysym.isOK()) {
2122 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2124 current_view_->restartCursor();
2128 if (keysym.isModifier()) {
2130 current_view_->restartCursor();
2134 char_type encoded_last_key = keysym.getUCSEncoded();
2136 // Do a one-deep top-level lookup for
2137 // cancel and meta-fake keys. RVDK_PATCH_5
2138 d->cancel_meta_seq.reset();
2140 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2141 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2143 // When not cancel or meta-fake, do the normal lookup.
2144 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2145 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2146 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2147 // remove Caps Lock and Mod2 as a modifiers
2148 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2149 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2152 // Dont remove this unless you know what you are doing.
2153 d->meta_fake_bit = NoModifier;
2155 // Can this happen now ?
2156 if (func.action() == LFUN_NOACTION)
2157 func = FuncRequest(LFUN_COMMAND_PREFIX);
2159 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2160 << d->keyseq.print(KeySequence::Portable) << ']');
2162 // already here we know if it any point in going further
2163 // why not return already here if action == -1 and
2164 // num_bytes == 0? (Lgb)
2166 if (d->keyseq.length() > 1 && current_view_)
2167 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2170 // Maybe user can only reach the key via holding down shift.
2171 // Let's see. But only if shift is the only modifier
2172 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2173 LYXERR(Debug::KEY, "Trying without shift");
2174 func = d->keyseq.addkey(keysym, NoModifier);
2175 LYXERR(Debug::KEY, "Action now " << func.action());
2178 if (func.action() == LFUN_UNKNOWN_ACTION) {
2179 // We didn't match any of the key sequences.
2180 // See if it's normal insertable text not already
2181 // covered by a binding
2182 if (keysym.isText() && d->keyseq.length() == 1) {
2183 // Non-printable characters (such as ASCII control characters)
2184 // must not be inserted (#5704)
2185 if (!isPrintable(encoded_last_key)) {
2186 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2188 current_view_->restartCursor();
2191 // The following modifier check is not needed on Mac.
2192 // The keysym is either not text or it is different
2193 // from the non-modifier keysym. See #9875 for the
2194 // broken alt-modifier effect of having this code active.
2195 #if !defined(Q_OS_MAC)
2196 // If a non-Shift Modifier is used we have a non-bound key sequence
2197 // (such as Alt+j = j). This should be omitted (#5575).
2198 // On Windows, AltModifier and ControlModifier are both
2199 // set when AltGr is pressed. Therefore, in order to not
2200 // break AltGr-bound symbols (see #5575 for details),
2201 // unbound Ctrl+Alt key sequences are allowed.
2202 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2203 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2204 && !(state & AltModifier && state & ControlModifier)
2208 if (current_view_) {
2209 current_view_->message(_("Unknown function."));
2210 current_view_->restartCursor();
2215 // Since all checks above were passed, we now really have text that
2216 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2217 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2219 LYXERR(Debug::KEY, "isText() is true, inserting.");
2220 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2222 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2223 if (current_view_) {
2224 current_view_->message(_("Unknown function."));
2225 current_view_->restartCursor();
2231 if (func.action() == LFUN_SELF_INSERT) {
2232 if (encoded_last_key != 0) {
2233 docstring const arg(1, encoded_last_key);
2234 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2235 FuncRequest::KEYBOARD));
2236 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2239 processFuncRequest(func);
2243 void GuiApplication::processFuncRequest(FuncRequest const & func)
2245 lyx::dispatch(func);
2249 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2251 addToFuncRequestQueue(func);
2252 processFuncRequestQueueAsync();
2256 void GuiApplication::processFuncRequestQueue()
2258 while (!d->func_request_queue_.empty()) {
2259 processFuncRequest(d->func_request_queue_.front());
2260 d->func_request_queue_.pop();
2265 void GuiApplication::processFuncRequestQueueAsync()
2267 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2271 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2273 d->func_request_queue_.push(func);
2277 void GuiApplication::resetGui()
2279 // Set the language defined by the user.
2283 if (!readUIFile(toqstr(lyxrc.ui_file)))
2284 // Gives some error box here.
2287 if (d->global_menubar_)
2288 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2290 QHash<int, GuiView *>::iterator it;
2291 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2294 gv->setLayoutDirection(layoutDirection());
2298 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2302 void GuiApplication::createView(int view_id)
2304 createView(QString(), true, view_id);
2308 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2311 // release the keyboard which might have been grabed by the global
2312 // menubar on Mac to catch shortcuts even without any GuiView.
2313 if (d->global_menubar_)
2314 d->global_menubar_->releaseKeyboard();
2318 while (d->views_.find(id) != d->views_.end())
2321 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2322 GuiView * view = new GuiView(id);
2324 d->views_[id] = view;
2328 setActiveWindow(view);
2331 if (!geometry_arg.isEmpty()) {
2332 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2336 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2337 re.indexIn(geometry_arg);
2338 w = re.cap(1).toInt();
2339 h = re.cap(2).toInt();
2340 x = re.cap(3).toInt();
2341 y = re.cap(4).toInt();
2342 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2343 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2344 // Set initial geometry such that we can get the frame size.
2345 view->setGeometry(x, y, w, h);
2346 int framewidth = view->geometry().x() - view->x();
2347 int titleheight = view->geometry().y() - view->y();
2348 // Negative displacements must be interpreted as distances
2349 // from the right or bottom screen borders.
2350 if (sx == '-' || sy == '-') {
2351 QRect rec = QApplication::desktop()->screenGeometry();
2353 x += rec.width() - w - framewidth;
2355 y += rec.height() - h - titleheight;
2356 view->setGeometry(x, y, w, h);
2358 // Make sure that the left and top frame borders are visible.
2359 if (view->x() < 0 || view->y() < 0) {
2364 view->setGeometry(x, y, w, h);
2372 Clipboard & GuiApplication::clipboard()
2374 return d->clipboard_;
2378 Selection & GuiApplication::selection()
2380 return d->selection_;
2384 FontLoader & GuiApplication::fontLoader()
2386 return d->font_loader_;
2390 Toolbars const & GuiApplication::toolbars() const
2392 return d->toolbars_;
2396 Toolbars & GuiApplication::toolbars()
2398 return d->toolbars_;
2402 Menus const & GuiApplication::menus() const
2408 Menus & GuiApplication::menus()
2414 QList<int> GuiApplication::viewIds() const
2416 return d->views_.keys();
2420 ColorCache & GuiApplication::colorCache()
2422 return d->color_cache_;
2426 int GuiApplication::exec()
2428 // asynchronously handle batch commands. This event will be in
2429 // the event queue in front of other asynchronous events. Hence,
2430 // we can assume in the latter that the gui is setup already.
2431 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2433 return QApplication::exec();
2437 void GuiApplication::exit(int status)
2439 QApplication::exit(status);
2443 void GuiApplication::setGuiLanguage()
2447 // install translation file for Qt built-in dialogs
2448 QString const language_name = QString("qt_") + theLocale.name();
2449 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2450 // Short-named translator can be loaded from a long name, but not the
2451 // opposite. Therefore, long name should be used without truncation.
2452 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2453 if (!d->qt_trans_.load(language_name,
2454 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2455 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2458 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2462 switch (theLocale.language()) {
2463 case QLocale::Arabic :
2464 case QLocale::Hebrew :
2465 case QLocale::Persian :
2466 case QLocale::Urdu :
2467 setLayoutDirection(Qt::RightToLeft);
2470 setLayoutDirection(Qt::LeftToRight);
2475 void GuiApplication::execBatchCommands()
2480 if (!readUIFile(toqstr(lyxrc.ui_file)))
2481 // Gives some error box here.
2485 #if QT_VERSION > 0x040600
2486 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2488 #if QT_VERSION > 0x050100
2489 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2491 // Create the global default menubar which is shown for the dialogs
2492 // and if no GuiView is visible.
2493 // This must be done after the session was recovered to know the "last files".
2494 d->global_menubar_ = new QMenuBar(0);
2495 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2498 lyx::execBatchCommands();
2502 QAbstractItemModel * GuiApplication::languageModel()
2504 if (d->language_model_)
2505 return d->language_model_;
2507 QStandardItemModel * lang_model = new QStandardItemModel(this);
2508 lang_model->insertColumns(0, 3);
2509 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2510 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2511 Languages::const_iterator it = lyx::languages.begin();
2512 Languages::const_iterator end = lyx::languages.end();
2513 for (; it != end; ++it) {
2514 int current_row = lang_model->rowCount();
2515 lang_model->insertRows(current_row, 1);
2516 QModelIndex pl_item = lang_model->index(current_row, 0);
2517 QModelIndex sp_item = lang_model->index(current_row, 1);
2518 QModelIndex th_item = lang_model->index(current_row, 2);
2519 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2520 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2521 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2522 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2523 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2524 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2525 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2526 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2527 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2528 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2530 d->language_model_ = new QSortFilterProxyModel(this);
2531 d->language_model_->setSourceModel(lang_model);
2532 d->language_model_->setSortLocaleAware(true);
2533 return d->language_model_;
2537 void GuiApplication::restoreGuiSession()
2539 if (!lyxrc.load_session)
2542 Session & session = theSession();
2543 LastOpenedSection::LastOpened const & lastopened =
2544 session.lastOpened().getfiles();
2546 validateCurrentView();
2548 FileName active_file;
2549 // do not add to the lastfile list since these files are restored from
2550 // last session, and should be already there (regular files), or should
2551 // not be added at all (help files).
2552 for (size_t i = 0; i < lastopened.size(); ++i) {
2553 FileName const & file_name = lastopened[i].file_name;
2554 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2555 && current_view_->documentBufferView() != 0)) {
2556 boost::crc_32_type crc;
2557 string const & fname = file_name.absFileName();
2558 crc = for_each(fname.begin(), fname.end(), crc);
2559 createView(crc.checksum());
2561 current_view_->loadDocument(file_name, false);
2563 if (lastopened[i].active)
2564 active_file = file_name;
2567 // Restore last active buffer
2568 Buffer * buffer = theBufferList().getBuffer(active_file);
2569 if (buffer && current_view_)
2570 current_view_->setBuffer(buffer);
2572 // clear this list to save a few bytes of RAM
2573 session.lastOpened().clear();
2577 QString const GuiApplication::romanFontName()
2580 font.setStyleHint(QFont::Serif);
2581 font.setFamily("serif");
2583 return QFontInfo(font).family();
2587 QString const GuiApplication::sansFontName()
2590 font.setStyleHint(QFont::SansSerif);
2591 font.setFamily("sans");
2593 return QFontInfo(font).family();
2597 QString const GuiApplication::typewriterFontName()
2599 return QFontInfo(typewriterSystemFont()).family();
2604 // We cannot use QFont::fixedPitch() because it doesn't
2605 // return the fact but only if it is requested.
2606 static bool isFixedPitch(const QFont & font) {
2607 const QFontInfo fi(font);
2608 return fi.fixedPitch();
2613 QFont const GuiApplication::typewriterSystemFont()
2615 #if QT_VERSION >= 0x050200
2616 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2618 QFont font("monospace");
2620 if (!isFixedPitch(font)) {
2621 // try to enforce a real monospaced font
2622 font.setStyleHint(QFont::Monospace);
2623 if (!isFixedPitch(font)) {
2624 font.setStyleHint(QFont::TypeWriter);
2625 if (!isFixedPitch(font)) font.setFamily("courier");
2629 // On a Mac the result is too small and it's not practical to
2630 // rely on Qtconfig utility to change the system settings of Qt.
2631 font.setPointSize(12);
2637 void GuiApplication::handleRegularEvents()
2639 ForkedCallsController::handleCompletedProcesses();
2643 bool GuiApplication::event(QEvent * e)
2646 case QEvent::FileOpen: {
2647 // Open a file; this happens only on Mac OS X for now.
2649 // We do this asynchronously because on startup the batch
2650 // commands are not executed here yet and the gui is not ready
2652 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2653 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2654 processFuncRequestAsync(fr);
2659 return QApplication::event(e);
2664 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2667 return QApplication::notify(receiver, event);
2669 catch (ExceptionMessage const & e) {
2671 case ErrorException:
2673 setQuitOnLastWindowClosed(false);
2675 Alert::error(e.title_, e.details_);
2677 // Properly crash in debug mode in order to get a useful backtrace.
2680 // In release mode, try to exit gracefully.
2683 case BufferException: {
2684 if (!current_view_ || !current_view_->documentBufferView())
2686 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2687 docstring details = e.details_ + '\n';
2688 details += buf->emergencyWrite();
2689 theBufferList().release(buf);
2690 details += "\n" + _("The current document was closed.");
2691 Alert::error(e.title_, details);
2694 case WarningException:
2695 Alert::warning(e.title_, e.details_);
2699 catch (exception const & e) {
2700 docstring s = _("LyX has caught an exception, it will now "
2701 "attempt to save all unsaved documents and exit."
2703 s += from_ascii(e.what());
2704 Alert::error(_("Software exception Detected"), s);
2708 docstring s = _("LyX has caught some really weird exception, it will "
2709 "now attempt to save all unsaved documents and exit.");
2710 Alert::error(_("Software exception Detected"), s);
2718 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2720 QColor const & qcol = d->color_cache_.get(col);
2721 if (!qcol.isValid()) {
2727 rgbcol.r = qcol.red();
2728 rgbcol.g = qcol.green();
2729 rgbcol.b = qcol.blue();
2734 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2736 QColor const qcol(lcolor.getX11Name(col).c_str());
2737 if (!qcol.isValid()) {
2743 rgbcol.r = qcol.red();
2744 rgbcol.g = qcol.green();
2745 rgbcol.b = qcol.blue();
2750 string const GuiApplication::hexName(ColorCode col)
2752 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2756 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2758 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2759 d->socket_notifiers_[fd] = sn;
2760 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2764 void GuiApplication::socketDataReceived(int fd)
2766 d->socket_notifiers_[fd]->func_();
2770 void GuiApplication::unregisterSocketCallback(int fd)
2772 d->socket_notifiers_.take(fd)->setEnabled(false);
2776 void GuiApplication::commitData(QSessionManager & sm)
2778 /** The implementation is required to avoid an application exit
2779 ** when session state save is triggered by session manager.
2780 ** The default implementation sends a close event to all
2781 ** visible top level widgets when session managment allows
2783 ** We are changing that to check the state of each buffer in all
2784 ** views and ask the users what to do if buffers are dirty.
2785 ** Furthermore, we save the session state.
2786 ** We do NOT close the views here since the user still can cancel
2787 ** the logout process (see #9277); also, this would hide LyX from
2788 ** an OSes own session handling (application restoration).
2790 #ifdef QT_NO_SESSIONMANAGER
2792 #warning Qt is compiled without session manager
2794 #pragma message("warning: Qt is compiled without session manager")
2798 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2806 void GuiApplication::unregisterView(GuiView * gv)
2808 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2809 d->views_.remove(gv->id());
2810 if (current_view_ == gv)
2816 bool GuiApplication::closeAllViews()
2818 if (d->views_.empty())
2821 // When a view/window was closed before without quitting LyX, there
2822 // are already entries in the lastOpened list.
2823 theSession().lastOpened().clear();
2825 QList<GuiView *> const views = d->views_.values();
2826 for (GuiView * view : views) {
2827 if (!view->closeScheduled())
2836 bool GuiApplication::prepareAllViewsForLogout()
2838 if (d->views_.empty())
2841 QList<GuiView *> const views = d->views_.values();
2842 for (GuiView * view : views) {
2843 if (!view->prepareAllBuffersForLogout())
2851 GuiView & GuiApplication::view(int id) const
2853 LAPPERR(d->views_.contains(id));
2854 return *d->views_.value(id);
2858 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2860 QList<GuiView *> const views = d->views_.values();
2861 for (GuiView * view : views)
2862 view->hideDialog(name, inset);
2866 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2868 Buffer const * buffer_ = 0;
2869 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2870 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2871 if (Buffer const * ptr = (*it)->updateInset(inset))
2878 bool GuiApplication::searchMenu(FuncRequest const & func,
2879 docstring_list & names) const
2881 return d->menus_.searchMenu(func, names);
2885 // Ensure that a file is read only once (prevents include loops)
2886 static QStringList uifiles;
2887 // store which ui files define Toolbars
2888 static QStringList toolbar_uifiles;
2891 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2902 LexerKeyword uitags[] = {
2903 { "format", ui_format },
2904 { "include", ui_include },
2905 { "menuset", ui_menuset },
2906 { "toolbars", ui_toolbars },
2907 { "toolbarset", ui_toolbarset }
2911 lex.setFile(ui_path);
2913 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2917 if (lyxerr.debugging(Debug::PARSER))
2918 lex.printTable(lyxerr);
2921 // format before introduction of format tag
2922 unsigned int format = 0;
2923 while (lex.isOK()) {
2924 int const status = lex.lex();
2926 // we have to do this check here, outside the switch,
2927 // because otherwise we would start reading include files,
2928 // e.g., if the first tag we hit was an include tag.
2929 if (status == ui_format)
2931 format = lex.getInteger();
2935 // this will trigger unless the first tag we hit is a format
2936 // tag, with the right format.
2937 if (format != LFUN_FORMAT)
2938 return FormatMismatch;
2941 case Lexer::LEX_FEOF:
2946 QString const file = toqstr(lex.getString());
2947 bool const success = readUIFile(file, true);
2949 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2956 d->menus_.read(lex);
2960 d->toolbars_.readToolbars(lex);
2964 d->toolbars_.readToolbarSettings(lex);
2965 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2969 if (!rtrim(lex.getString()).empty())
2970 lex.printError("LyX::ReadUIFile: "
2971 "Unknown menu tag: `$$Token'");
2973 LYXERR0("Error with status: " << status);
2979 return (error ? ReadError : ReadOK);
2983 bool GuiApplication::readUIFile(QString const & name, bool include)
2985 LYXERR(Debug::INIT, "About to read " << name << "...");
2989 ui_path = libFileSearch("ui", name, "inc");
2990 if (ui_path.empty())
2991 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2993 ui_path = libFileSearch("ui", name, "ui");
2996 if (ui_path.empty()) {
2997 static const QString defaultUIFile = "default";
2998 LYXERR(Debug::INIT, "Could not find " << name);
3000 Alert::warning(_("Could not find UI definition file"),
3001 bformat(_("Error while reading the included file\n%1$s\n"
3002 "Please check your installation."), qstring_to_ucs4(name)));
3005 if (name == defaultUIFile) {
3006 LYXERR(Debug::INIT, "Could not find default UI file!!");
3007 Alert::warning(_("Could not find default UI file"),
3008 _("LyX could not find the default UI file!\n"
3009 "Please check your installation."));
3012 Alert::warning(_("Could not find UI definition file"),
3013 bformat(_("Error while reading the configuration file\n%1$s\n"
3014 "Falling back to default.\n"
3015 "Please look under Tools>Preferences>User Interface and\n"
3016 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3017 return readUIFile(defaultUIFile, false);
3020 QString const uifile = toqstr(ui_path.absFileName());
3021 if (uifiles.contains(uifile)) {
3023 // We are reading again the top uifile so reset the safeguard:
3026 d->toolbars_.reset();
3028 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3029 << "Is this an include loop?");
3033 uifiles.push_back(uifile);
3035 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3037 ReturnValues retval = readUIFile(ui_path);
3039 if (retval == FormatMismatch) {
3040 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3041 TempFile tmp("convertXXXXXX.ui");
3042 FileName const tempfile = tmp.name();
3043 bool const success = prefs2prefs(ui_path, tempfile, true);
3045 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3046 " to format " << LFUN_FORMAT << ".");
3048 retval = readUIFile(tempfile);
3052 if (retval != ReadOK) {
3053 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3061 settings.beginGroup("ui_files");
3062 bool touched = false;
3063 for (int i = 0; i != uifiles.size(); ++i) {
3064 QFileInfo fi(uifiles[i]);
3065 QDateTime const date_value = fi.lastModified();
3066 QString const name_key = QString::number(i);
3067 // if an ui file which defines Toolbars has changed,
3068 // we have to reset the settings
3069 if (toolbar_uifiles.contains(uifiles[i])
3070 && (!settings.contains(name_key)
3071 || settings.value(name_key).toString() != uifiles[i]
3072 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3074 settings.setValue(name_key, uifiles[i]);
3075 settings.setValue(name_key + "/date", date_value);
3078 settings.endGroup();
3080 settings.remove("views");
3086 void GuiApplication::onLastWindowClosed()
3088 if (d->global_menubar_)
3089 d->global_menubar_->grabKeyboard();
3093 void GuiApplication::startLongOperation() {
3094 d->key_checker_.start();
3098 bool GuiApplication::longOperationCancelled() {
3099 return d->key_checker_.pressed();
3103 void GuiApplication::stopLongOperation() {
3104 d->key_checker_.stop();
3108 bool GuiApplication::longOperationStarted() {
3109 return d->key_checker_.started();
3113 ////////////////////////////////////////////////////////////////////////
3115 // X11 specific stuff goes here...
3118 bool GuiApplication::x11EventFilter(XEvent * xev)
3123 switch (xev->type) {
3124 case SelectionRequest: {
3125 if (xev->xselectionrequest.selection != XA_PRIMARY)
3127 LYXERR(Debug::SELECTION, "X requested selection.");
3128 BufferView * bv = current_view_->currentBufferView();
3130 docstring const sel = bv->requestSelection();
3132 d->selection_.put(sel);
3136 case SelectionClear: {
3137 if (xev->xselectionclear.selection != XA_PRIMARY)
3139 LYXERR(Debug::SELECTION, "Lost selection.");
3140 BufferView * bv = current_view_->currentBufferView();
3142 bv->clearSelection();
3148 #elif defined(QPA_XCB)
3149 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3150 void * message, long *)
3152 if (!current_view_ || eventType != "xcb_generic_event_t")
3155 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3157 switch (ev->response_type) {
3158 case XCB_SELECTION_REQUEST: {
3159 xcb_selection_request_event_t * srev =
3160 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3161 if (srev->selection != XCB_ATOM_PRIMARY)
3163 LYXERR(Debug::SELECTION, "X requested selection.");
3164 BufferView * bv = current_view_->currentBufferView();
3166 docstring const sel = bv->requestSelection();
3168 d->selection_.put(sel);
3172 case XCB_SELECTION_CLEAR: {
3173 xcb_selection_clear_event_t * scev =
3174 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3175 if (scev->selection != XCB_ATOM_PRIMARY)
3177 LYXERR(Debug::SELECTION, "Lost selection.");
3178 BufferView * bv = current_view_->currentBufferView();
3180 bv->clearSelection();
3188 } // namespace frontend
3191 void hideDialogs(std::string const & name, Inset * inset)
3194 frontend::guiApp->hideDialogs(name, inset);
3198 ////////////////////////////////////////////////////////////////////
3202 ////////////////////////////////////////////////////////////////////
3204 frontend::FontLoader & theFontLoader()
3206 LAPPERR(frontend::guiApp);
3207 return frontend::guiApp->fontLoader();
3211 frontend::FontMetrics const & theFontMetrics(Font const & f)
3213 return theFontMetrics(f.fontInfo());
3217 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3219 LAPPERR(frontend::guiApp);
3220 return frontend::guiApp->fontLoader().metrics(f);
3224 ////////////////////////////////////////////////////////////////////
3228 ////////////////////////////////////////////////////////////////////
3230 frontend::Clipboard & theClipboard()
3232 LAPPERR(frontend::guiApp);
3233 return frontend::guiApp->clipboard();
3237 frontend::Selection & theSelection()
3239 LAPPERR(frontend::guiApp);
3240 return frontend::guiApp->selection();
3246 #include "moc_GuiApplication.cpp"