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"
85 #include <QFontDatabase>
89 #include <QDesktopWidget>
93 #include <QFileOpenEvent>
97 #include <QImageReader>
100 #include <QLibraryInfo>
106 #include <QPixmapCache>
108 #include <QSessionManager>
110 #include <QShowEvent>
111 #include <QSocketNotifier>
112 #include <QSortFilterProxyModel>
113 #include <QStandardItemModel>
114 #include <QTextCodec>
116 #include <QTranslator>
117 #include <QThreadPool>
121 #include <X11/Xatom.h>
122 #include <X11/Xlib.h>
125 #elif defined(QPA_XCB)
129 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
130 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
131 #if (QT_VERSION < 0x050000)
132 #include <QWindowsMime>
133 #define QWINDOWSMIME QWindowsMime
136 #define QWINDOWSMIME QWinMime
146 #include <QMacPasteboardMime>
149 #include "support/bind.h"
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 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
232 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
234 string ext = ascii_lowercase((const char *) *it);
245 ////////////////////////////////////////////////////////////////////////
247 // Icon loading support code
249 ////////////////////////////////////////////////////////////////////////
259 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
261 return lhs.key < rhs.key;
267 CompareKey(QString const & name) : name_(name) {}
268 bool operator()(ImgMap const & other) const { return other.key == name_; }
274 // this must be sorted alphabetically
275 // Upper case comes before lower case
276 // Please don't change the formatting, this list is parsed by
277 // development/tools/generate_symbols_images.py.
278 ImgMap sorted_img_map[] = {
279 { "Arrownot", "arrownot2"},
280 { "Arrowvert", "arrowvert2"},
281 { "Bowtie", "bowtie2" },
283 { "Bumpeq", "bumpeq2" },
284 { "CIRCLE", "circle3" },
286 { "CheckedBox", "checkedbox2" },
287 { "Circle", "circle2" },
288 { "Colonapprox", "colonapprox2" },
289 { "Coloneq", "coloneq2" },
290 { "Coloneqq", "coloneqq2" },
291 { "Colonsim", "colonsim2" },
293 { "DOWNarrow", "downarrow3" },
294 { "Delta", "delta2" },
295 { "Diamond", "diamond2" },
296 { "Doteq", "doteq2" },
297 { "Downarrow", "downarrow2" },
298 { "Eqcolon", "eqcolon2" },
299 { "Eqqcolon", "eqqcolon2" },
300 { "Gamma", "gamma2" },
302 { "LEFTCIRCLE", "leftcircle3" },
303 { "LEFTarrow", "leftarrow3" },
304 { "LEFTcircle", "leftcircle4" },
306 { "Lambda", "lambda2" },
308 { "Leftarrow", "leftarrow2" },
309 { "Leftcircle", "leftcircle2" },
310 { "Leftrightarrow", "leftrightarrow2" },
311 { "Longarrownot", "longarrownot2"},
312 { "Longleftarrow", "longleftarrow2" },
313 { "Longleftrightarrow", "longleftrightarrow2" },
314 { "Longmapsfrom", "longmapsfrom2"},
315 { "Longmapsto", "longmapsto2"},
316 { "Longrightarrow", "longrightarrow2" },
317 { "Mapsfrom", "mapsfrom2"},
318 { "Mapsfromchar", "mapsfromchar2"},
319 { "Mapsto", "mapsto2"},
320 { "Mapstochar", "mapstochar2"},
321 { "Omega", "omega2" },
326 { "RIGHTCIRCLE", "rightcircle3" },
327 { "RIGHTarrow", "rightarrow3" },
328 { "RIGHTcircle", "rightcircle4" },
330 { "Rightarrow", "rightarrow2" },
331 { "Rightcircle", "rightcircle2" },
332 { "Sigma", "sigma2" },
333 { "Square", "square2" },
334 { "Subset", "subset2" },
335 { "Supset", "supset2" },
336 { "Theta", "theta2" },
337 { "Thorn", "thorn2" },
338 { "UParrow", "uparrow3" },
339 { "Uparrow", "uparrow2" },
340 { "Updownarrow", "updownarrow2" },
341 { "Upsilon", "upsilon2" },
342 { "Vdash", "vdash3" },
347 { "lVert", "vert2" },
349 { "nLeftarrow", "nleftarrow2" },
350 { "nLeftrightarrow", "nleftrightarrow2" },
351 { "nRightarrow", "nrightarrow2" },
352 { "nVDash", "nvdash3" },
353 { "nVdash", "nvdash4" },
354 { "nvDash", "nvdash2" },
355 { "rVert", "vert2" },
357 { "textrm \\AA", "textrm_AA"},
358 { "textrm \\O", "textrm_O"},
359 { "vDash", "vdash2" },
360 { "varDelta", "vardelta2" },
361 { "varGamma", "vargamma2" },
362 { "varLambda", "varlambda2" },
363 { "varOmega", "varomega2" },
364 { "varPhi", "varphi2" },
365 { "varPi", "varpi2" },
366 { "varPsi", "varpsi2" },
367 { "varSigma", "varsigma2" },
368 { "varTheta", "vartheta2" },
369 { "varUpsilon", "varupsilon2" },
370 { "varXi", "varxi2" }
374 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
376 // This list specifies which system's theme icon is related to which lyx
377 // command. It was based on:
378 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
379 // this must be sorted alphabetically
380 // Upper case comes before lower case
381 ImgMap sorted_theme_icon_map[] = {
382 { "bookmark-goto 0", "go-jump" },
383 { "buffer-new", "document-new" },
384 { "buffer-write", "document-save" },
385 { "buffer-write-as", "document-save-as" },
386 { "buffer-zoom-in", "zoom-in" },
387 { "buffer-zoom-out", "zoom-out" },
388 { "copy", "edit-copy" },
389 { "cut", "edit-cut" },
390 { "depth-decrement", "format-indent-less" },
391 { "depth-increment", "format-indent-more" },
392 { "dialog-show spellchecker", "tools-check-spelling" },
393 { "dialog-show-new-inset graphics", "insert-image" },
394 { "dialog-toggle findreplaceadv", "edit-find-replace" },
395 { "file-open", "document-open" },
396 { "font-bold", "format-text-bold" },
397 { "font-ital", "format-text-italic" },
398 { "font-strikeout", "format-text-strikethrough" },
399 { "font-underline", "format-text-underline" },
400 { "lyx-quit", "application-exit" },
401 { "paste", "edit-paste" },
402 { "redo", "edit-redo" },
403 { "undo", "edit-undo" },
404 { "window-close", "window-close" },
405 { "window-new", "window-new" }
408 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
411 QString findImg(QString const & name)
413 ImgMap const * const begin = sorted_img_map;
414 ImgMap const * const end = begin + nr_sorted_img_map;
415 LATTEST(sorted(begin, end));
417 ImgMap const * const it = find_if(begin, end, CompareKey(name));
421 img_name = it->value;
424 img_name.replace('_', "underscore");
425 img_name.replace(' ', '_');
427 // This way we can have "math-delim { }" on the toolbar.
428 img_name.replace('(', "lparen");
429 img_name.replace(')', "rparen");
430 img_name.replace('[', "lbracket");
431 img_name.replace(']', "rbracket");
432 img_name.replace('{', "lbrace");
433 img_name.replace('}', "rbrace");
434 img_name.replace('|', "bars");
435 img_name.replace(',', "thinspace");
436 img_name.replace(':', "mediumspace");
437 img_name.replace(';', "thickspace");
438 img_name.replace('!', "negthinspace");
441 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
442 << "Looking for math icon called \"" << img_name << '"');
449 QString themeIconName(QString const & action)
451 ImgMap const * const begin = sorted_theme_icon_map;
452 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
453 LASSERT(sorted(begin, end), /**/);
455 ImgMap const * const it = find_if(begin, end, CompareKey(action));
463 QString iconName(FuncRequest const & f, bool unknown)
465 initializeResources();
469 switch (f.action()) {
470 case LFUN_MATH_INSERT:
471 if (!f.argument().empty()) {
473 name1 = findImg(toqstr(f.argument()).mid(1));
476 case LFUN_MATH_DELIM:
477 case LFUN_MATH_BIGDELIM:
479 name1 = findImg(toqstr(f.argument()));
483 name1 = toqstr(f.argument());
485 case LFUN_COMMAND_ALTERNATIVES: {
486 // use the first of the alternative commands
488 docstring dummy = split(f.argument(), firstcom, ';');
489 name1 = toqstr(firstcom);
490 name1.replace(' ', '_');
494 name2 = toqstr(lyxaction.getActionName(f.action()));
497 if (!f.argument().empty()) {
498 name1 = name2 + ' ' + toqstr(f.argument());
499 name1.replace(' ', '_');
500 name1.replace('\\', "backslash");
504 QStringList imagedirs;
505 imagedirs << "images/" << "images/ipa/";
506 search_mode mode = theGuiApp()->imageSearchMode();
507 for (int i = 0; i < imagedirs.size(); ++i) {
508 QString imagedir = imagedirs.at(i) + path;
509 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
511 return toqstr(fname.absFileName());
513 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
515 return toqstr(fname.absFileName());
518 path = ":/images/" + path;
521 LYXERR0("Directory " << path << " not found in resource!");
524 if (res.exists(name1 + ".svgz"))
525 return path + name1 + ".svgz";
526 else if (res.exists(name1 + ".png"))
527 return path + name1 + ".png";
529 if (res.exists(name2 + ".svgz"))
530 return path + name2 + ".svgz";
531 else if (res.exists(name2 + ".png"))
532 return path + name2 + ".png";
534 LYXERR(Debug::GUI, "Cannot find icon with filename "
535 << "\"" << name1 << ".{svgz,png}\""
537 << "\"" << name2 << ".{svgz,png}\""
539 << lyxaction.getActionName(f.action())
540 << '(' << to_utf8(f.argument()) << ")\"");
543 QString imagedir = "images/";
544 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
546 return toqstr(fname.absFileName());
547 return QString(":/images/unknown.svgz");
554 bool getPixmap(QPixmap & pixmap, QString const & path)
556 if (pixmap.load(path)) {
557 #if QT_VERSION >= 0x050000
558 if (path.endsWith(".svgz") || path.endsWith(".svg") ) {
559 GuiApplication const * guiApp = theGuiApp();
561 pixmap.setDevicePixelRatio(guiApp->pixelRatio());
571 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
573 QString imagedir = path;
574 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
575 QString fpath = toqstr(fname.absFileName());
576 QPixmap pixmap = QPixmap();
578 if (getPixmap(pixmap, fpath)) {
582 QStringList exts = ext.split(",");
583 fpath = ":/" + path + name + ".";
584 for (int i = 0; i < exts.size(); ++i) {
585 if (getPixmap(pixmap, 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!");
599 QIcon getIcon(FuncRequest const & f, bool unknown)
601 #if (QT_VERSION >= 0x040600)
602 if (lyxrc.use_system_theme_icons) {
603 // use the icons from system theme that are available
604 QString action = toqstr(lyxaction.getActionName(f.action()));
605 if (!f.argument().empty())
606 action += " " + toqstr(f.argument());
607 QString const theme_icon = themeIconName(action);
608 if (QIcon::hasThemeIcon(theme_icon)) {
609 QIcon const thmicn = QIcon::fromTheme(theme_icon);
610 if (!thmicn.isNull())
616 QString icon = iconName(f, unknown);
620 //LYXERR(Debug::GUI, "Found icon: " << icon);
621 QPixmap pixmap = QPixmap();
622 if (!getPixmap(pixmap,icon)) {
623 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
627 return QIcon(pixmap);
631 ////////////////////////////////////////////////////////////////////////
633 // LyX server support code.
635 ////////////////////////////////////////////////////////////////////////
637 class SocketNotifier : public QSocketNotifier
640 /// connect a connection notification from the LyXServerSocket
641 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
642 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
646 /// The callback function
647 Application::SocketCallback func_;
651 ////////////////////////////////////////////////////////////////////////
653 // Mac specific stuff goes here...
655 ////////////////////////////////////////////////////////////////////////
657 class MenuTranslator : public QTranslator
660 MenuTranslator(QObject * parent)
661 : QTranslator(parent)
664 #if QT_VERSION >= 0x050000
665 virtual QString translate(const char * /* context */,
666 const char *sourceText,
667 const char * /* disambiguation */ = 0, int /* n */ = -1) const
669 QString translate(const char * /*context*/,
670 const char * sourceText,
671 const char * /*comment*/ = 0) const
674 string const s = sourceText;
675 if (s == N_("About %1") || s == N_("Preferences")
676 || s == N_("Reconfigure") || s == N_("Quit %1"))
684 // QMacPasteboardMimeGraphics can only be compiled on Mac.
686 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
689 QMacPasteboardMimeGraphics()
690 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
693 QString convertorName() { return "Graphics"; }
695 QString flavorFor(QString const & mime)
697 LYXERR(Debug::ACTION, "flavorFor " << mime);
698 if (mime == pdfMimeType())
699 return QLatin1String("com.adobe.pdf");
703 QString mimeFor(QString flav)
705 LYXERR(Debug::ACTION, "mimeFor " << flav);
706 if (flav == QLatin1String("com.adobe.pdf"))
707 return pdfMimeType();
711 bool canConvert(QString const & mime, QString flav)
713 return mimeFor(flav) == mime;
716 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
720 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
724 QList<QByteArray> convertFromMime(QString const & /*mime*/,
725 QVariant data, QString /*flav*/)
727 QList<QByteArray> ret;
728 ret.append(data.toByteArray());
734 ///////////////////////////////////////////////////////////////
736 // You can find more platform specific stuff at the end of this file...
738 ///////////////////////////////////////////////////////////////
740 ////////////////////////////////////////////////////////////////////////
741 // Windows specific stuff goes here...
743 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
744 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
745 // QWindowsMimeMetafile can only be compiled on Windows.
747 static FORMATETC cfFromMime(QString const & mimetype)
750 if (mimetype == emfMimeType()) {
751 formatetc.cfFormat = CF_ENHMETAFILE;
752 formatetc.tymed = TYMED_ENHMF;
753 } else if (mimetype == wmfMimeType()) {
754 formatetc.cfFormat = CF_METAFILEPICT;
755 formatetc.tymed = TYMED_MFPICT;
758 formatetc.dwAspect = DVASPECT_CONTENT;
759 formatetc.lindex = -1;
764 class QWindowsMimeMetafile : public QWINDOWSMIME {
766 QWindowsMimeMetafile() {}
768 bool canConvertFromMime(FORMATETC const & formatetc,
769 QMimeData const * mimedata) const
774 bool canConvertToMime(QString const & mimetype,
775 IDataObject * pDataObj) const
777 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
779 FORMATETC formatetc = cfFromMime(mimetype);
780 return pDataObj->QueryGetData(&formatetc) == S_OK;
783 bool convertFromMime(FORMATETC const & formatetc,
784 const QMimeData * mimedata, STGMEDIUM * pmedium) const
789 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
790 QVariant::Type preferredType) const
793 if (!canConvertToMime(mimetype, pDataObj))
796 FORMATETC formatetc = cfFromMime(mimetype);
798 if (pDataObj->GetData(&formatetc, &s) != S_OK)
802 if (s.tymed == TYMED_ENHMF) {
803 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
804 data.resize(dataSize);
805 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
806 (LPBYTE)data.data());
807 } else if (s.tymed == TYMED_MFPICT) {
808 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
809 data.resize(dataSize);
810 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
811 (LPBYTE)data.data());
814 ReleaseStgMedium(&s);
820 QVector<FORMATETC> formatsForMime(QString const & mimetype,
821 QMimeData const * mimedata) const
823 QVector<FORMATETC> formats;
824 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
825 formats += cfFromMime(mimetype);
829 QString mimeForFormat(FORMATETC const & formatetc) const
831 switch (formatetc.cfFormat) {
833 return emfMimeType();
834 case CF_METAFILEPICT:
835 return wmfMimeType();
845 /// Allows to check whether ESC was pressed during a long operation
846 class KeyChecker : public QObject {
851 KeyChecker() : pressed_(false), started_(false) {}
854 QCoreApplication::instance()->installEventFilter(this);
859 QCoreApplication::instance()->removeEventFilter(this);
863 QCoreApplication::processEvents();
866 bool started() const {
869 bool eventFilter(QObject *obj, QEvent *event) {
870 LYXERR(Debug::ACTION, "Event Type: " << event->type());
871 switch (event->type()) {
875 case QEvent::UpdateRequest:
876 case QEvent::CursorChange:
877 case QEvent::ActionChanged:
878 case QEvent::EnabledChange:
879 case QEvent::SockAct:
882 case QEvent::ToolTipChange:
883 case QEvent::LayoutRequest:
884 case QEvent::MetaCall:
885 return QObject::eventFilter(obj, event);
887 // FIXME Blocking all these events is a bad idea.
888 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
889 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
897 ////////////////////////////////////////////////////////////////////////
898 // GuiApplication::Private definition and implementation.
899 ////////////////////////////////////////////////////////////////////////
901 struct GuiApplication::Private
903 Private(): language_model_(0), meta_fake_bit(NoModifier),
906 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
907 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
908 /// WMF Mime handler for Windows clipboard.
909 wmf_mime_ = new QWindowsMimeMetafile;
912 initKeySequences(&theTopLevelKeymap());
915 void initKeySequences(KeyMap * kb)
917 keyseq = KeySequence(kb, kb);
918 cancel_meta_seq = KeySequence(kb, kb);
922 QSortFilterProxyModel * language_model_;
924 GuiClipboard clipboard_;
926 GuiSelection selection_;
928 FontLoader font_loader_;
930 ColorCache color_cache_;
932 QTranslator qt_trans_;
934 QHash<int, SocketNotifier *> socket_notifiers_;
938 /// The global instance
941 /// this timer is used for any regular events one wants to
942 /// perform. at present it is used to check if forked processes
944 QTimer general_timer_;
946 /// delayed FuncRequests
947 std::queue<FuncRequest> func_request_queue_;
952 KeySequence cancel_meta_seq;
954 KeyModifier meta_fake_bit;
956 /// The result of last dispatch action
957 DispatchResult dispatch_result_;
959 /// Multiple views container.
961 * Warning: This must not be a smart pointer as the destruction of the
962 * object is handled by Qt when the view is closed
963 * \sa Qt::WA_DeleteOnClose attribute.
965 QHash<int, GuiView *> views_;
967 /// Only used on mac.
968 QMenuBar * global_menubar_;
971 /// Linkback mime handler for MacOSX.
972 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
975 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
976 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
977 /// WMF Mime handler for Windows clipboard.
978 QWindowsMimeMetafile * wmf_mime_;
982 /// Allows to check whether ESC was pressed during a long operation
983 KeyChecker key_checker_;
987 GuiApplication * guiApp;
989 GuiApplication::~GuiApplication()
992 closeAllLinkBackLinks();
998 GuiApplication::GuiApplication(int & argc, char ** argv)
999 : QApplication(argc, argv), current_view_(0),
1000 d(new GuiApplication::Private)
1002 QString app_name = "LyX";
1003 QCoreApplication::setOrganizationName(app_name);
1004 QCoreApplication::setOrganizationDomain("lyx.org");
1005 QCoreApplication::setApplicationName(lyx_package);
1007 qsrand(QDateTime::currentDateTime().toTime_t());
1009 // Install translator for GUI elements.
1010 installTranslator(&d->qt_trans_);
1013 // Enable reception of XCB events.
1014 installNativeEventFilter(this);
1017 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1018 // lyxrc setting for this in order to let the application stay resident.
1019 // But then we need some kind of dock icon, at least on Windows.
1021 if (lyxrc.quit_on_last_window_closed)
1022 setQuitOnLastWindowClosed(false);
1025 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1026 // seems to be the default case for applications like LyX.
1027 setQuitOnLastWindowClosed(false);
1028 // This allows to translate the strings that appear in the LyX menu.
1029 /// A translator suitable for the entries in the LyX menu.
1030 /// Only needed with Qt/Mac.
1031 installTranslator(new MenuTranslator(this));
1036 #if defined(Q_WS_X11) || defined(QPA_XCB)
1037 // doubleClickInterval() is 400 ms on X11 which is just too long.
1038 // On Windows and Mac OS X, the operating system's value is used.
1039 // On Microsoft Windows, calling this function sets the double
1040 // click interval for all applications. So we don't!
1041 QApplication::setDoubleClickInterval(300);
1044 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1046 // needs to be done before reading lyxrc
1048 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1052 // Set the cache to 5120 kilobytes which corresponds to screen size of
1053 // 1280 by 1024 pixels with a color depth of 32 bits.
1054 QPixmapCache::setCacheLimit(5120);
1056 // Initialize RC Fonts
1057 if (lyxrc.roman_font_name.empty())
1058 lyxrc.roman_font_name = fromqstr(romanFontName());
1060 if (lyxrc.sans_font_name.empty())
1061 lyxrc.sans_font_name = fromqstr(sansFontName());
1063 if (lyxrc.typewriter_font_name.empty())
1064 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1066 d->general_timer_.setInterval(500);
1067 connect(&d->general_timer_, SIGNAL(timeout()),
1068 this, SLOT(handleRegularEvents()));
1069 d->general_timer_.start();
1071 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1072 // This is clearly not enough in a time where we use threads for
1073 // document preview and/or export. 20 should be OK.
1074 QThreadPool::globalInstance()->setMaxThreadCount(20);
1078 GuiApplication * theGuiApp()
1080 return dynamic_cast<GuiApplication *>(theApp());
1084 double GuiApplication::pixelRatio() const
1086 #if QT_VERSION >= 0x050000
1087 return devicePixelRatio();
1094 void GuiApplication::clearSession()
1101 docstring Application::iconName(FuncRequest const & f, bool unknown)
1103 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1107 docstring Application::mathIcon(docstring const & c)
1109 return qstring_to_ucs4(findImg(toqstr(c)));
1113 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1117 BufferView * bv = 0;
1118 BufferView * doc_bv = 0;
1120 if (cmd.action() == LFUN_NOACTION) {
1121 status.message(from_utf8(N_("Nothing to do")));
1122 status.setEnabled(false);
1125 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1126 status.setUnknown(true);
1127 status.message(from_utf8(N_("Unknown action")));
1128 status.setEnabled(false);
1131 // Does the GuiApplication know something?
1132 else if (getStatus(cmd, status)) { }
1134 // If we do not have a GuiView, then other functions are disabled
1135 else if (!current_view_)
1136 status.setEnabled(false);
1138 // Does the GuiView know something?
1139 else if (current_view_->getStatus(cmd, status)) { }
1141 // In LyX/Mac, when a dialog is open, the menus of the
1142 // application can still be accessed without giving focus to
1143 // the main window. In this case, we want to disable the menu
1144 // entries that are buffer or view-related.
1145 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1147 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1148 status.setEnabled(false);
1151 // If we do not have a BufferView, then other functions are disabled
1152 else if (!(bv = current_view_->currentBufferView()))
1153 status.setEnabled(false);
1155 // Does the current BufferView know something?
1156 else if (bv->getStatus(cmd, status)) { }
1158 // Does the current Buffer know something?
1159 else if (bv->buffer().getStatus(cmd, status)) { }
1161 // If we do not have a document BufferView, different from the
1162 // current BufferView, then other functions are disabled
1163 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1164 status.setEnabled(false);
1166 // Does the document Buffer know something?
1167 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1170 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1171 status.message(from_utf8(N_("Command not handled")));
1172 status.setEnabled(false);
1175 // the default error message if we disable the command
1176 if (!status.enabled() && status.message().empty())
1177 status.message(from_utf8(N_("Command disabled")));
1183 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1185 // I would really like to avoid having this switch and rather try to
1186 // encode this in the function itself.
1187 // -- And I'd rather let an inset decide which LFUNs it is willing
1188 // to handle (Andre')
1190 switch (cmd.action()) {
1192 // This could be used for the no-GUI version. The GUI version is handled in
1193 // GuiView::getStatus(). See above.
1195 case LFUN_BUFFER_WRITE:
1196 case LFUN_BUFFER_WRITE_AS: {
1197 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1198 enable = b && (b->isUnnamed() || !b->isClean());
1203 case LFUN_BOOKMARK_GOTO: {
1204 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1205 enable = theSession().bookmarks().isValid(num);
1209 case LFUN_BOOKMARK_CLEAR:
1210 enable = theSession().bookmarks().hasValid();
1213 // this one is difficult to get right. As a half-baked
1214 // solution, we consider only the first action of the sequence
1215 case LFUN_COMMAND_SEQUENCE: {
1216 // argument contains ';'-terminated commands
1217 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1218 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1219 func.setOrigin(cmd.origin());
1220 flag = getStatus(func);
1224 // we want to check if at least one of these is enabled
1225 case LFUN_COMMAND_ALTERNATIVES: {
1226 // argument contains ';'-terminated commands
1227 string arg = to_utf8(cmd.argument());
1228 while (!arg.empty()) {
1230 arg = split(arg, first, ';');
1231 FuncRequest func(lyxaction.lookupFunc(first));
1232 func.setOrigin(cmd.origin());
1233 flag = getStatus(func);
1234 // if this one is enabled, the whole thing is
1243 string name = to_utf8(cmd.argument());
1244 if (theTopLevelCmdDef().lock(name, func)) {
1245 func.setOrigin(cmd.origin());
1246 flag = getStatus(func);
1247 theTopLevelCmdDef().release(name);
1249 // catch recursion or unknown command
1250 // definition. all operations until the
1251 // recursion or unknown command definition
1252 // occurs are performed, so set the state to
1259 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1261 case LFUN_PREFERENCES_SAVE:
1262 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1263 case LFUN_DEBUG_LEVEL_SET:
1264 // these are handled in our dispatch()
1267 case LFUN_WINDOW_CLOSE:
1268 enable = d->views_.size() > 0;
1271 case LFUN_BUFFER_NEW:
1272 case LFUN_BUFFER_NEW_TEMPLATE:
1273 case LFUN_FILE_OPEN:
1274 case LFUN_HELP_OPEN:
1275 case LFUN_SCREEN_FONT_UPDATE:
1276 case LFUN_SET_COLOR:
1277 case LFUN_WINDOW_NEW:
1279 case LFUN_LYXRC_APPLY:
1280 case LFUN_COMMAND_PREFIX:
1282 case LFUN_META_PREFIX:
1283 case LFUN_RECONFIGURE:
1284 case LFUN_SERVER_GET_FILENAME:
1285 case LFUN_SERVER_NOTIFY:
1289 case LFUN_BUFFER_FORALL: {
1290 if (theBufferList().empty()) {
1291 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1292 flag.setEnabled(false);
1296 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1297 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1298 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1299 flag.setEnabled(false);
1304 case LFUN_DIALOG_SHOW: {
1305 string const name = cmd.getArg(0);
1306 return name == "aboutlyx"
1308 || name == "texinfo"
1309 || name == "progress"
1310 || name == "compare";
1318 flag.setEnabled(false);
1322 /// make a post-dispatch status message
1323 static docstring makeDispatchMessage(docstring const & msg,
1324 FuncRequest const & cmd)
1326 const bool verbose = (cmd.origin() == FuncRequest::MENU
1327 || cmd.origin() == FuncRequest::TOOLBAR
1328 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1330 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1331 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1335 docstring dispatch_msg = msg;
1336 if (!dispatch_msg.empty())
1337 dispatch_msg += ' ';
1339 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1341 bool argsadded = false;
1343 if (!cmd.argument().empty()) {
1344 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1345 comname += ' ' + cmd.argument();
1349 docstring const shortcuts = theTopLevelKeymap().
1350 printBindings(cmd, KeySequence::ForGui);
1352 if (!shortcuts.empty())
1353 comname += ": " + shortcuts;
1354 else if (!argsadded && !cmd.argument().empty())
1355 comname += ' ' + cmd.argument();
1357 if (!comname.empty()) {
1358 comname = rtrim(comname);
1359 dispatch_msg += '(' + rtrim(comname) + ')';
1361 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1362 return dispatch_msg;
1366 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1368 Buffer * buffer = 0;
1369 if (current_view_ && current_view_->currentBufferView()) {
1370 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1371 buffer = ¤t_view_->currentBufferView()->buffer();
1373 buffer->undo().beginUndoGroup();
1377 // redraw the screen at the end (first of the two drawing steps).
1378 // This is done unless explicitly requested otherwise
1379 dr.screenUpdate(Update::FitCursor);
1381 updateCurrentView(cmd, dr);
1383 // the buffer may have been closed by one action
1384 if (theBufferList().isLoaded(buffer))
1385 buffer->undo().endUndoGroup();
1387 d->dispatch_result_ = dr;
1388 return d->dispatch_result_;
1392 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1397 BufferView * bv = current_view_->currentBufferView();
1399 if (dr.needBufferUpdate()) {
1400 bv->cursor().clearBufferUpdate();
1401 bv->buffer().updateBuffer();
1403 // BufferView::update() updates the ViewMetricsInfo and
1404 // also initializes the position cache for all insets in
1405 // (at least partially) visible top-level paragraphs.
1406 // We will redraw the screen only if needed.
1407 bv->processUpdateFlags(dr.screenUpdate());
1409 // Do we have a selection?
1410 theSelection().haveSelection(bv->cursor().selection());
1413 current_view_->restartCursor();
1415 if (dr.needMessageUpdate()) {
1416 // Some messages may already be translated, so we cannot use _()
1417 current_view_->message(makeDispatchMessage(
1418 translateIfPossible(dr.message()), cmd));
1423 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1424 bool switchToBuffer)
1426 if (!theSession().bookmarks().isValid(idx))
1428 BookmarksSection::Bookmark const & bm =
1429 theSession().bookmarks().bookmark(idx);
1430 LASSERT(!bm.filename.empty(), return);
1431 string const file = bm.filename.absFileName();
1432 // if the file is not opened, open it.
1433 if (!theBufferList().exists(bm.filename)) {
1435 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1439 // open may fail, so we need to test it again
1440 if (!theBufferList().exists(bm.filename))
1443 // bm can be changed when saving
1444 BookmarksSection::Bookmark tmp = bm;
1446 // Special case idx == 0 used for back-from-back jump navigation
1448 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1450 // if the current buffer is not that one, switch to it.
1451 BufferView * doc_bv = current_view_ ?
1452 current_view_->documentBufferView() : 0;
1453 Cursor const old = doc_bv->cursor();
1454 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1455 if (switchToBuffer) {
1456 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1459 doc_bv = current_view_->documentBufferView();
1464 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1465 if (!doc_bv->moveToPosition(
1466 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1469 Cursor & cur = doc_bv->cursor();
1471 notifyCursorLeavesOrEnters(old, cur);
1477 // Cursor jump succeeded!
1478 pit_type new_pit = cur.pit();
1479 pos_type new_pos = cur.pos();
1480 int new_id = cur.paragraph().id();
1482 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1483 // see http://www.lyx.org/trac/ticket/3092
1484 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1485 || bm.top_id != new_id) {
1486 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1487 new_pit, new_pos, new_id);
1491 // This function runs "configure" and then rereads lyx.defaults to
1492 // reconfigure the automatic settings.
1493 void GuiApplication::reconfigure(string const & option)
1495 // emit message signal.
1497 current_view_->message(_("Running configure..."));
1499 // Run configure in user lyx directory
1500 string const lock_file = package().getConfigureLockName();
1501 int fd = fileLock(lock_file.c_str());
1502 int const ret = package().reconfigureUserLyXDir(option);
1503 // emit message signal.
1505 current_view_->message(_("Reloading configuration..."));
1506 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1507 // Re-read packages.lst
1508 LaTeXPackages::getAvailable();
1509 fileUnlock(fd, lock_file.c_str());
1512 Alert::information(_("System reconfiguration failed"),
1513 _("The system reconfiguration has failed.\n"
1514 "Default textclass is used but LyX may\n"
1515 "not be able to work properly.\n"
1516 "Please reconfigure again if needed."));
1518 Alert::information(_("System reconfigured"),
1519 _("The system has been reconfigured.\n"
1520 "You need to restart LyX to make use of any\n"
1521 "updated document class specifications."));
1524 void GuiApplication::validateCurrentView()
1526 if (!d->views_.empty() && !current_view_) {
1527 // currently at least one view exists but no view has the focus.
1528 // choose the last view to make it current.
1529 // a view without any open document is preferred.
1530 GuiView * candidate = 0;
1531 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1532 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1533 for (; it != end; ++it) {
1535 if (!candidate->documentBufferView())
1538 setCurrentView(candidate);
1542 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1544 string const argument = to_utf8(cmd.argument());
1545 FuncCode const action = cmd.action();
1547 LYXERR(Debug::ACTION, "cmd: " << cmd);
1549 // we have not done anything wrong yet.
1552 FuncStatus const flag = getStatus(cmd);
1553 if (!flag.enabled()) {
1554 // We cannot use this function here
1555 LYXERR(Debug::ACTION, "action "
1556 << lyxaction.getActionName(action)
1557 << " [" << action << "] is disabled at this location");
1558 dr.setMessage(flag.message());
1560 dr.dispatched(false);
1561 dr.screenUpdate(Update::None);
1562 dr.clearBufferUpdate();
1566 if (cmd.origin() == FuncRequest::LYXSERVER) {
1567 if (current_view_ && current_view_->currentBufferView())
1568 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1569 // we will also need to redraw the screen at the end
1570 dr.screenUpdate(Update::FitCursor);
1573 // Assumes that the action will be dispatched.
1574 dr.dispatched(true);
1576 switch (cmd.action()) {
1578 case LFUN_WINDOW_NEW:
1579 createView(toqstr(cmd.argument()));
1582 case LFUN_WINDOW_CLOSE:
1583 // update bookmark pit of the current buffer before window close
1584 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1585 gotoBookmark(i+1, false, false);
1586 // clear the last opened list, because
1587 // maybe this will end the session
1588 theSession().lastOpened().clear();
1589 // check for valid current_view_
1590 validateCurrentView();
1592 current_view_->closeScheduled();
1596 // quitting is triggered by the gui code
1597 // (leaving the event loop).
1599 current_view_->message(from_utf8(N_("Exiting.")));
1600 if (closeAllViews())
1604 case LFUN_SCREEN_FONT_UPDATE: {
1605 // handle the screen font changes.
1606 d->font_loader_.update();
1607 // Backup current_view_
1608 GuiView * view = current_view_;
1609 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1610 // to skip the refresh.
1612 theBufferList().changed(false);
1613 // Restore current_view_
1614 current_view_ = view;
1618 case LFUN_BUFFER_NEW:
1619 validateCurrentView();
1620 if (d->views_.empty()
1621 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1622 createView(QString(), false); // keep hidden
1623 current_view_->newDocument(to_utf8(cmd.argument()), false);
1624 current_view_->show();
1625 setActiveWindow(current_view_);
1627 current_view_->newDocument(to_utf8(cmd.argument()), false);
1631 case LFUN_BUFFER_NEW_TEMPLATE:
1632 validateCurrentView();
1633 if (d->views_.empty()
1634 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1636 current_view_->newDocument(to_utf8(cmd.argument()), true);
1637 if (!current_view_->documentBufferView())
1638 current_view_->close();
1640 current_view_->newDocument(to_utf8(cmd.argument()), true);
1644 case LFUN_FILE_OPEN: {
1645 validateCurrentView();
1646 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1647 string const fname = to_utf8(cmd.argument());
1648 bool const is_open = FileName::isAbsolute(fname)
1649 && theBufferList().getBuffer(FileName(fname));
1650 if (d->views_.empty()
1651 || (!lyxrc.open_buffers_in_tabs
1652 && current_view_->documentBufferView() != 0
1654 // We want the ui session to be saved per document and not per
1655 // window number. The filename crc is a good enough identifier.
1656 boost::crc_32_type crc;
1657 crc = for_each(fname.begin(), fname.end(), crc);
1658 createView(crc.checksum());
1659 current_view_->openDocument(fname);
1660 if (current_view_ && !current_view_->documentBufferView())
1661 current_view_->close();
1663 current_view_->openDocument(fname);
1667 case LFUN_HELP_OPEN: {
1668 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1669 if (current_view_ == 0)
1671 string const arg = to_utf8(cmd.argument());
1673 current_view_->message(_("Missing argument"));
1676 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1678 fname = i18nLibFileSearch("examples", arg, "lyx");
1680 if (fname.empty()) {
1681 lyxerr << "LyX: unable to find documentation file `"
1682 << arg << "'. Bad installation?" << endl;
1685 current_view_->message(bformat(_("Opening help file %1$s..."),
1686 makeDisplayPath(fname.absFileName())));
1687 Buffer * buf = current_view_->loadDocument(fname, false);
1689 #ifndef DEVEL_VERSION
1691 buf->setReadonly(true);
1698 case LFUN_SET_COLOR: {
1700 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1701 if (lyx_name.empty() || x11_name.empty()) {
1703 current_view_->message(
1704 _("Syntax: set-color <lyx_name> <x11_name>"));
1709 // FIXME: The graphics cache no longer has a changeDisplay method.
1710 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1711 bool const graphicsbg_changed =
1712 lyx_name == graphicsbg && x11_name != graphicsbg;
1713 if (graphicsbg_changed)
1714 graphics::GCache::get().changeDisplay(true);
1717 if (!lcolor.setColor(lyx_name, x11_name)) {
1719 current_view_->message(
1720 bformat(_("Set-color \"%1$s\" failed "
1721 "- color is undefined or "
1722 "may not be redefined"),
1723 from_utf8(lyx_name)));
1726 // Make sure we don't keep old colors in cache.
1727 d->color_cache_.clear();
1728 // Update the current view
1729 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1733 case LFUN_LYXRC_APPLY: {
1734 // reset active key sequences, since the bindings
1735 // are updated (bug 6064)
1737 LyXRC const lyxrc_orig = lyxrc;
1739 istringstream ss(to_utf8(cmd.argument()));
1740 bool const success = lyxrc.read(ss);
1743 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1744 << "Unable to read lyxrc data"
1749 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1751 // If the request comes from the minibuffer, then we can't reset
1752 // the GUI, since that would destory the minibuffer itself and
1753 // cause a crash, since we are currently in one of the methods of
1754 // GuiCommandBuffer. See bug #8540.
1755 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1758 // FIXME Unfortunately, that leaves a bug here, since we cannot
1759 // reset the GUI in this case. If the changes to lyxrc affected the
1760 // UI, then, nothing would happen. This seems fairly unlikely, but
1761 // it definitely is a bug.
1766 case LFUN_COMMAND_PREFIX:
1767 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1772 d->meta_fake_bit = NoModifier;
1773 GuiView * gv = currentView();
1774 if (gv && gv->currentBufferView())
1775 // cancel any selection
1776 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1777 dr.setMessage(from_ascii(N_("Cancel")));
1780 case LFUN_META_PREFIX:
1781 d->meta_fake_bit = AltModifier;
1782 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1785 // --- Menus -----------------------------------------------
1786 case LFUN_RECONFIGURE:
1787 // argument is any additional parameter to the configure.py command
1788 reconfigure(to_utf8(cmd.argument()));
1791 // --- lyxserver commands ----------------------------
1792 case LFUN_SERVER_GET_FILENAME: {
1793 if (current_view_ && current_view_->documentBufferView()) {
1794 docstring const fname = from_utf8(
1795 current_view_->documentBufferView()->buffer().absFileName());
1796 dr.setMessage(fname);
1797 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1799 dr.setMessage(docstring());
1800 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1805 case LFUN_SERVER_NOTIFY: {
1806 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1807 dr.setMessage(dispatch_buffer);
1808 theServer().notifyClient(to_utf8(dispatch_buffer));
1812 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1813 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1819 string rest = split(argument, countstr, ' ');
1820 istringstream is(countstr);
1823 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1824 for (int i = 0; i < count; ++i)
1825 dispatch(lyxaction.lookupFunc(rest));
1829 case LFUN_COMMAND_SEQUENCE: {
1830 // argument contains ';'-terminated commands
1831 string arg = argument;
1832 // FIXME: this LFUN should also work without any view.
1833 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1834 ? &(current_view_->documentBufferView()->buffer()) : 0;
1836 buffer->undo().beginUndoGroup();
1837 while (!arg.empty()) {
1839 arg = split(arg, first, ';');
1840 FuncRequest func(lyxaction.lookupFunc(first));
1841 func.setOrigin(cmd.origin());
1844 // the buffer may have been closed by one action
1845 if (theBufferList().isLoaded(buffer))
1846 buffer->undo().endUndoGroup();
1850 case LFUN_BUFFER_FORALL: {
1851 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1853 map<Buffer *, GuiView *> views_lVisible;
1854 map<GuiView *, Buffer *> activeBuffers;
1856 QList<GuiView *> allViews = d->views_.values();
1858 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1859 // and on which buffer is active in each view.
1860 Buffer * const last = theBufferList().last();
1861 foreach (GuiView * view, allViews) {
1862 // all of the buffers might be locally hidden. That is, there is no active buffer.
1863 if (!view || !view->currentBufferView())
1864 activeBuffers[view] = 0;
1866 activeBuffers[view] = &view->currentBufferView()->buffer();
1868 // find out if each is locally visible or locally hidden.
1869 // we don't use a for loop as the buffer list cycles.
1870 Buffer * b = theBufferList().first();
1872 bool const locallyVisible = view && view->workArea(*b);
1873 if (locallyVisible) {
1874 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1875 // only need to overwrite/add if we don't already know a buffer is globally
1876 // visible or we do know but we would prefer to dispatch LFUN from the
1877 // current view because of cursor position issues.
1878 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1879 views_lVisible[b] = view;
1883 b = theBufferList().next(b);
1887 GuiView * const homeView = currentView();
1888 Buffer * b = theBufferList().first();
1889 Buffer * nextBuf = 0;
1890 int numProcessed = 0;
1893 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1895 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1897 // first change to a view where b is locally visible, preferably current_view_.
1898 GuiView * const vLv = views_lVisible[b];
1900 lyx::dispatch(funcToRun);
1908 // put things back to how they were (if possible).
1909 foreach (GuiView * view, allViews) {
1910 Buffer * originalBuf = activeBuffers[view];
1911 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1912 if (theBufferList().isLoaded(originalBuf))
1913 view->setBuffer(originalBuf);
1915 homeView->setFocus();
1917 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1921 case LFUN_COMMAND_ALTERNATIVES: {
1922 // argument contains ';'-terminated commands
1923 string arg = argument;
1924 while (!arg.empty()) {
1926 arg = split(arg, first, ';');
1927 FuncRequest func(lyxaction.lookupFunc(first));
1928 func.setOrigin(cmd.origin());
1929 FuncStatus const stat = getStatus(func);
1930 if (stat.enabled()) {
1940 if (theTopLevelCmdDef().lock(argument, func)) {
1941 func.setOrigin(cmd.origin());
1943 theTopLevelCmdDef().release(argument);
1945 if (func.action() == LFUN_UNKNOWN_ACTION) {
1946 // unknown command definition
1947 lyxerr << "Warning: unknown command definition `"
1951 // recursion detected
1952 lyxerr << "Warning: Recursion in the command definition `"
1953 << argument << "' detected"
1960 case LFUN_PREFERENCES_SAVE:
1961 lyxrc.write(support::makeAbsPath("preferences",
1962 package().user_support().absFileName()), false);
1965 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1966 string const fname = addName(addPath(package().user_support().absFileName(),
1967 "templates/"), "defaults.lyx");
1968 Buffer defaults(fname);
1970 istringstream ss(argument);
1975 // We need to make sure that, after we recreat the DocumentClass,
1976 // which we do in readHeader, we apply it to the document itself.
1977 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1978 int const unknown_tokens = defaults.readHeader(lex);
1979 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1981 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1982 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1984 if (unknown_tokens != 0) {
1985 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1986 << unknown_tokens << " unknown token"
1987 << (unknown_tokens == 1 ? "" : "s")
1991 if (defaults.writeFile(FileName(defaults.absFileName())))
1992 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1993 makeDisplayPath(fname)));
1996 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2001 case LFUN_BOOKMARK_GOTO:
2002 // go to bookmark, open unopened file and switch to buffer if necessary
2003 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2004 dr.screenUpdate(Update::Force | Update::FitCursor);
2007 case LFUN_BOOKMARK_CLEAR:
2008 theSession().bookmarks().clear();
2011 case LFUN_DEBUG_LEVEL_SET:
2012 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2015 case LFUN_DIALOG_SHOW: {
2016 string const name = cmd.getArg(0);
2018 if ( name == "aboutlyx"
2020 || name == "texinfo"
2021 || name == "progress"
2022 || name == "compare")
2024 // work around: on Mac OS the application
2025 // is not terminated when closing the last view.
2026 // Create a new one to be able to dispatch the
2027 // LFUN_DIALOG_SHOW to this view.
2028 if (current_view_ == 0)
2035 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2038 current_view_->dispatch(cmd, dr);
2042 if (cmd.origin() == FuncRequest::LYXSERVER)
2043 updateCurrentView(cmd, dr);
2047 docstring GuiApplication::viewStatusMessage()
2049 // When meta-fake key is pressed, show the key sequence so far + "M-".
2050 if (d->meta_fake_bit != NoModifier)
2051 return d->keyseq.print(KeySequence::ForGui) + "M-";
2053 // Else, when a non-complete key sequence is pressed,
2054 // show the available options.
2055 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2056 return d->keyseq.printOptions(true);
2062 void GuiApplication::handleKeyFunc(FuncCode action)
2066 if (d->keyseq.length())
2068 GuiView * gv = currentView();
2069 LASSERT(gv && gv->currentBufferView(), return);
2070 BufferView * bv = gv->currentBufferView();
2071 bv->getIntl().getTransManager().deadkey(
2072 c, get_accent(action).accent, bv->cursor().innerText(),
2074 // Need to clear, in case the minibuffer calls these
2077 // copied verbatim from do_accent_char
2078 bv->cursor().resetAnchor();
2082 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2084 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2086 // Do nothing if we have nothing (JMarc)
2087 if (!keysym.isOK()) {
2088 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2090 current_view_->restartCursor();
2094 if (keysym.isModifier()) {
2096 current_view_->restartCursor();
2100 char_type encoded_last_key = keysym.getUCSEncoded();
2102 // Do a one-deep top-level lookup for
2103 // cancel and meta-fake keys. RVDK_PATCH_5
2104 d->cancel_meta_seq.reset();
2106 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2107 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2109 // When not cancel or meta-fake, do the normal lookup.
2110 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2111 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2112 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2113 // remove Caps Lock and Mod2 as a modifiers
2114 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2115 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2118 // Dont remove this unless you know what you are doing.
2119 d->meta_fake_bit = NoModifier;
2121 // Can this happen now ?
2122 if (func.action() == LFUN_NOACTION)
2123 func = FuncRequest(LFUN_COMMAND_PREFIX);
2125 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2126 << d->keyseq.print(KeySequence::Portable) << ']');
2128 // already here we know if it any point in going further
2129 // why not return already here if action == -1 and
2130 // num_bytes == 0? (Lgb)
2132 if (d->keyseq.length() > 1 && current_view_)
2133 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2136 // Maybe user can only reach the key via holding down shift.
2137 // Let's see. But only if shift is the only modifier
2138 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2139 LYXERR(Debug::KEY, "Trying without shift");
2140 func = d->keyseq.addkey(keysym, NoModifier);
2141 LYXERR(Debug::KEY, "Action now " << func.action());
2144 if (func.action() == LFUN_UNKNOWN_ACTION) {
2145 // We didn't match any of the key sequences.
2146 // See if it's normal insertable text not already
2147 // covered by a binding
2148 if (keysym.isText() && d->keyseq.length() == 1) {
2149 // Non-printable characters (such as ASCII control characters)
2150 // must not be inserted (#5704)
2151 if (!isPrintable(encoded_last_key)) {
2152 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2154 current_view_->restartCursor();
2157 // The following modifier check is not needed on Mac.
2158 // The keysym is either not text or it is different
2159 // from the non-modifier keysym. See #9875 for the
2160 // broken alt-modifier effect of having this code active.
2161 #if !defined(Q_OS_MAC)
2162 // If a non-Shift Modifier is used we have a non-bound key sequence
2163 // (such as Alt+j = j). This should be omitted (#5575).
2164 // On Windows, AltModifier and ControlModifier are both
2165 // set when AltGr is pressed. Therefore, in order to not
2166 // break AltGr-bound symbols (see #5575 for details),
2167 // unbound Ctrl+Alt key sequences are allowed.
2168 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2169 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2170 && !(state & AltModifier && state & ControlModifier)
2174 if (current_view_) {
2175 current_view_->message(_("Unknown function."));
2176 current_view_->restartCursor();
2181 // Since all checks above were passed, we now really have text that
2182 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2183 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2185 LYXERR(Debug::KEY, "isText() is true, inserting.");
2186 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2188 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2189 if (current_view_) {
2190 current_view_->message(_("Unknown function."));
2191 current_view_->restartCursor();
2197 if (func.action() == LFUN_SELF_INSERT) {
2198 if (encoded_last_key != 0) {
2199 docstring const arg(1, encoded_last_key);
2200 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2201 FuncRequest::KEYBOARD));
2202 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2205 processFuncRequest(func);
2209 void GuiApplication::processFuncRequest(FuncRequest const & func)
2211 lyx::dispatch(func);
2215 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2217 addToFuncRequestQueue(func);
2218 processFuncRequestQueueAsync();
2222 void GuiApplication::processFuncRequestQueue()
2224 while (!d->func_request_queue_.empty()) {
2225 processFuncRequest(d->func_request_queue_.front());
2226 d->func_request_queue_.pop();
2231 void GuiApplication::processFuncRequestQueueAsync()
2233 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2237 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2239 d->func_request_queue_.push(func);
2243 void GuiApplication::resetGui()
2245 // Set the language defined by the user.
2249 if (!readUIFile(toqstr(lyxrc.ui_file)))
2250 // Gives some error box here.
2253 if (d->global_menubar_)
2254 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2256 QHash<int, GuiView *>::iterator it;
2257 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2260 gv->setLayoutDirection(layoutDirection());
2264 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2268 void GuiApplication::createView(int view_id)
2270 createView(QString(), true, view_id);
2274 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2277 // release the keyboard which might have been grabed by the global
2278 // menubar on Mac to catch shortcuts even without any GuiView.
2279 if (d->global_menubar_)
2280 d->global_menubar_->releaseKeyboard();
2284 while (d->views_.find(id) != d->views_.end())
2287 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2288 GuiView * view = new GuiView(id);
2290 d->views_[id] = view;
2294 setActiveWindow(view);
2297 if (!geometry_arg.isEmpty()) {
2298 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2302 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2303 re.indexIn(geometry_arg);
2304 w = re.cap(1).toInt();
2305 h = re.cap(2).toInt();
2306 x = re.cap(3).toInt();
2307 y = re.cap(4).toInt();
2308 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2309 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2310 // Set initial geometry such that we can get the frame size.
2311 view->setGeometry(x, y, w, h);
2312 int framewidth = view->geometry().x() - view->x();
2313 int titleheight = view->geometry().y() - view->y();
2314 // Negative displacements must be interpreted as distances
2315 // from the right or bottom screen borders.
2316 if (sx == '-' || sy == '-') {
2317 QRect rec = QApplication::desktop()->screenGeometry();
2319 x += rec.width() - w - framewidth;
2321 y += rec.height() - h - titleheight;
2322 view->setGeometry(x, y, w, h);
2324 // Make sure that the left and top frame borders are visible.
2325 if (view->x() < 0 || view->y() < 0) {
2330 view->setGeometry(x, y, w, h);
2338 Clipboard & GuiApplication::clipboard()
2340 return d->clipboard_;
2344 Selection & GuiApplication::selection()
2346 return d->selection_;
2350 FontLoader & GuiApplication::fontLoader()
2352 return d->font_loader_;
2356 Toolbars const & GuiApplication::toolbars() const
2358 return d->toolbars_;
2362 Toolbars & GuiApplication::toolbars()
2364 return d->toolbars_;
2368 Menus const & GuiApplication::menus() const
2374 Menus & GuiApplication::menus()
2380 QList<int> GuiApplication::viewIds() const
2382 return d->views_.keys();
2386 ColorCache & GuiApplication::colorCache()
2388 return d->color_cache_;
2392 int GuiApplication::exec()
2394 // asynchronously handle batch commands. This event will be in
2395 // the event queue in front of other asynchronous events. Hence,
2396 // we can assume in the latter that the gui is setup already.
2397 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2399 return QApplication::exec();
2403 void GuiApplication::exit(int status)
2405 QApplication::exit(status);
2409 void GuiApplication::setGuiLanguage()
2413 // install translation file for Qt built-in dialogs
2414 QString const language_name = QString("qt_") + theLocale.name();
2415 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2416 // Short-named translator can be loaded from a long name, but not the
2417 // opposite. Therefore, long name should be used without truncation.
2418 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2419 if (!d->qt_trans_.load(language_name,
2420 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2421 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2424 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2428 switch (theLocale.language()) {
2429 case QLocale::Arabic :
2430 case QLocale::Hebrew :
2431 case QLocale::Persian :
2432 case QLocale::Urdu :
2433 setLayoutDirection(Qt::RightToLeft);
2436 setLayoutDirection(Qt::LeftToRight);
2441 void GuiApplication::execBatchCommands()
2446 if (!readUIFile(toqstr(lyxrc.ui_file)))
2447 // Gives some error box here.
2451 #if QT_VERSION > 0x040600
2452 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2454 #if QT_VERSION > 0x050100
2455 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2457 // Create the global default menubar which is shown for the dialogs
2458 // and if no GuiView is visible.
2459 // This must be done after the session was recovered to know the "last files".
2460 d->global_menubar_ = new QMenuBar(0);
2461 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2464 lyx::execBatchCommands();
2468 QAbstractItemModel * GuiApplication::languageModel()
2470 if (d->language_model_)
2471 return d->language_model_;
2473 QStandardItemModel * lang_model = new QStandardItemModel(this);
2474 lang_model->insertColumns(0, 3);
2475 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2476 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2477 Languages::const_iterator it = lyx::languages.begin();
2478 Languages::const_iterator end = lyx::languages.end();
2479 for (; it != end; ++it) {
2480 int current_row = lang_model->rowCount();
2481 lang_model->insertRows(current_row, 1);
2482 QModelIndex pl_item = lang_model->index(current_row, 0);
2483 QModelIndex sp_item = lang_model->index(current_row, 1);
2484 QModelIndex th_item = lang_model->index(current_row, 2);
2485 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2486 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2487 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2488 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2489 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2490 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2491 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2492 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2493 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2494 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2496 d->language_model_ = new QSortFilterProxyModel(this);
2497 d->language_model_->setSourceModel(lang_model);
2498 d->language_model_->setSortLocaleAware(true);
2499 return d->language_model_;
2503 void GuiApplication::restoreGuiSession()
2505 if (!lyxrc.load_session)
2508 Session & session = theSession();
2509 LastOpenedSection::LastOpened const & lastopened =
2510 session.lastOpened().getfiles();
2512 validateCurrentView();
2514 FileName active_file;
2515 // do not add to the lastfile list since these files are restored from
2516 // last session, and should be already there (regular files), or should
2517 // not be added at all (help files).
2518 for (size_t i = 0; i < lastopened.size(); ++i) {
2519 FileName const & file_name = lastopened[i].file_name;
2520 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2521 && current_view_->documentBufferView() != 0)) {
2522 boost::crc_32_type crc;
2523 string const & fname = file_name.absFileName();
2524 crc = for_each(fname.begin(), fname.end(), crc);
2525 createView(crc.checksum());
2527 current_view_->loadDocument(file_name, false);
2529 if (lastopened[i].active)
2530 active_file = file_name;
2533 // Restore last active buffer
2534 Buffer * buffer = theBufferList().getBuffer(active_file);
2535 if (buffer && current_view_)
2536 current_view_->setBuffer(buffer);
2538 // clear this list to save a few bytes of RAM
2539 session.lastOpened().clear();
2543 QString const GuiApplication::romanFontName()
2546 font.setStyleHint(QFont::Serif);
2547 font.setFamily("serif");
2549 return QFontInfo(font).family();
2553 QString const GuiApplication::sansFontName()
2556 font.setStyleHint(QFont::SansSerif);
2557 font.setFamily("sans");
2559 return QFontInfo(font).family();
2563 QString const GuiApplication::typewriterFontName()
2565 return QFontInfo(typewriterSystemFont()).family();
2570 // We cannot use QFont::fixedPitch() because it doesn't
2571 // return the fact but only if it is requested.
2572 static bool isFixedPitch(const QFont & font) {
2573 const QFontInfo fi(font);
2574 return fi.fixedPitch();
2579 QFont const GuiApplication::typewriterSystemFont()
2581 #if QT_VERSION >= 0x050200
2582 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2584 QFont font("monospace");
2586 if (!isFixedPitch(font)) {
2587 // try to enforce a real monospaced font
2588 font.setStyleHint(QFont::Monospace);
2589 if (!isFixedPitch(font)) {
2590 font.setStyleHint(QFont::TypeWriter);
2591 if (!isFixedPitch(font)) font.setFamily("courier");
2595 // On a Mac the result is too small and it's not practical to
2596 // rely on Qtconfig utility to change the system settings of Qt.
2597 font.setPointSize(12);
2603 void GuiApplication::handleRegularEvents()
2605 ForkedCallsController::handleCompletedProcesses();
2609 bool GuiApplication::event(QEvent * e)
2612 case QEvent::FileOpen: {
2613 // Open a file; this happens only on Mac OS X for now.
2615 // We do this asynchronously because on startup the batch
2616 // commands are not executed here yet and the gui is not ready
2618 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2619 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2620 processFuncRequestAsync(fr);
2625 return QApplication::event(e);
2630 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2633 return QApplication::notify(receiver, event);
2635 catch (ExceptionMessage const & e) {
2637 case ErrorException:
2639 setQuitOnLastWindowClosed(false);
2641 Alert::error(e.title_, e.details_);
2643 // Properly crash in debug mode in order to get a useful backtrace.
2646 // In release mode, try to exit gracefully.
2649 case BufferException: {
2650 if (!current_view_ || !current_view_->documentBufferView())
2652 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2653 docstring details = e.details_ + '\n';
2654 details += buf->emergencyWrite();
2655 theBufferList().release(buf);
2656 details += "\n" + _("The current document was closed.");
2657 Alert::error(e.title_, details);
2660 case WarningException:
2661 Alert::warning(e.title_, e.details_);
2665 catch (exception const & e) {
2666 docstring s = _("LyX has caught an exception, it will now "
2667 "attempt to save all unsaved documents and exit."
2669 s += from_ascii(e.what());
2670 Alert::error(_("Software exception Detected"), s);
2674 docstring s = _("LyX has caught some really weird exception, it will "
2675 "now attempt to save all unsaved documents and exit.");
2676 Alert::error(_("Software exception Detected"), s);
2684 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2686 QColor const & qcol = d->color_cache_.get(col);
2687 if (!qcol.isValid()) {
2693 rgbcol.r = qcol.red();
2694 rgbcol.g = qcol.green();
2695 rgbcol.b = qcol.blue();
2700 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2702 QColor const qcol(lcolor.getX11Name(col).c_str());
2703 if (!qcol.isValid()) {
2709 rgbcol.r = qcol.red();
2710 rgbcol.g = qcol.green();
2711 rgbcol.b = qcol.blue();
2716 string const GuiApplication::hexName(ColorCode col)
2718 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2722 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2724 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2725 d->socket_notifiers_[fd] = sn;
2726 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2730 void GuiApplication::socketDataReceived(int fd)
2732 d->socket_notifiers_[fd]->func_();
2736 void GuiApplication::unregisterSocketCallback(int fd)
2738 d->socket_notifiers_.take(fd)->setEnabled(false);
2742 void GuiApplication::commitData(QSessionManager & sm)
2744 /** The implementation is required to avoid an application exit
2745 ** when session state save is triggered by session manager.
2746 ** The default implementation sends a close event to all
2747 ** visible top level widgets when session managment allows
2749 ** We are changing that to check the state of each buffer in all
2750 ** views and ask the users what to do if buffers are dirty.
2751 ** Furthermore, we save the session state.
2752 ** We do NOT close the views here since the user still can cancel
2753 ** the logout process (see #9277); also, this would hide LyX from
2754 ** an OSes own session handling (application restoration).
2756 #ifdef QT_NO_SESSIONMANAGER
2758 #warning Qt is compiled without session manager
2760 #pragma message("warning: Qt is compiled without session manager")
2764 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2772 void GuiApplication::unregisterView(GuiView * gv)
2774 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2775 d->views_.remove(gv->id());
2776 if (current_view_ == gv)
2782 bool GuiApplication::closeAllViews()
2784 if (d->views_.empty())
2787 // When a view/window was closed before without quitting LyX, there
2788 // are already entries in the lastOpened list.
2789 theSession().lastOpened().clear();
2791 QList<GuiView *> const views = d->views_.values();
2792 foreach (GuiView * view, views) {
2793 if (!view->closeScheduled())
2802 bool GuiApplication::prepareAllViewsForLogout()
2804 if (d->views_.empty())
2807 QList<GuiView *> const views = d->views_.values();
2808 foreach (GuiView * view, views) {
2809 if (!view->prepareAllBuffersForLogout())
2817 GuiView & GuiApplication::view(int id) const
2819 LAPPERR(d->views_.contains(id));
2820 return *d->views_.value(id);
2824 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2826 QList<GuiView *> const views = d->views_.values();
2827 foreach (GuiView * view, views)
2828 view->hideDialog(name, inset);
2832 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2834 Buffer const * buffer_ = 0;
2835 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2836 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2837 if (Buffer const * ptr = (*it)->updateInset(inset))
2844 bool GuiApplication::searchMenu(FuncRequest const & func,
2845 docstring_list & names) const
2847 return d->menus_.searchMenu(func, names);
2851 // Ensure that a file is read only once (prevents include loops)
2852 static QStringList uifiles;
2853 // store which ui files define Toolbars
2854 static QStringList toolbar_uifiles;
2857 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2868 LexerKeyword uitags[] = {
2869 { "format", ui_format },
2870 { "include", ui_include },
2871 { "menuset", ui_menuset },
2872 { "toolbars", ui_toolbars },
2873 { "toolbarset", ui_toolbarset }
2877 lex.setFile(ui_path);
2879 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2883 if (lyxerr.debugging(Debug::PARSER))
2884 lex.printTable(lyxerr);
2887 // format before introduction of format tag
2888 unsigned int format = 0;
2889 while (lex.isOK()) {
2890 int const status = lex.lex();
2892 // we have to do this check here, outside the switch,
2893 // because otherwise we would start reading include files,
2894 // e.g., if the first tag we hit was an include tag.
2895 if (status == ui_format)
2897 format = lex.getInteger();
2901 // this will trigger unless the first tag we hit is a format
2902 // tag, with the right format.
2903 if (format != LFUN_FORMAT)
2904 return FormatMismatch;
2907 case Lexer::LEX_FEOF:
2912 QString const file = toqstr(lex.getString());
2913 bool const success = readUIFile(file, true);
2915 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2922 d->menus_.read(lex);
2926 d->toolbars_.readToolbars(lex);
2930 d->toolbars_.readToolbarSettings(lex);
2931 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2935 if (!rtrim(lex.getString()).empty())
2936 lex.printError("LyX::ReadUIFile: "
2937 "Unknown menu tag: `$$Token'");
2939 LYXERR0("Error with status: " << status);
2945 return (error ? ReadError : ReadOK);
2949 bool GuiApplication::readUIFile(QString const & name, bool include)
2951 LYXERR(Debug::INIT, "About to read " << name << "...");
2955 ui_path = libFileSearch("ui", name, "inc");
2956 if (ui_path.empty())
2957 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2959 ui_path = libFileSearch("ui", name, "ui");
2962 if (ui_path.empty()) {
2963 static const QString defaultUIFile = "default";
2964 LYXERR(Debug::INIT, "Could not find " << name);
2966 Alert::warning(_("Could not find UI definition file"),
2967 bformat(_("Error while reading the included file\n%1$s\n"
2968 "Please check your installation."), qstring_to_ucs4(name)));
2971 if (name == defaultUIFile) {
2972 LYXERR(Debug::INIT, "Could not find default UI file!!");
2973 Alert::warning(_("Could not find default UI file"),
2974 _("LyX could not find the default UI file!\n"
2975 "Please check your installation."));
2978 Alert::warning(_("Could not find UI definition file"),
2979 bformat(_("Error while reading the configuration file\n%1$s\n"
2980 "Falling back to default.\n"
2981 "Please look under Tools>Preferences>User Interface and\n"
2982 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2983 return readUIFile(defaultUIFile, false);
2986 QString const uifile = toqstr(ui_path.absFileName());
2987 if (uifiles.contains(uifile)) {
2989 // We are reading again the top uifile so reset the safeguard:
2992 d->toolbars_.reset();
2994 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2995 << "Is this an include loop?");
2999 uifiles.push_back(uifile);
3001 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3003 ReturnValues retval = readUIFile(ui_path);
3005 if (retval == FormatMismatch) {
3006 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3007 TempFile tmp("convertXXXXXX.ui");
3008 FileName const tempfile = tmp.name();
3009 bool const success = prefs2prefs(ui_path, tempfile, true);
3011 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3012 " to format " << LFUN_FORMAT << ".");
3014 retval = readUIFile(tempfile);
3018 if (retval != ReadOK) {
3019 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3027 settings.beginGroup("ui_files");
3028 bool touched = false;
3029 for (int i = 0; i != uifiles.size(); ++i) {
3030 QFileInfo fi(uifiles[i]);
3031 QDateTime const date_value = fi.lastModified();
3032 QString const name_key = QString::number(i);
3033 // if an ui file which defines Toolbars has changed,
3034 // we have to reset the settings
3035 if (toolbar_uifiles.contains(uifiles[i])
3036 && (!settings.contains(name_key)
3037 || settings.value(name_key).toString() != uifiles[i]
3038 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3040 settings.setValue(name_key, uifiles[i]);
3041 settings.setValue(name_key + "/date", date_value);
3044 settings.endGroup();
3046 settings.remove("views");
3052 void GuiApplication::onLastWindowClosed()
3054 if (d->global_menubar_)
3055 d->global_menubar_->grabKeyboard();
3059 void GuiApplication::startLongOperation() {
3060 d->key_checker_.start();
3064 bool GuiApplication::longOperationCancelled() {
3065 return d->key_checker_.pressed();
3069 void GuiApplication::stopLongOperation() {
3070 d->key_checker_.stop();
3074 bool GuiApplication::longOperationStarted() {
3075 return d->key_checker_.started();
3079 ////////////////////////////////////////////////////////////////////////
3081 // X11 specific stuff goes here...
3084 bool GuiApplication::x11EventFilter(XEvent * xev)
3089 switch (xev->type) {
3090 case SelectionRequest: {
3091 if (xev->xselectionrequest.selection != XA_PRIMARY)
3093 LYXERR(Debug::SELECTION, "X requested selection.");
3094 BufferView * bv = current_view_->currentBufferView();
3096 docstring const sel = bv->requestSelection();
3098 d->selection_.put(sel);
3102 case SelectionClear: {
3103 if (xev->xselectionclear.selection != XA_PRIMARY)
3105 LYXERR(Debug::SELECTION, "Lost selection.");
3106 BufferView * bv = current_view_->currentBufferView();
3108 bv->clearSelection();
3114 #elif defined(QPA_XCB)
3115 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3116 void * message, long *)
3118 if (!current_view_ || eventType != "xcb_generic_event_t")
3121 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3123 switch (ev->response_type) {
3124 case XCB_SELECTION_REQUEST: {
3125 xcb_selection_request_event_t * srev =
3126 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3127 if (srev->selection != XCB_ATOM_PRIMARY)
3129 LYXERR(Debug::SELECTION, "X requested selection.");
3130 BufferView * bv = current_view_->currentBufferView();
3132 docstring const sel = bv->requestSelection();
3134 d->selection_.put(sel);
3138 case XCB_SELECTION_CLEAR: {
3139 xcb_selection_clear_event_t * scev =
3140 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3141 if (scev->selection != XCB_ATOM_PRIMARY)
3143 LYXERR(Debug::SELECTION, "Lost selection.");
3144 BufferView * bv = current_view_->currentBufferView();
3146 bv->clearSelection();
3154 } // namespace frontend
3157 void hideDialogs(std::string const & name, Inset * inset)
3160 frontend::guiApp->hideDialogs(name, inset);
3164 ////////////////////////////////////////////////////////////////////
3168 ////////////////////////////////////////////////////////////////////
3170 frontend::FontLoader & theFontLoader()
3172 LAPPERR(frontend::guiApp);
3173 return frontend::guiApp->fontLoader();
3177 frontend::FontMetrics const & theFontMetrics(Font const & f)
3179 return theFontMetrics(f.fontInfo());
3183 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3185 LAPPERR(frontend::guiApp);
3186 return frontend::guiApp->fontLoader().metrics(f);
3190 ////////////////////////////////////////////////////////////////////
3194 ////////////////////////////////////////////////////////////////////
3196 frontend::Clipboard & theClipboard()
3198 LAPPERR(frontend::guiApp);
3199 return frontend::guiApp->clipboard();
3203 frontend::Selection & theSelection()
3205 LAPPERR(frontend::guiApp);
3206 return frontend::guiApp->selection();
3212 #include "moc_GuiApplication.cpp"