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 "ColorCache.h"
19 #include "GuiClipboard.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
24 #include "qt_helpers.h"
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
33 #include "BufferList.h"
34 #include "BufferParams.h"
35 #include "BufferView.h"
38 #include "CutAndPaste.h"
39 #include "ErrorList.h"
41 #include "FuncRequest.h"
42 #include "FuncStatus.h"
43 #include "GuiWorkArea.h"
47 #include "LaTeXPackages.h"
50 #include "LyXAction.h"
52 #include "Paragraph.h"
55 #include "SpellChecker.h"
56 #include "Thesaurus.h"
59 #include "insets/InsetText.h"
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/ExceptionMessage.h"
64 #include "support/FileName.h"
65 #include "support/filetools.h"
66 #include "support/foreach.h"
67 #include "support/ForkedCalls.h"
68 #include "support/gettext.h"
69 #include "support/lassert.h"
70 #include "support/lstrings.h"
71 #include "support/lyxalgo.h" // sorted
72 #include "support/textutils.h"
73 #include "support/Messages.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/TempFile.h"
79 #include "support/AppleScript.h"
80 #include "support/linkback/LinkBackProxy.h"
88 #include <QDesktopWidget>
92 #include <QFileOpenEvent>
96 #include <QImageReader>
99 #include <QLibraryInfo>
105 #include <QPixmapCache>
107 #include <QSessionManager>
109 #include <QShowEvent>
110 #include <QSocketNotifier>
111 #include <QSortFilterProxyModel>
112 #include <QStandardItemModel>
113 #include <QTextCodec>
115 #include <QTranslator>
116 #include <QThreadPool>
120 #include <X11/Xatom.h>
121 #include <X11/Xlib.h>
124 #elif defined(QPA_XCB)
126 #include <X11/Xatom.h>
127 #include <X11/Intrinsic.h>
131 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
132 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
133 #if (QT_VERSION < 0x050000)
134 #include <QWindowsMime>
135 #define QWINDOWSMIME QWindowsMime
138 #define QWINDOWSMIME QWinMime
148 #include <QMacPasteboardMime>
151 #include "support/bind.h"
152 #include <boost/crc.hpp>
159 using namespace lyx::support;
162 static void initializeResources()
164 static bool initialized = false;
166 Q_INIT_RESOURCE(Resources);
174 frontend::Application * createApplication(int & argc, char * argv[])
176 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
177 // prune -geometry argument(s) by shifting
178 // the following ones 2 places down.
179 for (int i = 0 ; i < argc ; ++i) {
180 if (strcmp(argv[i], "-geometry") == 0) {
181 int const remove = (i+1) < argc ? 2 : 1;
183 for (int j = i; j < argc; ++j)
184 argv[j] = argv[j + remove];
189 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
190 // I'd rather do that in the constructor, but I do not think that
191 // the palette is accessible there.
192 guiApp->colorCache().setPalette(guiApp->palette());
201 if (lyxrc.gui_language == "auto") {
202 theLocale = QLocale::system();
203 code = fromqstr(theLocale.name());
205 Language const * l = languages.getLanguage(lyxrc.gui_language);
206 code = l ? l->code() : "C";
207 theLocale = QLocale(toqstr(code));
209 // Qt tries to outsmart us and transforms en_US to C.
210 Messages::guiLanguage((code == "C") ? "en_US" : code);
211 QLocale::setDefault(theLocale);
212 setlocale(LC_NUMERIC, "C");
219 /// Return the list of loadable formats.
220 vector<string> loadableImageFormats()
224 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
226 LYXERR(Debug::GRAPHICS,
227 "\nThe image loader can load the following directly:\n");
229 if (qt_formats.empty())
230 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
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);
247 ////////////////////////////////////////////////////////////////////////
249 // Icon loading support code
251 ////////////////////////////////////////////////////////////////////////
261 bool operator<(PngMap const & lhs, PngMap const & rhs)
263 return lhs.key < rhs.key;
269 CompareKey(QString const & name) : name_(name) {}
270 bool operator()(PngMap const & other) const { return other.key == name_; }
276 // this must be sorted alphabetically
277 // Upper case comes before lower case
278 // Please don't change the formatting, this list is parsed by
279 // development/tools/generate_symbols_images.py.
280 PngMap sorted_png_map[] = {
281 { "Arrownot", "arrownot2"},
282 { "Arrowvert", "arrowvert2"},
283 { "Bowtie", "bowtie2" },
285 { "Bumpeq", "bumpeq2" },
286 { "CIRCLE", "circle3" },
288 { "CheckedBox", "checkedbox2" },
289 { "Circle", "circle2" },
290 { "Colonapprox", "colonapprox2" },
291 { "Coloneq", "coloneq2" },
292 { "Coloneqq", "coloneqq2" },
293 { "Colonsim", "colonsim2" },
295 { "DOWNarrow", "downarrow3" },
296 { "Delta", "delta2" },
297 { "Diamond", "diamond2" },
298 { "Doteq", "doteq2" },
299 { "Downarrow", "downarrow2" },
300 { "Eqcolon", "eqcolon2" },
301 { "Eqqcolon", "eqqcolon2" },
302 { "Gamma", "gamma2" },
304 { "LEFTCIRCLE", "leftcircle3" },
305 { "LEFTarrow", "leftarrow3" },
306 { "LEFTcircle", "leftcircle4" },
308 { "Lambda", "lambda2" },
310 { "Leftarrow", "leftarrow2" },
311 { "Leftcircle", "leftcircle2" },
312 { "Leftrightarrow", "leftrightarrow2" },
313 { "Longarrownot", "longarrownot2"},
314 { "Longleftarrow", "longleftarrow2" },
315 { "Longleftrightarrow", "longleftrightarrow2" },
316 { "Longmapsfrom", "longmapsfrom2"},
317 { "Longmapsto", "longmapsto2"},
318 { "Longrightarrow", "longrightarrow2" },
319 { "Mapsfrom", "mapsfrom2"},
320 { "Mapsfromchar", "mapsfromchar2"},
321 { "Mapsto", "mapsto2"},
322 { "Mapstochar", "mapstochar2"},
323 { "Omega", "omega2" },
328 { "RIGHTCIRCLE", "rightcircle3" },
329 { "RIGHTarrow", "rightarrow3" },
330 { "RIGHTcircle", "rightcircle4" },
332 { "Rightarrow", "rightarrow2" },
333 { "Rightcircle", "rightcircle2" },
334 { "Sigma", "sigma2" },
335 { "Square", "square2" },
336 { "Subset", "subset2" },
337 { "Supset", "supset2" },
338 { "Theta", "theta2" },
339 { "Thorn", "thorn2" },
340 { "UParrow", "uparrow3" },
341 { "Uparrow", "uparrow2" },
342 { "Updownarrow", "updownarrow2" },
343 { "Upsilon", "upsilon2" },
344 { "Vdash", "vdash3" },
349 { "lVert", "vert2" },
351 { "nLeftarrow", "nleftarrow2" },
352 { "nLeftrightarrow", "nleftrightarrow2" },
353 { "nRightarrow", "nrightarrow2" },
354 { "nVDash", "nvdash3" },
355 { "nVdash", "nvdash4" },
356 { "nvDash", "nvdash2" },
357 { "rVert", "vert2" },
359 { "textrm \\AA", "textrm_AA"},
360 { "textrm \\O", "textrm_O"},
361 { "vDash", "vdash2" },
362 { "varDelta", "vardelta2" },
363 { "varGamma", "vargamma2" },
364 { "varLambda", "varlambda2" },
365 { "varOmega", "varomega2" },
366 { "varPhi", "varphi2" },
367 { "varPi", "varpi2" },
368 { "varPsi", "varpsi2" },
369 { "varSigma", "varsigma2" },
370 { "varTheta", "vartheta2" },
371 { "varUpsilon", "varupsilon2" },
372 { "varXi", "varxi2" }
376 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
378 // This list specifies which system's theme icon is related to which lyx
379 // command. It was based on:
380 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
381 // this must be sorted alphabetically
382 // Upper case comes before lower case
383 PngMap sorted_theme_icon_map[] = {
384 { "bookmark-goto 0", "go-jump" },
385 { "buffer-new", "document-new" },
386 { "buffer-print", "document-print" },
387 { "buffer-write", "document-save" },
388 { "buffer-write-as", "document-save-as" },
389 { "buffer-zoom-in", "zoom-in" },
390 { "buffer-zoom-out", "zoom-out" },
391 { "copy", "edit-copy" },
392 { "cut", "edit-cut" },
393 { "depth-decrement", "format-indent-less" },
394 { "depth-increment", "format-indent-more" },
395 { "dialog-show print", "document-print" },
396 { "dialog-show spellchecker", "tools-check-spelling" },
397 { "dialog-show-new-inset graphics", "insert-image" },
398 { "dialog-toggle findreplaceadv", "edit-find-replace" },
399 { "file-open", "document-open" },
400 { "font-bold", "format-text-bold" },
401 { "font-ital", "format-text-italic" },
402 { "font-strikeout", "format-text-strikethrough" },
403 { "font-underline", "format-text-underline" },
404 { "lyx-quit", "application-exit" },
405 { "paste", "edit-paste" },
406 { "redo", "edit-redo" },
407 { "undo", "edit-undo" },
408 { "window-close", "window-close" },
409 { "window-new", "window-new" }
412 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
415 QString findPng(QString const & name)
417 PngMap const * const begin = sorted_png_map;
418 PngMap const * const end = begin + nr_sorted_png_map;
419 LATTEST(sorted(begin, end));
421 PngMap const * const it = find_if(begin, end, CompareKey(name));
425 png_name = it->value;
428 png_name.replace('_', "underscore");
429 png_name.replace(' ', '_');
431 // This way we can have "math-delim { }" on the toolbar.
432 png_name.replace('(', "lparen");
433 png_name.replace(')', "rparen");
434 png_name.replace('[', "lbracket");
435 png_name.replace(']', "rbracket");
436 png_name.replace('{', "lbrace");
437 png_name.replace('}', "rbrace");
438 png_name.replace('|', "bars");
439 png_name.replace(',', "thinspace");
440 png_name.replace(':', "mediumspace");
441 png_name.replace(';', "thickspace");
442 png_name.replace('!', "negthinspace");
445 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
446 << "Looking for math PNG called \"" << png_name << '"');
453 QString themeIconName(QString const & action)
455 PngMap const * const begin = sorted_theme_icon_map;
456 PngMap const * const end = begin + nr_sorted_theme_icon_map;
457 LASSERT(sorted(begin, end), /**/);
459 PngMap const * const it = find_if(begin, end, CompareKey(action));
467 QString iconName(FuncRequest const & f, bool unknown)
469 initializeResources();
473 switch (f.action()) {
474 case LFUN_MATH_INSERT:
475 if (!f.argument().empty()) {
477 name1 = findPng(toqstr(f.argument()).mid(1));
480 case LFUN_MATH_DELIM:
481 case LFUN_MATH_BIGDELIM:
483 name1 = findPng(toqstr(f.argument()));
487 name1 = toqstr(f.argument());
489 case LFUN_COMMAND_ALTERNATIVES: {
490 // use the first of the alternative commands
492 docstring dummy = split(f.argument(), firstcom, ';');
493 name1 = toqstr(firstcom);
494 // FIXME: we should rename the icons to tabular-xxx instead of
495 // "tabular-feature-xxx"
496 name1.replace("inset-modify tabular", "tabular-feature");
497 name1.replace(' ', '_');
500 case LFUN_INSET_MODIFY: {
501 // FIXME: we should rename the icons to tabular-xxx instead of
502 // "tabular-feature-xxx" and generalize this naming to all
503 // insets, not to tabular using ones.
505 string const command = split(to_utf8(f.argument()), inset_name, ' ');
506 if (insetCode(inset_name) == TABULAR_CODE) {
507 name1 = "tabular-feature "+ toqstr(command);
508 name1.replace(' ', '_');
513 name2 = toqstr(lyxaction.getActionName(f.action()));
516 if (!f.argument().empty()) {
517 name1 = name2 + ' ' + toqstr(f.argument());
518 name1.replace(' ', '_');
519 name1.replace('\\', "backslash");
523 QStringList imagedirs;
524 imagedirs << "images/" << "images/ipa/";
525 search_mode mode = theGuiApp()->imageSearchMode();
526 for (int i = 0; i < imagedirs.size(); ++i) {
527 QString imagedir = imagedirs.at(i) + path;
528 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
530 return toqstr(fname.absFileName());
532 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
534 return toqstr(fname.absFileName());
537 path = ":/images/" + path;
540 LYXERR0("Directory " << path << " not found in resource!");
543 if (res.exists(name1 + ".svgz"))
544 return path + name1 + ".svgz";
545 else if (res.exists(name1 + ".png"))
546 return path + name1 + ".png";
548 if (res.exists(name2 + ".svgz"))
549 return path + name2 + ".svgz";
550 else if (res.exists(name2 + ".png"))
551 return path + name2 + ".png";
553 LYXERR(Debug::GUI, "Cannot find icon with filename "
554 << "\"" << name1 << ".{svgz,png}\""
556 << "\"" << name2 << ".{svgz,png}\""
558 << lyxaction.getActionName(f.action())
559 << '(' << to_utf8(f.argument()) << ")\"");
562 QString imagedir = "images/";
563 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
565 return toqstr(fname.absFileName());
566 return QString(":/images/unknown.png");
572 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
575 QString imagedir = path;
576 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
577 QString fpath = toqstr(fname.absFileName());
579 if (pixmap.load(fpath)) {
582 QStringList exts = ext.split(",");
583 fpath = ":/" + path + name + ".";
584 for (int i = 0; i < exts.size(); ++i) {
585 if (pixmap.load(fpath + exts.at(i)))
590 bool const list = ext.contains(",");
591 LYXERR0("Cannot load pixmap \""
592 << path << name << "." << (list ? "{" : "") << ext
593 << (list ? "}" : "") << "\", please verify resource system!");
598 QIcon getIcon(FuncRequest const & f, bool unknown)
600 #if (QT_VERSION >= 0x040600)
601 if (lyxrc.use_system_theme_icons) {
602 QString action = toqstr(lyxaction.getActionName(f.action()));
603 if (!f.argument().empty())
604 action += " " + toqstr(f.argument());
605 QString const theme_icon = themeIconName(action);
606 if (QIcon::hasThemeIcon(theme_icon))
607 return QIcon::fromTheme(theme_icon);
611 QString icon = iconName(f, unknown);
615 //LYXERR(Debug::GUI, "Found icon: " << icon);
617 if (!pm.load(icon)) {
618 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
626 ////////////////////////////////////////////////////////////////////////
628 // LyX server support code.
630 ////////////////////////////////////////////////////////////////////////
632 class SocketNotifier : public QSocketNotifier
635 /// connect a connection notification from the LyXServerSocket
636 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
637 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
641 /// The callback function
642 Application::SocketCallback func_;
646 ////////////////////////////////////////////////////////////////////////
648 // Mac specific stuff goes here...
650 ////////////////////////////////////////////////////////////////////////
652 class MenuTranslator : public QTranslator
655 MenuTranslator(QObject * parent)
656 : QTranslator(parent)
659 #if QT_VERSION >= 0x050000
660 virtual QString translate(const char * /* context */,
661 const char *sourceText,
662 const char * /* disambiguation */ = 0, int /* n */ = -1) const
664 QString translate(const char * /*context*/,
665 const char * sourceText,
666 const char * /*comment*/ = 0) const
669 string const s = sourceText;
670 if (s == N_("About %1") || s == N_("Preferences")
671 || s == N_("Reconfigure") || s == N_("Quit %1"))
679 // QMacPasteboardMimeGraphics can only be compiled on Mac.
681 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
684 QMacPasteboardMimeGraphics()
685 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
688 QString convertorName() { return "Graphics"; }
690 QString flavorFor(QString const & mime)
692 LYXERR(Debug::ACTION, "flavorFor " << mime);
693 if (mime == pdfMimeType())
694 return QLatin1String("com.adobe.pdf");
698 QString mimeFor(QString flav)
700 LYXERR(Debug::ACTION, "mimeFor " << flav);
701 if (flav == QLatin1String("com.adobe.pdf"))
702 return pdfMimeType();
706 bool canConvert(QString const & mime, QString flav)
708 return mimeFor(flav) == mime;
711 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
715 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
719 QList<QByteArray> convertFromMime(QString const & /*mime*/,
720 QVariant data, QString /*flav*/)
722 QList<QByteArray> ret;
723 ret.append(data.toByteArray());
729 ///////////////////////////////////////////////////////////////
731 // You can find more platform specific stuff at the end of this file...
733 ///////////////////////////////////////////////////////////////
735 ////////////////////////////////////////////////////////////////////////
736 // Windows specific stuff goes here...
738 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
739 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
740 // QWindowsMimeMetafile can only be compiled on Windows.
742 static FORMATETC cfFromMime(QString const & mimetype)
745 if (mimetype == emfMimeType()) {
746 formatetc.cfFormat = CF_ENHMETAFILE;
747 formatetc.tymed = TYMED_ENHMF;
748 } else if (mimetype == wmfMimeType()) {
749 formatetc.cfFormat = CF_METAFILEPICT;
750 formatetc.tymed = TYMED_MFPICT;
753 formatetc.dwAspect = DVASPECT_CONTENT;
754 formatetc.lindex = -1;
759 class QWindowsMimeMetafile : public QWINDOWSMIME {
761 QWindowsMimeMetafile() {}
763 bool canConvertFromMime(FORMATETC const & formatetc,
764 QMimeData const * mimedata) const
769 bool canConvertToMime(QString const & mimetype,
770 IDataObject * pDataObj) const
772 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
774 FORMATETC formatetc = cfFromMime(mimetype);
775 return pDataObj->QueryGetData(&formatetc) == S_OK;
778 bool convertFromMime(FORMATETC const & formatetc,
779 const QMimeData * mimedata, STGMEDIUM * pmedium) const
784 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
785 QVariant::Type preferredType) const
788 if (!canConvertToMime(mimetype, pDataObj))
791 FORMATETC formatetc = cfFromMime(mimetype);
793 if (pDataObj->GetData(&formatetc, &s) != S_OK)
797 if (s.tymed == TYMED_ENHMF) {
798 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
799 data.resize(dataSize);
800 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
801 (LPBYTE)data.data());
802 } else if (s.tymed == TYMED_MFPICT) {
803 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
804 data.resize(dataSize);
805 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
806 (LPBYTE)data.data());
809 ReleaseStgMedium(&s);
815 QVector<FORMATETC> formatsForMime(QString const & mimetype,
816 QMimeData const * mimedata) const
818 QVector<FORMATETC> formats;
819 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
820 formats += cfFromMime(mimetype);
824 QString mimeForFormat(FORMATETC const & formatetc) const
826 switch (formatetc.cfFormat) {
828 return emfMimeType();
829 case CF_METAFILEPICT:
830 return wmfMimeType();
840 /// Allows to check whether ESC was pressed during a long operation
841 class KeyChecker : public QObject {
846 KeyChecker() : pressed_(false), started_(false) {}
849 QCoreApplication::instance()->installEventFilter(this);
854 QCoreApplication::instance()->removeEventFilter(this);
858 QCoreApplication::processEvents();
861 bool started() const {
864 bool eventFilter(QObject *obj, QEvent *event) {
865 LYXERR(Debug::ACTION, "Event Type: " << event->type());
866 switch (event->type()) {
870 case QEvent::UpdateRequest:
871 case QEvent::CursorChange:
872 case QEvent::ActionChanged:
873 case QEvent::EnabledChange:
874 case QEvent::SockAct:
877 case QEvent::ToolTipChange:
878 case QEvent::LayoutRequest:
879 case QEvent::MetaCall:
880 return QObject::eventFilter(obj, event);
882 // FIXME Blocking all these events is a bad idea.
883 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
884 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
892 ////////////////////////////////////////////////////////////////////////
893 // GuiApplication::Private definition and implementation.
894 ////////////////////////////////////////////////////////////////////////
896 struct GuiApplication::Private
898 Private(): language_model_(0), meta_fake_bit(NoModifier),
901 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
902 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
903 /// WMF Mime handler for Windows clipboard.
904 wmf_mime_ = new QWindowsMimeMetafile;
907 initKeySequences(&theTopLevelKeymap());
910 void initKeySequences(KeyMap * kb)
912 keyseq = KeySequence(kb, kb);
913 cancel_meta_seq = KeySequence(kb, kb);
917 QSortFilterProxyModel * language_model_;
919 GuiClipboard clipboard_;
921 GuiSelection selection_;
923 FontLoader font_loader_;
925 ColorCache color_cache_;
927 QTranslator qt_trans_;
929 QHash<int, SocketNotifier *> socket_notifiers_;
933 /// The global instance
936 /// this timer is used for any regular events one wants to
937 /// perform. at present it is used to check if forked processes
939 QTimer general_timer_;
941 /// delayed FuncRequests
942 std::queue<FuncRequest> func_request_queue_;
947 KeySequence cancel_meta_seq;
949 KeyModifier meta_fake_bit;
951 /// Multiple views container.
953 * Warning: This must not be a smart pointer as the destruction of the
954 * object is handled by Qt when the view is closed
955 * \sa Qt::WA_DeleteOnClose attribute.
957 QHash<int, GuiView *> views_;
959 /// Only used on mac.
960 QMenuBar * global_menubar_;
963 /// Linkback mime handler for MacOSX.
964 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
967 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
968 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
969 /// WMF Mime handler for Windows clipboard.
970 QWindowsMimeMetafile * wmf_mime_;
974 /// Allows to check whether ESC was pressed during a long operation
975 KeyChecker key_checker_;
979 GuiApplication * guiApp;
981 GuiApplication::~GuiApplication()
984 closeAllLinkBackLinks();
990 GuiApplication::GuiApplication(int & argc, char ** argv)
991 : QApplication(argc, argv), current_view_(0),
992 d(new GuiApplication::Private)
994 QString app_name = "LyX";
995 QCoreApplication::setOrganizationName(app_name);
996 QCoreApplication::setOrganizationDomain("lyx.org");
997 QCoreApplication::setApplicationName(lyx_package);
999 qsrand(QDateTime::currentDateTime().toTime_t());
1001 // Install translator for GUI elements.
1002 installTranslator(&d->qt_trans_);
1005 // Enable reception of XCB events.
1006 installNativeEventFilter(this);
1009 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1010 // lyxrc setting for this in order to let the application stay resident.
1011 // But then we need some kind of dock icon, at least on Windows.
1013 if (lyxrc.quit_on_last_window_closed)
1014 setQuitOnLastWindowClosed(false);
1017 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1018 // seems to be the default case for applications like LyX.
1019 setQuitOnLastWindowClosed(false);
1020 // This allows to translate the strings that appear in the LyX menu.
1021 /// A translator suitable for the entries in the LyX menu.
1022 /// Only needed with Qt/Mac.
1023 installTranslator(new MenuTranslator(this));
1028 #if defined(Q_WS_X11) || defined(QPA_XCB)
1029 // doubleClickInterval() is 400 ms on X11 which is just too long.
1030 // On Windows and Mac OS X, the operating system's value is used.
1031 // On Microsoft Windows, calling this function sets the double
1032 // click interval for all applications. So we don't!
1033 QApplication::setDoubleClickInterval(300);
1036 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1038 // needs to be done before reading lyxrc
1040 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1044 // Set the cache to 5120 kilobytes which corresponds to screen size of
1045 // 1280 by 1024 pixels with a color depth of 32 bits.
1046 QPixmapCache::setCacheLimit(5120);
1048 // Initialize RC Fonts
1049 if (lyxrc.roman_font_name.empty())
1050 lyxrc.roman_font_name = fromqstr(romanFontName());
1052 if (lyxrc.sans_font_name.empty())
1053 lyxrc.sans_font_name = fromqstr(sansFontName());
1055 if (lyxrc.typewriter_font_name.empty())
1056 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1058 d->general_timer_.setInterval(500);
1059 connect(&d->general_timer_, SIGNAL(timeout()),
1060 this, SLOT(handleRegularEvents()));
1061 d->general_timer_.start();
1063 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1064 // This is clearly not enough in a time where we use threads for
1065 // document preview and/or export. 20 should be OK.
1066 QThreadPool::globalInstance()->setMaxThreadCount(20);
1070 GuiApplication * theGuiApp()
1072 return dynamic_cast<GuiApplication *>(theApp());
1076 double GuiApplication::pixelRatio() const
1078 #if QT_VERSION >= 0x050000
1079 return devicePixelRatio();
1086 void GuiApplication::clearSession()
1093 docstring Application::iconName(FuncRequest const & f, bool unknown)
1095 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1099 docstring Application::mathIcon(docstring const & c)
1101 return qstring_to_ucs4(findPng(toqstr(c)));
1105 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1109 BufferView * bv = 0;
1110 BufferView * doc_bv = 0;
1112 if (cmd.action() == LFUN_NOACTION) {
1113 status.message(from_utf8(N_("Nothing to do")));
1114 status.setEnabled(false);
1117 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1118 status.setUnknown(true);
1119 status.message(from_utf8(N_("Unknown action")));
1120 status.setEnabled(false);
1123 // Does the GuiApplication know something?
1124 else if (getStatus(cmd, status)) { }
1126 // If we do not have a GuiView, then other functions are disabled
1127 else if (!current_view_)
1128 status.setEnabled(false);
1130 // Does the GuiView know something?
1131 else if (current_view_->getStatus(cmd, status)) { }
1133 // In LyX/Mac, when a dialog is open, the menus of the
1134 // application can still be accessed without giving focus to
1135 // the main window. In this case, we want to disable the menu
1136 // entries that are buffer or view-related.
1137 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1139 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1140 status.setEnabled(false);
1143 // If we do not have a BufferView, then other functions are disabled
1144 else if (!(bv = current_view_->currentBufferView()))
1145 status.setEnabled(false);
1147 // Does the current BufferView know something?
1148 else if (bv->getStatus(cmd, status)) { }
1150 // Does the current Buffer know something?
1151 else if (bv->buffer().getStatus(cmd, status)) { }
1153 // If we do not have a document BufferView, different from the
1154 // current BufferView, then other functions are disabled
1155 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1156 status.setEnabled(false);
1158 // Does the document Buffer know something?
1159 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1162 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1163 status.message(from_utf8(N_("Command not handled")));
1164 status.setEnabled(false);
1167 // the default error message if we disable the command
1168 if (!status.enabled() && status.message().empty())
1169 status.message(from_utf8(N_("Command disabled")));
1175 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1177 // I would really like to avoid having this switch and rather try to
1178 // encode this in the function itself.
1179 // -- And I'd rather let an inset decide which LFUNs it is willing
1180 // to handle (Andre')
1182 switch (cmd.action()) {
1184 // This could be used for the no-GUI version. The GUI version is handled in
1185 // GuiView::getStatus(). See above.
1187 case LFUN_BUFFER_WRITE:
1188 case LFUN_BUFFER_WRITE_AS: {
1189 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1190 enable = b && (b->isUnnamed() || !b->isClean());
1195 case LFUN_BOOKMARK_GOTO: {
1196 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1197 enable = theSession().bookmarks().isValid(num);
1201 case LFUN_BOOKMARK_CLEAR:
1202 enable = theSession().bookmarks().hasValid();
1205 // this one is difficult to get right. As a half-baked
1206 // solution, we consider only the first action of the sequence
1207 case LFUN_COMMAND_SEQUENCE: {
1208 // argument contains ';'-terminated commands
1209 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1210 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1211 func.setOrigin(cmd.origin());
1212 flag = getStatus(func);
1216 // we want to check if at least one of these is enabled
1217 case LFUN_COMMAND_ALTERNATIVES: {
1218 // argument contains ';'-terminated commands
1219 string arg = to_utf8(cmd.argument());
1220 while (!arg.empty()) {
1222 arg = split(arg, first, ';');
1223 FuncRequest func(lyxaction.lookupFunc(first));
1224 func.setOrigin(cmd.origin());
1225 flag = getStatus(func);
1226 // if this one is enabled, the whole thing is
1235 string name = to_utf8(cmd.argument());
1236 if (theTopLevelCmdDef().lock(name, func)) {
1237 func.setOrigin(cmd.origin());
1238 flag = getStatus(func);
1239 theTopLevelCmdDef().release(name);
1241 // catch recursion or unknown command
1242 // definition. all operations until the
1243 // recursion or unknown command definition
1244 // occurs are performed, so set the state to
1251 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1253 case LFUN_PREFERENCES_SAVE:
1254 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1255 case LFUN_DEBUG_LEVEL_SET:
1256 // these are handled in our dispatch()
1259 case LFUN_WINDOW_CLOSE:
1260 enable = d->views_.size() > 0;
1263 case LFUN_BUFFER_NEW:
1264 case LFUN_BUFFER_NEW_TEMPLATE:
1265 case LFUN_FILE_OPEN:
1266 case LFUN_HELP_OPEN:
1267 case LFUN_SCREEN_FONT_UPDATE:
1268 case LFUN_SET_COLOR:
1269 case LFUN_WINDOW_NEW:
1271 case LFUN_LYXRC_APPLY:
1272 case LFUN_COMMAND_PREFIX:
1274 case LFUN_META_PREFIX:
1275 case LFUN_RECONFIGURE:
1276 case LFUN_SERVER_GET_FILENAME:
1277 case LFUN_SERVER_NOTIFY:
1281 case LFUN_BUFFER_FORALL: {
1282 if (theBufferList().empty()) {
1283 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1284 flag.setEnabled(false);
1288 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1289 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1290 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1291 flag.setEnabled(false);
1296 case LFUN_DIALOG_SHOW: {
1297 string const name = cmd.getArg(0);
1298 return name == "aboutlyx"
1300 || name == "texinfo"
1301 || name == "progress"
1302 || name == "compare";
1310 flag.setEnabled(false);
1314 /// make a post-dispatch status message
1315 static docstring makeDispatchMessage(docstring const & msg,
1316 FuncRequest const & cmd)
1318 const bool verbose = (cmd.origin() == FuncRequest::MENU
1319 || cmd.origin() == FuncRequest::TOOLBAR
1320 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1322 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1323 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1327 docstring dispatch_msg = msg;
1328 if (!dispatch_msg.empty())
1329 dispatch_msg += ' ';
1331 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1333 bool argsadded = false;
1335 if (!cmd.argument().empty()) {
1336 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1337 comname += ' ' + cmd.argument();
1341 docstring const shortcuts = theTopLevelKeymap().
1342 printBindings(cmd, KeySequence::ForGui);
1344 if (!shortcuts.empty())
1345 comname += ": " + shortcuts;
1346 else if (!argsadded && !cmd.argument().empty())
1347 comname += ' ' + cmd.argument();
1349 if (!comname.empty()) {
1350 comname = rtrim(comname);
1351 dispatch_msg += '(' + rtrim(comname) + ')';
1353 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1354 return dispatch_msg;
1358 void GuiApplication::dispatch(FuncRequest const & cmd)
1360 Buffer * buffer = 0;
1361 if (current_view_ && current_view_->currentBufferView()) {
1362 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1363 buffer = ¤t_view_->currentBufferView()->buffer();
1365 buffer->undo().beginUndoGroup();
1369 // redraw the screen at the end (first of the two drawing steps).
1370 // This is done unless explicitly requested otherwise
1371 dr.screenUpdate(Update::FitCursor);
1373 updateCurrentView(cmd, dr);
1375 // the buffer may have been closed by one action
1376 if (theBufferList().isLoaded(buffer))
1377 buffer->undo().endUndoGroup();
1381 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1386 BufferView * bv = current_view_->currentBufferView();
1388 if (dr.needBufferUpdate()) {
1389 bv->cursor().clearBufferUpdate();
1390 bv->buffer().updateBuffer();
1392 // BufferView::update() updates the ViewMetricsInfo and
1393 // also initializes the position cache for all insets in
1394 // (at least partially) visible top-level paragraphs.
1395 // We will redraw the screen only if needed.
1396 bv->processUpdateFlags(dr.screenUpdate());
1398 // Do we have a selection?
1399 theSelection().haveSelection(bv->cursor().selection());
1402 current_view_->restartCursor();
1404 if (dr.needMessageUpdate()) {
1405 // Some messages may already be translated, so we cannot use _()
1406 current_view_->message(makeDispatchMessage(
1407 translateIfPossible(dr.message()), cmd));
1412 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1413 bool switchToBuffer)
1415 if (!theSession().bookmarks().isValid(idx))
1417 BookmarksSection::Bookmark const & bm =
1418 theSession().bookmarks().bookmark(idx);
1419 LASSERT(!bm.filename.empty(), return);
1420 string const file = bm.filename.absFileName();
1421 // if the file is not opened, open it.
1422 if (!theBufferList().exists(bm.filename)) {
1424 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1428 // open may fail, so we need to test it again
1429 if (!theBufferList().exists(bm.filename))
1432 // bm can be changed when saving
1433 BookmarksSection::Bookmark tmp = bm;
1435 // Special case idx == 0 used for back-from-back jump navigation
1437 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1439 // if the current buffer is not that one, switch to it.
1440 BufferView * doc_bv = current_view_ ?
1441 current_view_->documentBufferView() : 0;
1442 Cursor const old = doc_bv->cursor();
1443 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1444 if (switchToBuffer) {
1445 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1448 doc_bv = current_view_->documentBufferView();
1453 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1454 if (!doc_bv->moveToPosition(
1455 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1458 Cursor & cur = doc_bv->cursor();
1460 notifyCursorLeavesOrEnters(old, cur);
1466 // Cursor jump succeeded!
1467 pit_type new_pit = cur.pit();
1468 pos_type new_pos = cur.pos();
1469 int new_id = cur.paragraph().id();
1471 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1472 // see http://www.lyx.org/trac/ticket/3092
1473 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1474 || bm.top_id != new_id) {
1475 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1476 new_pit, new_pos, new_id);
1480 // This function runs "configure" and then rereads lyx.defaults to
1481 // reconfigure the automatic settings.
1482 void GuiApplication::reconfigure(string const & option)
1484 // emit message signal.
1486 current_view_->message(_("Running configure..."));
1488 // Run configure in user lyx directory
1489 string const lock_file = package().getConfigureLockName();
1490 int fd = fileLock(lock_file.c_str());
1491 int const ret = package().reconfigureUserLyXDir(option);
1492 // emit message signal.
1494 current_view_->message(_("Reloading configuration..."));
1495 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1496 // Re-read packages.lst
1497 LaTeXPackages::getAvailable();
1498 fileUnlock(fd, lock_file.c_str());
1501 Alert::information(_("System reconfiguration failed"),
1502 _("The system reconfiguration has failed.\n"
1503 "Default textclass is used but LyX may\n"
1504 "not be able to work properly.\n"
1505 "Please reconfigure again if needed."));
1507 Alert::information(_("System reconfigured"),
1508 _("The system has been reconfigured.\n"
1509 "You need to restart LyX to make use of any\n"
1510 "updated document class specifications."));
1513 void GuiApplication::validateCurrentView()
1515 if (!d->views_.empty() && !current_view_) {
1516 // currently at least one view exists but no view has the focus.
1517 // choose the last view to make it current.
1518 // a view without any open document is preferred.
1519 GuiView * candidate = 0;
1520 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1521 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1522 for (; it != end; ++it) {
1524 if (!candidate->documentBufferView())
1527 setCurrentView(candidate);
1531 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1533 string const argument = to_utf8(cmd.argument());
1534 FuncCode const action = cmd.action();
1536 LYXERR(Debug::ACTION, "cmd: " << cmd);
1538 // we have not done anything wrong yet.
1541 FuncStatus const flag = getStatus(cmd);
1542 if (!flag.enabled()) {
1543 // We cannot use this function here
1544 LYXERR(Debug::ACTION, "action "
1545 << lyxaction.getActionName(action)
1546 << " [" << action << "] is disabled at this location");
1547 dr.setMessage(flag.message());
1549 dr.dispatched(false);
1550 dr.screenUpdate(Update::None);
1551 dr.clearBufferUpdate();
1555 if (cmd.origin() == FuncRequest::LYXSERVER) {
1556 if (current_view_ && current_view_->currentBufferView())
1557 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1558 // we will also need to redraw the screen at the end
1559 dr.screenUpdate(Update::FitCursor);
1562 // Assumes that the action will be dispatched.
1563 dr.dispatched(true);
1565 switch (cmd.action()) {
1567 case LFUN_WINDOW_NEW:
1568 createView(toqstr(cmd.argument()));
1571 case LFUN_WINDOW_CLOSE:
1572 // update bookmark pit of the current buffer before window close
1573 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1574 gotoBookmark(i+1, false, false);
1575 // clear the last opened list, because
1576 // maybe this will end the session
1577 theSession().lastOpened().clear();
1578 // check for valid current_view_
1579 validateCurrentView();
1581 current_view_->closeScheduled();
1585 // quitting is triggered by the gui code
1586 // (leaving the event loop).
1588 current_view_->message(from_utf8(N_("Exiting.")));
1589 if (closeAllViews())
1593 case LFUN_SCREEN_FONT_UPDATE: {
1594 // handle the screen font changes.
1595 d->font_loader_.update();
1596 // Backup current_view_
1597 GuiView * view = current_view_;
1598 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1599 // to skip the refresh.
1601 theBufferList().changed(false);
1602 // Restore current_view_
1603 current_view_ = view;
1607 case LFUN_BUFFER_NEW:
1608 validateCurrentView();
1609 if (d->views_.empty()
1610 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1611 createView(QString(), false); // keep hidden
1612 current_view_->newDocument(to_utf8(cmd.argument()), false);
1613 current_view_->show();
1614 setActiveWindow(current_view_);
1616 current_view_->newDocument(to_utf8(cmd.argument()), false);
1620 case LFUN_BUFFER_NEW_TEMPLATE:
1621 validateCurrentView();
1622 if (d->views_.empty()
1623 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1625 current_view_->newDocument(to_utf8(cmd.argument()), true);
1626 if (!current_view_->documentBufferView())
1627 current_view_->close();
1629 current_view_->newDocument(to_utf8(cmd.argument()), true);
1633 case LFUN_FILE_OPEN: {
1634 validateCurrentView();
1635 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1636 string const fname = to_utf8(cmd.argument());
1637 bool const is_open = FileName::isAbsolute(fname)
1638 && theBufferList().getBuffer(FileName(fname));
1639 if (d->views_.empty()
1640 || (!lyxrc.open_buffers_in_tabs
1641 && current_view_->documentBufferView() != 0
1643 // We want the ui session to be saved per document and not per
1644 // window number. The filename crc is a good enough identifier.
1645 boost::crc_32_type crc;
1646 crc = for_each(fname.begin(), fname.end(), crc);
1647 createView(crc.checksum());
1648 current_view_->openDocument(fname);
1649 if (current_view_ && !current_view_->documentBufferView())
1650 current_view_->close();
1652 current_view_->openDocument(fname);
1656 case LFUN_HELP_OPEN: {
1657 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1658 if (current_view_ == 0)
1660 string const arg = to_utf8(cmd.argument());
1662 current_view_->message(_("Missing argument"));
1665 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1667 fname = i18nLibFileSearch("examples", arg, "lyx");
1669 if (fname.empty()) {
1670 lyxerr << "LyX: unable to find documentation file `"
1671 << arg << "'. Bad installation?" << endl;
1674 current_view_->message(bformat(_("Opening help file %1$s..."),
1675 makeDisplayPath(fname.absFileName())));
1676 Buffer * buf = current_view_->loadDocument(fname, false);
1678 #ifndef DEVEL_VERSION
1680 buf->setReadonly(true);
1687 case LFUN_SET_COLOR: {
1689 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1690 if (lyx_name.empty() || x11_name.empty()) {
1692 current_view_->message(
1693 _("Syntax: set-color <lyx_name> <x11_name>"));
1698 // FIXME: The graphics cache no longer has a changeDisplay method.
1699 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1700 bool const graphicsbg_changed =
1701 lyx_name == graphicsbg && x11_name != graphicsbg;
1702 if (graphicsbg_changed)
1703 graphics::GCache::get().changeDisplay(true);
1706 if (!lcolor.setColor(lyx_name, x11_name)) {
1708 current_view_->message(
1709 bformat(_("Set-color \"%1$s\" failed "
1710 "- color is undefined or "
1711 "may not be redefined"),
1712 from_utf8(lyx_name)));
1715 // Make sure we don't keep old colors in cache.
1716 d->color_cache_.clear();
1720 case LFUN_LYXRC_APPLY: {
1721 // reset active key sequences, since the bindings
1722 // are updated (bug 6064)
1724 LyXRC const lyxrc_orig = lyxrc;
1726 istringstream ss(to_utf8(cmd.argument()));
1727 bool const success = lyxrc.read(ss);
1730 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1731 << "Unable to read lyxrc data"
1736 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1738 // If the request comes from the minibuffer, then we can't reset
1739 // the GUI, since that would destory the minibuffer itself and
1740 // cause a crash, since we are currently in one of the methods of
1741 // GuiCommandBuffer. See bug #8540.
1742 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1745 // FIXME Unfortunately, that leaves a bug here, since we cannot
1746 // reset the GUI in this case. If the changes to lyxrc affected the
1747 // UI, then, nothing would happen. This seems fairly unlikely, but
1748 // it definitely is a bug.
1753 case LFUN_COMMAND_PREFIX:
1754 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1759 d->meta_fake_bit = NoModifier;
1760 GuiView * gv = currentView();
1761 if (gv && gv->currentBufferView())
1762 // cancel any selection
1763 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1764 dr.setMessage(from_ascii(N_("Cancel")));
1767 case LFUN_META_PREFIX:
1768 d->meta_fake_bit = AltModifier;
1769 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1772 // --- Menus -----------------------------------------------
1773 case LFUN_RECONFIGURE:
1774 // argument is any additional parameter to the configure.py command
1775 reconfigure(to_utf8(cmd.argument()));
1778 // --- lyxserver commands ----------------------------
1779 case LFUN_SERVER_GET_FILENAME: {
1780 if (current_view_ && current_view_->documentBufferView()) {
1781 docstring const fname = from_utf8(
1782 current_view_->documentBufferView()->buffer().absFileName());
1783 dr.setMessage(fname);
1784 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1786 dr.setMessage(docstring());
1787 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1792 case LFUN_SERVER_NOTIFY: {
1793 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1794 dr.setMessage(dispatch_buffer);
1795 theServer().notifyClient(to_utf8(dispatch_buffer));
1799 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1800 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1806 string rest = split(argument, countstr, ' ');
1807 istringstream is(countstr);
1810 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1811 for (int i = 0; i < count; ++i)
1812 dispatch(lyxaction.lookupFunc(rest));
1816 case LFUN_COMMAND_SEQUENCE: {
1817 // argument contains ';'-terminated commands
1818 string arg = argument;
1819 // FIXME: this LFUN should also work without any view.
1820 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1821 ? &(current_view_->documentBufferView()->buffer()) : 0;
1823 buffer->undo().beginUndoGroup();
1824 while (!arg.empty()) {
1826 arg = split(arg, first, ';');
1827 FuncRequest func(lyxaction.lookupFunc(first));
1828 func.setOrigin(cmd.origin());
1831 // the buffer may have been closed by one action
1832 if (theBufferList().isLoaded(buffer))
1833 buffer->undo().endUndoGroup();
1837 case LFUN_BUFFER_FORALL: {
1838 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1840 map<Buffer *, GuiView *> views_lVisible;
1841 map<GuiView *, Buffer *> activeBuffers;
1843 QList<GuiView *> allViews = d->views_.values();
1845 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1846 // and on which buffer is active in each view.
1847 Buffer * const last = theBufferList().last();
1848 foreach (GuiView * view, allViews) {
1849 // all of the buffers might be locally hidden. That is, there is no active buffer.
1850 if (!view || !view->currentBufferView())
1851 activeBuffers[view] = 0;
1853 activeBuffers[view] = &view->currentBufferView()->buffer();
1855 // find out if each is locally visible or locally hidden.
1856 // we don't use a for loop as the buffer list cycles.
1857 Buffer * b = theBufferList().first();
1859 bool const locallyVisible = view && view->workArea(*b);
1860 if (locallyVisible) {
1861 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1862 // only need to overwrite/add if we don't already know a buffer is globally
1863 // visible or we do know but we would prefer to dispatch LFUN from the
1864 // current view because of cursor position issues.
1865 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1866 views_lVisible[b] = view;
1870 b = theBufferList().next(b);
1874 GuiView * const homeView = currentView();
1875 Buffer * b = theBufferList().first();
1876 Buffer * nextBuf = 0;
1877 int numProcessed = 0;
1880 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1882 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1884 // first change to a view where b is locally visible, preferably current_view_.
1885 GuiView * const vLv = views_lVisible[b];
1887 lyx::dispatch(funcToRun);
1895 // put things back to how they were (if possible).
1896 foreach (GuiView * view, allViews) {
1897 Buffer * originalBuf = activeBuffers[view];
1898 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1899 if (theBufferList().isLoaded(originalBuf))
1900 view->setBuffer(originalBuf);
1902 homeView->setFocus();
1904 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1908 case LFUN_COMMAND_ALTERNATIVES: {
1909 // argument contains ';'-terminated commands
1910 string arg = argument;
1911 while (!arg.empty()) {
1913 arg = split(arg, first, ';');
1914 FuncRequest func(lyxaction.lookupFunc(first));
1915 func.setOrigin(cmd.origin());
1916 FuncStatus const stat = getStatus(func);
1917 if (stat.enabled()) {
1927 if (theTopLevelCmdDef().lock(argument, func)) {
1928 func.setOrigin(cmd.origin());
1930 theTopLevelCmdDef().release(argument);
1932 if (func.action() == LFUN_UNKNOWN_ACTION) {
1933 // unknown command definition
1934 lyxerr << "Warning: unknown command definition `"
1938 // recursion detected
1939 lyxerr << "Warning: Recursion in the command definition `"
1940 << argument << "' detected"
1947 case LFUN_PREFERENCES_SAVE:
1948 lyxrc.write(support::makeAbsPath("preferences",
1949 package().user_support().absFileName()), false);
1952 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1953 string const fname = addName(addPath(package().user_support().absFileName(),
1954 "templates/"), "defaults.lyx");
1955 Buffer defaults(fname);
1957 istringstream ss(argument);
1962 // We need to make sure that, after we recreat the DocumentClass,
1963 // which we do in readHeader, we apply it to the document itself.
1964 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1965 int const unknown_tokens = defaults.readHeader(lex);
1966 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1968 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1969 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1971 if (unknown_tokens != 0) {
1972 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1973 << unknown_tokens << " unknown token"
1974 << (unknown_tokens == 1 ? "" : "s")
1978 if (defaults.writeFile(FileName(defaults.absFileName())))
1979 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1980 makeDisplayPath(fname)));
1983 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1988 case LFUN_BOOKMARK_GOTO:
1989 // go to bookmark, open unopened file and switch to buffer if necessary
1990 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1991 dr.screenUpdate(Update::Force | Update::FitCursor);
1994 case LFUN_BOOKMARK_CLEAR:
1995 theSession().bookmarks().clear();
1998 case LFUN_DEBUG_LEVEL_SET:
1999 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2002 case LFUN_DIALOG_SHOW: {
2003 string const name = cmd.getArg(0);
2005 if ( name == "aboutlyx"
2007 || name == "texinfo"
2008 || name == "progress"
2009 || name == "compare")
2011 // work around: on Mac OS the application
2012 // is not terminated when closing the last view.
2013 // Create a new one to be able to dispatch the
2014 // LFUN_DIALOG_SHOW to this view.
2015 if (current_view_ == 0)
2021 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2024 current_view_->dispatch(cmd, dr);
2028 if (cmd.origin() == FuncRequest::LYXSERVER)
2029 updateCurrentView(cmd, dr);
2033 docstring GuiApplication::viewStatusMessage()
2035 // When meta-fake key is pressed, show the key sequence so far + "M-".
2036 if (d->meta_fake_bit != NoModifier)
2037 return d->keyseq.print(KeySequence::ForGui) + "M-";
2039 // Else, when a non-complete key sequence is pressed,
2040 // show the available options.
2041 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2042 return d->keyseq.printOptions(true);
2048 void GuiApplication::handleKeyFunc(FuncCode action)
2052 if (d->keyseq.length())
2054 GuiView * gv = currentView();
2055 LASSERT(gv && gv->currentBufferView(), return);
2056 BufferView * bv = gv->currentBufferView();
2057 bv->getIntl().getTransManager().deadkey(
2058 c, get_accent(action).accent, bv->cursor().innerText(),
2060 // Need to clear, in case the minibuffer calls these
2063 // copied verbatim from do_accent_char
2064 bv->cursor().resetAnchor();
2068 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2070 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2072 // Do nothing if we have nothing (JMarc)
2073 if (!keysym.isOK()) {
2074 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2076 current_view_->restartCursor();
2080 if (keysym.isModifier()) {
2082 current_view_->restartCursor();
2086 char_type encoded_last_key = keysym.getUCSEncoded();
2088 // Do a one-deep top-level lookup for
2089 // cancel and meta-fake keys. RVDK_PATCH_5
2090 d->cancel_meta_seq.reset();
2092 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2093 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2095 // When not cancel or meta-fake, do the normal lookup.
2096 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2097 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2098 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2099 // remove Caps Lock and Mod2 as a modifiers
2100 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2101 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2104 // Dont remove this unless you know what you are doing.
2105 d->meta_fake_bit = NoModifier;
2107 // Can this happen now ?
2108 if (func.action() == LFUN_NOACTION)
2109 func = FuncRequest(LFUN_COMMAND_PREFIX);
2111 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2112 << d->keyseq.print(KeySequence::Portable) << ']');
2114 // already here we know if it any point in going further
2115 // why not return already here if action == -1 and
2116 // num_bytes == 0? (Lgb)
2118 if (d->keyseq.length() > 1 && current_view_)
2119 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2122 // Maybe user can only reach the key via holding down shift.
2123 // Let's see. But only if shift is the only modifier
2124 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2125 LYXERR(Debug::KEY, "Trying without shift");
2126 func = d->keyseq.addkey(keysym, NoModifier);
2127 LYXERR(Debug::KEY, "Action now " << func.action());
2130 if (func.action() == LFUN_UNKNOWN_ACTION) {
2131 // We didn't match any of the key sequences.
2132 // See if it's normal insertable text not already
2133 // covered by a binding
2134 if (keysym.isText() && d->keyseq.length() == 1) {
2135 // Non-printable characters (such as ASCII control characters)
2136 // must not be inserted (#5704)
2137 if (!isPrintable(encoded_last_key)) {
2138 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2139 current_view_->restartCursor();
2142 // If a non-Shift Modifier is used we have a non-bound key sequence
2143 // (such as Alt+j = j). This should be omitted (#5575).
2144 // On Windows, AltModifier and ControlModifier are both
2145 // set when AltGr is pressed. Therefore, in order to not
2146 // break AltGr-bound symbols (see #5575 for details),
2147 // unbound Ctrl+Alt key sequences are allowed.
2148 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2149 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2150 && !(state & AltModifier && state & ControlModifier)
2153 current_view_->message(_("Unknown function."));
2154 current_view_->restartCursor();
2157 // Since all checks above were passed, we now really have text that
2158 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2159 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2161 LYXERR(Debug::KEY, "isText() is true, inserting.");
2162 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2164 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2165 if (current_view_) {
2166 current_view_->message(_("Unknown function."));
2167 current_view_->restartCursor();
2173 if (func.action() == LFUN_SELF_INSERT) {
2174 if (encoded_last_key != 0) {
2175 docstring const arg(1, encoded_last_key);
2176 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2177 FuncRequest::KEYBOARD));
2178 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2181 processFuncRequest(func);
2185 void GuiApplication::processFuncRequest(FuncRequest const & func)
2187 lyx::dispatch(func);
2191 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2193 addToFuncRequestQueue(func);
2194 processFuncRequestQueueAsync();
2198 void GuiApplication::processFuncRequestQueue()
2200 while (!d->func_request_queue_.empty()) {
2201 processFuncRequest(d->func_request_queue_.front());
2202 d->func_request_queue_.pop();
2207 void GuiApplication::processFuncRequestQueueAsync()
2209 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2213 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2215 d->func_request_queue_.push(func);
2219 void GuiApplication::resetGui()
2221 // Set the language defined by the user.
2225 if (!readUIFile(toqstr(lyxrc.ui_file)))
2226 // Gives some error box here.
2229 if (d->global_menubar_)
2230 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2232 QHash<int, GuiView *>::iterator it;
2233 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2236 gv->setLayoutDirection(layoutDirection());
2240 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2244 void GuiApplication::createView(int view_id)
2246 createView(QString(), true, view_id);
2250 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2253 // release the keyboard which might have been grabed by the global
2254 // menubar on Mac to catch shortcuts even without any GuiView.
2255 if (d->global_menubar_)
2256 d->global_menubar_->releaseKeyboard();
2260 while (d->views_.find(id) != d->views_.end())
2263 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2264 GuiView * view = new GuiView(id);
2266 d->views_[id] = view;
2270 setActiveWindow(view);
2273 if (!geometry_arg.isEmpty()) {
2274 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2278 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2279 re.indexIn(geometry_arg);
2280 w = re.cap(1).toInt();
2281 h = re.cap(2).toInt();
2282 x = re.cap(3).toInt();
2283 y = re.cap(4).toInt();
2284 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2285 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2286 // Set initial geometry such that we can get the frame size.
2287 view->setGeometry(x, y, w, h);
2288 int framewidth = view->geometry().x() - view->x();
2289 int titleheight = view->geometry().y() - view->y();
2290 // Negative displacements must be interpreted as distances
2291 // from the right or bottom screen borders.
2292 if (sx == '-' || sy == '-') {
2293 QRect rec = QApplication::desktop()->screenGeometry();
2295 x += rec.width() - w - framewidth;
2297 y += rec.height() - h - titleheight;
2298 view->setGeometry(x, y, w, h);
2300 // Make sure that the left and top frame borders are visible.
2301 if (view->x() < 0 || view->y() < 0) {
2306 view->setGeometry(x, y, w, h);
2314 Clipboard & GuiApplication::clipboard()
2316 return d->clipboard_;
2320 Selection & GuiApplication::selection()
2322 return d->selection_;
2326 FontLoader & GuiApplication::fontLoader()
2328 return d->font_loader_;
2332 Toolbars const & GuiApplication::toolbars() const
2334 return d->toolbars_;
2338 Toolbars & GuiApplication::toolbars()
2340 return d->toolbars_;
2344 Menus const & GuiApplication::menus() const
2350 Menus & GuiApplication::menus()
2356 QList<int> GuiApplication::viewIds() const
2358 return d->views_.keys();
2362 ColorCache & GuiApplication::colorCache()
2364 return d->color_cache_;
2368 int GuiApplication::exec()
2370 // asynchronously handle batch commands. This event will be in
2371 // the event queue in front of other asynchronous events. Hence,
2372 // we can assume in the latter that the gui is setup already.
2373 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2375 return QApplication::exec();
2379 void GuiApplication::exit(int status)
2381 QApplication::exit(status);
2385 void GuiApplication::setGuiLanguage()
2389 // install translation file for Qt built-in dialogs
2390 QString const language_name = QString("qt_") + theLocale.name();
2391 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2392 // Short-named translator can be loaded from a long name, but not the
2393 // opposite. Therefore, long name should be used without truncation.
2394 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2395 if (!d->qt_trans_.load(language_name,
2396 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2397 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2400 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2404 switch (theLocale.language()) {
2405 case QLocale::Arabic :
2406 case QLocale::Hebrew :
2407 case QLocale::Persian :
2408 case QLocale::Urdu :
2409 setLayoutDirection(Qt::RightToLeft);
2412 setLayoutDirection(Qt::LeftToRight);
2417 void GuiApplication::execBatchCommands()
2422 if (!readUIFile(toqstr(lyxrc.ui_file)))
2423 // Gives some error box here.
2427 #if QT_VERSION > 0x040600
2428 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2430 // Create the global default menubar which is shown for the dialogs
2431 // and if no GuiView is visible.
2432 // This must be done after the session was recovered to know the "last files".
2433 d->global_menubar_ = new QMenuBar(0);
2434 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2437 lyx::execBatchCommands();
2441 QAbstractItemModel * GuiApplication::languageModel()
2443 if (d->language_model_)
2444 return d->language_model_;
2446 QStandardItemModel * lang_model = new QStandardItemModel(this);
2447 lang_model->insertColumns(0, 3);
2449 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2450 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2451 Languages::const_iterator it = lyx::languages.begin();
2452 Languages::const_iterator end = lyx::languages.end();
2453 for (; it != end; ++it) {
2454 current_row = lang_model->rowCount();
2455 lang_model->insertRows(current_row, 1);
2456 QModelIndex pl_item = lang_model->index(current_row, 0);
2457 QModelIndex sp_item = lang_model->index(current_row, 1);
2458 QModelIndex th_item = lang_model->index(current_row, 2);
2459 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2460 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2461 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2462 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2463 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2464 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2465 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2466 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2467 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2468 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2470 d->language_model_ = new QSortFilterProxyModel(this);
2471 d->language_model_->setSourceModel(lang_model);
2472 d->language_model_->setSortLocaleAware(true);
2473 return d->language_model_;
2477 void GuiApplication::restoreGuiSession()
2479 if (!lyxrc.load_session)
2482 Session & session = theSession();
2483 LastOpenedSection::LastOpened const & lastopened =
2484 session.lastOpened().getfiles();
2486 validateCurrentView();
2488 FileName active_file;
2489 // do not add to the lastfile list since these files are restored from
2490 // last session, and should be already there (regular files), or should
2491 // not be added at all (help files).
2492 for (size_t i = 0; i < lastopened.size(); ++i) {
2493 FileName const & file_name = lastopened[i].file_name;
2494 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2495 && current_view_->documentBufferView() != 0)) {
2496 boost::crc_32_type crc;
2497 string const & fname = file_name.absFileName();
2498 crc = for_each(fname.begin(), fname.end(), crc);
2499 createView(crc.checksum());
2501 current_view_->loadDocument(file_name, false);
2503 if (lastopened[i].active)
2504 active_file = file_name;
2507 // Restore last active buffer
2508 Buffer * buffer = theBufferList().getBuffer(active_file);
2509 if (buffer && current_view_)
2510 current_view_->setBuffer(buffer);
2512 // clear this list to save a few bytes of RAM
2513 session.lastOpened().clear();
2517 QString const GuiApplication::romanFontName()
2520 font.setStyleHint(QFont::Serif);
2521 font.setFamily("serif");
2523 return QFontInfo(font).family();
2527 QString const GuiApplication::sansFontName()
2530 font.setStyleHint(QFont::SansSerif);
2531 font.setFamily("sans");
2533 return QFontInfo(font).family();
2537 QString const GuiApplication::typewriterFontName()
2540 font.setStyleHint(QFont::TypeWriter);
2541 font.setFamily("monospace");
2543 return QFontInfo(font).family();
2547 void GuiApplication::handleRegularEvents()
2549 ForkedCallsController::handleCompletedProcesses();
2553 bool GuiApplication::event(QEvent * e)
2556 case QEvent::FileOpen: {
2557 // Open a file; this happens only on Mac OS X for now.
2559 // We do this asynchronously because on startup the batch
2560 // commands are not executed here yet and the gui is not ready
2562 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2563 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2564 processFuncRequestAsync(fr);
2569 return QApplication::event(e);
2574 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2577 return QApplication::notify(receiver, event);
2579 catch (ExceptionMessage const & e) {
2581 case ErrorException:
2583 setQuitOnLastWindowClosed(false);
2585 Alert::error(e.title_, e.details_);
2587 // Properly crash in debug mode in order to get a useful backtrace.
2590 // In release mode, try to exit gracefully.
2593 case BufferException: {
2594 if (!current_view_ || !current_view_->documentBufferView())
2596 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2597 docstring details = e.details_ + '\n';
2598 details += buf->emergencyWrite();
2599 theBufferList().release(buf);
2600 details += "\n" + _("The current document was closed.");
2601 Alert::error(e.title_, details);
2604 case WarningException:
2605 Alert::warning(e.title_, e.details_);
2609 catch (exception const & e) {
2610 docstring s = _("LyX has caught an exception, it will now "
2611 "attempt to save all unsaved documents and exit."
2613 s += from_ascii(e.what());
2614 Alert::error(_("Software exception Detected"), s);
2618 docstring s = _("LyX has caught some really weird exception, it will "
2619 "now attempt to save all unsaved documents and exit.");
2620 Alert::error(_("Software exception Detected"), s);
2628 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2630 QColor const & qcol = d->color_cache_.get(col);
2631 if (!qcol.isValid()) {
2637 rgbcol.r = qcol.red();
2638 rgbcol.g = qcol.green();
2639 rgbcol.b = qcol.blue();
2644 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2646 QColor const qcol(lcolor.getX11Name(col).c_str());
2647 if (!qcol.isValid()) {
2653 rgbcol.r = qcol.red();
2654 rgbcol.g = qcol.green();
2655 rgbcol.b = qcol.blue();
2660 string const GuiApplication::hexName(ColorCode col)
2662 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2666 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2668 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2669 d->socket_notifiers_[fd] = sn;
2670 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2674 void GuiApplication::socketDataReceived(int fd)
2676 d->socket_notifiers_[fd]->func_();
2680 void GuiApplication::unregisterSocketCallback(int fd)
2682 d->socket_notifiers_.take(fd)->setEnabled(false);
2686 void GuiApplication::commitData(QSessionManager & sm)
2688 /** The implementation is required to avoid an application exit
2689 ** when session state save is triggered by session manager.
2690 ** The default implementation sends a close event to all
2691 ** visible top level widgets when session managment allows
2693 ** We are changing that to check the state of each buffer in all
2694 ** views and ask the users what to do if buffers are dirty.
2695 ** Furthermore, we save the session state.
2696 ** We do NOT close the views here since the user still can cancel
2697 ** the logout process (see #9277); also, this would hide LyX from
2698 ** an OSes own session handling (application restoration).
2700 #ifdef QT_NO_SESSIONMANAGER
2702 #warning Qt is compiled without session manager
2704 #pragma message("warning: Qt is compiled without session manager")
2708 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2716 void GuiApplication::unregisterView(GuiView * gv)
2718 LAPPERR(d->views_[gv->id()] == gv);
2719 d->views_.remove(gv->id());
2720 if (current_view_ == gv)
2725 bool GuiApplication::closeAllViews()
2727 if (d->views_.empty())
2730 // When a view/window was closed before without quitting LyX, there
2731 // are already entries in the lastOpened list.
2732 theSession().lastOpened().clear();
2734 QList<GuiView *> const views = d->views_.values();
2735 foreach (GuiView * view, views) {
2736 if (!view->closeScheduled())
2745 bool GuiApplication::prepareAllViewsForLogout()
2747 if (d->views_.empty())
2750 QList<GuiView *> const views = d->views_.values();
2751 foreach (GuiView * view, views) {
2752 if (!view->prepareAllBuffersForLogout())
2760 GuiView & GuiApplication::view(int id) const
2762 LAPPERR(d->views_.contains(id));
2763 return *d->views_.value(id);
2767 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2769 QList<GuiView *> const views = d->views_.values();
2770 foreach (GuiView * view, views)
2771 view->hideDialog(name, inset);
2775 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2777 Buffer const * buffer_ = 0;
2778 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2779 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2780 if (Buffer const * ptr = (*it)->updateInset(inset))
2787 bool GuiApplication::searchMenu(FuncRequest const & func,
2788 docstring_list & names) const
2790 return d->menus_.searchMenu(func, names);
2794 // Ensure that a file is read only once (prevents include loops)
2795 static QStringList uifiles;
2796 // store which ui files define Toolbars
2797 static QStringList toolbar_uifiles;
2800 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2811 LexerKeyword uitags[] = {
2812 { "format", ui_format },
2813 { "include", ui_include },
2814 { "menuset", ui_menuset },
2815 { "toolbars", ui_toolbars },
2816 { "toolbarset", ui_toolbarset }
2820 lex.setFile(ui_path);
2822 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2826 if (lyxerr.debugging(Debug::PARSER))
2827 lex.printTable(lyxerr);
2830 // format before introduction of format tag
2831 unsigned int format = 0;
2832 while (lex.isOK()) {
2833 int const status = lex.lex();
2835 // we have to do this check here, outside the switch,
2836 // because otherwise we would start reading include files,
2837 // e.g., if the first tag we hit was an include tag.
2838 if (status == ui_format)
2840 format = lex.getInteger();
2844 // this will trigger unless the first tag we hit is a format
2845 // tag, with the right format.
2846 if (format != LFUN_FORMAT)
2847 return FormatMismatch;
2850 case Lexer::LEX_FEOF:
2855 QString const file = toqstr(lex.getString());
2856 bool const success = readUIFile(file, true);
2858 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2865 d->menus_.read(lex);
2869 d->toolbars_.readToolbars(lex);
2873 d->toolbars_.readToolbarSettings(lex);
2874 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2878 if (!rtrim(lex.getString()).empty())
2879 lex.printError("LyX::ReadUIFile: "
2880 "Unknown menu tag: `$$Token'");
2882 LYXERR0("Error with status: " << status);
2888 return (error ? ReadError : ReadOK);
2892 bool GuiApplication::readUIFile(QString const & name, bool include)
2894 LYXERR(Debug::INIT, "About to read " << name << "...");
2898 ui_path = libFileSearch("ui", name, "inc");
2899 if (ui_path.empty())
2900 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2902 ui_path = libFileSearch("ui", name, "ui");
2905 if (ui_path.empty()) {
2906 static const QString defaultUIFile = "default";
2907 LYXERR(Debug::INIT, "Could not find " << name);
2909 Alert::warning(_("Could not find UI definition file"),
2910 bformat(_("Error while reading the included file\n%1$s\n"
2911 "Please check your installation."), qstring_to_ucs4(name)));
2914 if (name == defaultUIFile) {
2915 LYXERR(Debug::INIT, "Could not find default UI file!!");
2916 Alert::warning(_("Could not find default UI file"),
2917 _("LyX could not find the default UI file!\n"
2918 "Please check your installation."));
2921 Alert::warning(_("Could not find UI definition file"),
2922 bformat(_("Error while reading the configuration file\n%1$s\n"
2923 "Falling back to default.\n"
2924 "Please look under Tools>Preferences>User Interface and\n"
2925 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2926 return readUIFile(defaultUIFile, false);
2929 QString const uifile = toqstr(ui_path.absFileName());
2930 if (uifiles.contains(uifile)) {
2932 // We are reading again the top uifile so reset the safeguard:
2935 d->toolbars_.reset();
2937 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2938 << "Is this an include loop?");
2942 uifiles.push_back(uifile);
2944 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2946 ReturnValues retval = readUIFile(ui_path);
2948 if (retval == FormatMismatch) {
2949 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2950 TempFile tmp("convertXXXXXX.ui");
2951 FileName const tempfile = tmp.name();
2952 bool const success = prefs2prefs(ui_path, tempfile, true);
2954 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2955 " to format " << LFUN_FORMAT << ".");
2957 retval = readUIFile(tempfile);
2961 if (retval != ReadOK) {
2962 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2970 settings.beginGroup("ui_files");
2971 bool touched = false;
2972 for (int i = 0; i != uifiles.size(); ++i) {
2973 QFileInfo fi(uifiles[i]);
2974 QDateTime const date_value = fi.lastModified();
2975 QString const name_key = QString::number(i);
2976 // if an ui file which defines Toolbars has changed,
2977 // we have to reset the settings
2978 if (toolbar_uifiles.contains(uifiles[i])
2979 && (!settings.contains(name_key)
2980 || settings.value(name_key).toString() != uifiles[i]
2981 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2983 settings.setValue(name_key, uifiles[i]);
2984 settings.setValue(name_key + "/date", date_value);
2987 settings.endGroup();
2989 settings.remove("views");
2995 void GuiApplication::onLastWindowClosed()
2997 if (d->global_menubar_)
2998 d->global_menubar_->grabKeyboard();
3002 void GuiApplication::startLongOperation() {
3003 d->key_checker_.start();
3007 bool GuiApplication::longOperationCancelled() {
3008 return d->key_checker_.pressed();
3012 void GuiApplication::stopLongOperation() {
3013 d->key_checker_.stop();
3017 bool GuiApplication::longOperationStarted() {
3018 return d->key_checker_.started();
3022 ////////////////////////////////////////////////////////////////////////
3024 // X11 specific stuff goes here...
3027 bool GuiApplication::x11EventFilter(XEvent * xev)
3032 switch (xev->type) {
3033 case SelectionRequest: {
3034 if (xev->xselectionrequest.selection != XA_PRIMARY)
3036 LYXERR(Debug::SELECTION, "X requested selection.");
3037 BufferView * bv = current_view_->currentBufferView();
3039 docstring const sel = bv->requestSelection();
3041 d->selection_.put(sel);
3045 case SelectionClear: {
3046 if (xev->xselectionclear.selection != XA_PRIMARY)
3048 LYXERR(Debug::SELECTION, "Lost selection.");
3049 BufferView * bv = current_view_->currentBufferView();
3051 bv->clearSelection();
3057 #elif defined(QPA_XCB)
3058 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3059 void * message, long *) Q_DECL_OVERRIDE
3061 if (!current_view_ || eventType != "xcb_generic_event_t")
3064 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3066 switch (ev->response_type) {
3067 case XCB_SELECTION_REQUEST: {
3068 xcb_selection_request_event_t * srev =
3069 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3070 if (srev->selection != XA_PRIMARY)
3072 LYXERR(Debug::SELECTION, "X requested selection.");
3073 BufferView * bv = current_view_->currentBufferView();
3075 docstring const sel = bv->requestSelection();
3077 d->selection_.put(sel);
3081 case XCB_SELECTION_CLEAR: {
3082 xcb_selection_clear_event_t * scev =
3083 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3084 if (scev->selection != XA_PRIMARY)
3086 LYXERR(Debug::SELECTION, "Lost selection.");
3087 BufferView * bv = current_view_->currentBufferView();
3089 bv->clearSelection();
3097 } // namespace frontend
3100 void hideDialogs(std::string const & name, Inset * inset)
3103 frontend::guiApp->hideDialogs(name, inset);
3107 ////////////////////////////////////////////////////////////////////
3111 ////////////////////////////////////////////////////////////////////
3113 frontend::FontLoader & theFontLoader()
3115 LAPPERR(frontend::guiApp);
3116 return frontend::guiApp->fontLoader();
3120 frontend::FontMetrics const & theFontMetrics(Font const & f)
3122 return theFontMetrics(f.fontInfo());
3126 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3128 LAPPERR(frontend::guiApp);
3129 return frontend::guiApp->fontLoader().metrics(f);
3133 ////////////////////////////////////////////////////////////////////
3137 ////////////////////////////////////////////////////////////////////
3139 frontend::Clipboard & theClipboard()
3141 LAPPERR(frontend::guiApp);
3142 return frontend::guiApp->clipboard();
3146 frontend::Selection & theSelection()
3148 LAPPERR(frontend::guiApp);
3149 return frontend::guiApp->selection();
3155 #include "moc_GuiApplication.cpp"