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 "Converter.h"
39 #include "CutAndPaste.h"
40 #include "ErrorList.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
44 #include "GuiWorkArea.h"
48 #include "LaTeXPackages.h"
51 #include "LyXAction.h"
53 #include "Paragraph.h"
56 #include "SpellChecker.h"
57 #include "Thesaurus.h"
60 #include "insets/InsetText.h"
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/ExceptionMessage.h"
65 #include "support/FileName.h"
66 #include "support/filetools.h"
67 #include "support/foreach.h"
68 #include "support/ForkedCalls.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/lstrings.h"
72 #include "support/lyxalgo.h" // sorted
73 #include "support/textutils.h"
74 #include "support/Messages.h"
75 #include "support/os.h"
76 #include "support/Package.h"
77 #include "support/TempFile.h"
80 #include "support/AppleScript.h"
81 #include "support/linkback/LinkBackProxy.h"
86 #include <QFontDatabase>
90 #include <QDesktopWidget>
94 #include <QFileOpenEvent>
98 #include <QImageReader>
101 #include <QLibraryInfo>
107 #include <QPixmapCache>
109 #include <QSessionManager>
111 #include <QShowEvent>
112 #include <QSocketNotifier>
113 #include <QSortFilterProxyModel>
114 #include <QStandardItemModel>
115 #include <QTextCodec>
117 #include <QTranslator>
118 #include <QThreadPool>
122 #include <X11/Xatom.h>
123 #include <X11/Xlib.h>
126 #elif defined(QPA_XCB)
130 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
131 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
132 #if (QT_VERSION < 0x050000)
133 #include <QWindowsMime>
134 #define QWINDOWSMIME QWindowsMime
137 #define QWINDOWSMIME QWinMime
147 #include <QMacPasteboardMime>
150 #include "support/bind.h"
151 #include <boost/crc.hpp>
158 using namespace lyx::support;
161 static void initializeResources()
163 static bool initialized = false;
165 Q_INIT_RESOURCE(Resources);
173 frontend::Application * createApplication(int & argc, char * argv[])
175 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
176 // prune -geometry argument(s) by shifting
177 // the following ones 2 places down.
178 for (int i = 0 ; i < argc ; ++i) {
179 if (strcmp(argv[i], "-geometry") == 0) {
180 int const remove = (i+1) < argc ? 2 : 1;
182 for (int j = i; j < argc; ++j)
183 argv[j] = argv[j + remove];
188 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
189 // I'd rather do that in the constructor, but I do not think that
190 // the palette is accessible there.
191 guiApp->colorCache().setPalette(guiApp->palette());
200 if (lyxrc.gui_language == "auto") {
201 theLocale = QLocale::system();
202 code = fromqstr(theLocale.name());
204 Language const * l = languages.getLanguage(lyxrc.gui_language);
205 code = l ? l->code() : "C";
206 theLocale = QLocale(toqstr(code));
208 // Qt tries to outsmart us and transforms en_US to C.
209 Messages::guiLanguage((code == "C") ? "en_US" : code);
210 QLocale::setDefault(theLocale);
211 setlocale(LC_NUMERIC, "C");
218 /// Return the list of loadable formats.
219 vector<string> loadableImageFormats()
223 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
225 LYXERR(Debug::GRAPHICS,
226 "\nThe image loader can load the following directly:\n");
228 if (qt_formats.empty())
229 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
231 bool jpeg_found = false;
232 bool jpg_found = false;
233 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
235 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
237 string ext = ascii_lowercase((const char *) *it);
245 else if (ext == "jpg") {
250 else if (lyxrc.use_converter_cache &&
251 (ext == "svg" || ext == "svgz") &&
252 theConverters().isReachable("svg", "png"))
253 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
254 // the SVG as in the output. However we require that the converter
255 // cache is enabled since this is expensive. We also require that
256 // an explicit svg->png converter is defined, since the default
257 // converter could produce bad quality as well. This assumes that
258 // png can always be loaded.
267 ////////////////////////////////////////////////////////////////////////
269 // Icon loading support code
271 ////////////////////////////////////////////////////////////////////////
281 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
283 return lhs.key < rhs.key;
289 CompareKey(QString const & name) : name_(name) {}
290 bool operator()(ImgMap const & other) const { return other.key == name_; }
296 // this must be sorted alphabetically
297 // Upper case comes before lower case
298 // Please don't change the formatting, this list is parsed by
299 // development/tools/generate_symbols_images.py.
300 ImgMap sorted_img_map[] = {
301 { "Arrownot", "arrownot2"},
302 { "Arrowvert", "arrowvert2"},
303 { "Bowtie", "bowtie2" },
305 { "Bumpeq", "bumpeq2" },
306 { "CIRCLE", "circle3" },
308 { "CheckedBox", "checkedbox2" },
309 { "Circle", "circle2" },
310 { "Colonapprox", "colonapprox2" },
311 { "Coloneq", "coloneq2" },
312 { "Coloneqq", "coloneqq2" },
313 { "Colonsim", "colonsim2" },
315 { "DOWNarrow", "downarrow3" },
316 { "Delta", "delta2" },
317 { "Diamond", "diamond2" },
318 { "Doteq", "doteq2" },
319 { "Downarrow", "downarrow2" },
320 { "Eqcolon", "eqcolon2" },
321 { "Eqqcolon", "eqqcolon2" },
322 { "Gamma", "gamma2" },
324 { "LEFTCIRCLE", "leftcircle3" },
325 { "LEFTarrow", "leftarrow3" },
326 { "LEFTcircle", "leftcircle4" },
328 { "Lambda", "lambda2" },
330 { "Leftarrow", "leftarrow2" },
331 { "Leftcircle", "leftcircle2" },
332 { "Leftrightarrow", "leftrightarrow2" },
333 { "Longarrownot", "longarrownot2"},
334 { "Longleftarrow", "longleftarrow2" },
335 { "Longleftrightarrow", "longleftrightarrow2" },
336 { "Longmapsfrom", "longmapsfrom2"},
337 { "Longmapsto", "longmapsto2"},
338 { "Longrightarrow", "longrightarrow2" },
339 { "Mapsfrom", "mapsfrom2"},
340 { "Mapsfromchar", "mapsfromchar2"},
341 { "Mapsto", "mapsto2"},
342 { "Mapstochar", "mapstochar2"},
343 { "Omega", "omega2" },
348 { "RIGHTCIRCLE", "rightcircle3" },
349 { "RIGHTarrow", "rightarrow3" },
350 { "RIGHTcircle", "rightcircle4" },
352 { "Rightarrow", "rightarrow2" },
353 { "Rightcircle", "rightcircle2" },
354 { "Sigma", "sigma2" },
355 { "Square", "square2" },
356 { "Subset", "subset2" },
357 { "Supset", "supset2" },
358 { "Theta", "theta2" },
359 { "Thorn", "thorn2" },
360 { "UParrow", "uparrow3" },
361 { "Uparrow", "uparrow2" },
362 { "Updownarrow", "updownarrow2" },
363 { "Upsilon", "upsilon2" },
364 { "Vdash", "vdash3" },
369 { "lVert", "vert2" },
371 { "nLeftarrow", "nleftarrow2" },
372 { "nLeftrightarrow", "nleftrightarrow2" },
373 { "nRightarrow", "nrightarrow2" },
374 { "nVDash", "nvdash3" },
375 { "nVdash", "nvdash4" },
376 { "nvDash", "nvdash2" },
377 { "rVert", "vert2" },
379 { "textrm \\AA", "textrm_AA"},
380 { "textrm \\O", "textrm_O"},
381 { "vDash", "vdash2" },
382 { "varDelta", "vardelta2" },
383 { "varGamma", "vargamma2" },
384 { "varLambda", "varlambda2" },
385 { "varOmega", "varomega2" },
386 { "varPhi", "varphi2" },
387 { "varPi", "varpi2" },
388 { "varPsi", "varpsi2" },
389 { "varSigma", "varsigma2" },
390 { "varTheta", "vartheta2" },
391 { "varUpsilon", "varupsilon2" },
392 { "varXi", "varxi2" }
396 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
398 // This list specifies which system's theme icon is related to which lyx
399 // command. It was based on:
400 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
401 // this must be sorted alphabetically
402 // Upper case comes before lower case
403 ImgMap sorted_theme_icon_map[] = {
404 { "bookmark-goto 0", "go-jump" },
405 { "buffer-new", "document-new" },
406 { "buffer-write", "document-save" },
407 { "buffer-write-as", "document-save-as" },
408 { "buffer-zoom-in", "zoom-in" },
409 { "buffer-zoom-out", "zoom-out" },
410 { "copy", "edit-copy" },
411 { "cut", "edit-cut" },
412 { "depth-decrement", "format-indent-less" },
413 { "depth-increment", "format-indent-more" },
414 { "dialog-show spellchecker", "tools-check-spelling" },
415 { "dialog-show-new-inset graphics", "insert-image" },
416 { "dialog-toggle findreplaceadv", "edit-find-replace" },
417 { "file-open", "document-open" },
418 { "font-bold", "format-text-bold" },
419 { "font-ital", "format-text-italic" },
420 { "font-strikeout", "format-text-strikethrough" },
421 { "font-underline", "format-text-underline" },
422 { "lyx-quit", "application-exit" },
423 { "paste", "edit-paste" },
424 { "redo", "edit-redo" },
425 { "undo", "edit-undo" },
426 { "window-close", "window-close" },
427 { "window-new", "window-new" }
430 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
433 QString findImg(QString const & name)
435 ImgMap const * const begin = sorted_img_map;
436 ImgMap const * const end = begin + nr_sorted_img_map;
437 LATTEST(sorted(begin, end));
439 ImgMap const * const it = find_if(begin, end, CompareKey(name));
443 img_name = it->value;
446 img_name.replace('_', "underscore");
447 img_name.replace(' ', '_');
449 // This way we can have "math-delim { }" on the toolbar.
450 img_name.replace('(', "lparen");
451 img_name.replace(')', "rparen");
452 img_name.replace('[', "lbracket");
453 img_name.replace(']', "rbracket");
454 img_name.replace('{', "lbrace");
455 img_name.replace('}', "rbrace");
456 img_name.replace('|', "bars");
457 img_name.replace(',', "thinspace");
458 img_name.replace(':', "mediumspace");
459 img_name.replace(';', "thickspace");
460 img_name.replace('!', "negthinspace");
463 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
464 << "Looking for math icon called \"" << img_name << '"');
471 QString themeIconName(QString const & action)
473 ImgMap const * const begin = sorted_theme_icon_map;
474 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
475 LASSERT(sorted(begin, end), /**/);
477 ImgMap const * const it = find_if(begin, end, CompareKey(action));
485 QString iconName(FuncRequest const & f, bool unknown)
487 initializeResources();
491 switch (f.action()) {
492 case LFUN_MATH_INSERT:
493 if (!f.argument().empty()) {
495 name1 = findImg(toqstr(f.argument()).mid(1));
498 case LFUN_MATH_DELIM:
499 case LFUN_MATH_BIGDELIM:
501 name1 = findImg(toqstr(f.argument()));
505 name1 = toqstr(f.argument());
507 case LFUN_COMMAND_ALTERNATIVES: {
508 // use the first of the alternative commands
510 docstring dummy = split(f.argument(), firstcom, ';');
511 name1 = toqstr(firstcom);
512 name1.replace(' ', '_');
516 name2 = toqstr(lyxaction.getActionName(f.action()));
519 if (!f.argument().empty()) {
520 name1 = name2 + ' ' + toqstr(f.argument());
521 name1.replace(' ', '_');
522 name1.replace('\\', "backslash");
526 QStringList imagedirs;
527 imagedirs << "images/" << "images/ipa/";
528 search_mode mode = theGuiApp()->imageSearchMode();
529 for (int i = 0; i < imagedirs.size(); ++i) {
530 QString imagedir = imagedirs.at(i) + path;
531 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
533 return toqstr(fname.absFileName());
535 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
537 return toqstr(fname.absFileName());
540 path = ":/images/" + path;
543 LYXERR0("Directory " << path << " not found in resource!");
546 if (res.exists(name1 + ".svgz"))
547 return path + name1 + ".svgz";
548 else if (res.exists(name1 + ".png"))
549 return path + name1 + ".png";
551 if (res.exists(name2 + ".svgz"))
552 return path + name2 + ".svgz";
553 else if (res.exists(name2 + ".png"))
554 return path + name2 + ".png";
556 LYXERR(Debug::GUI, "Cannot find icon with filename "
557 << "\"" << name1 << ".{svgz,png}\""
559 << "\"" << name2 << ".{svgz,png}\""
561 << lyxaction.getActionName(f.action())
562 << '(' << to_utf8(f.argument()) << ")\"");
565 QString imagedir = "images/";
566 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
568 return toqstr(fname.absFileName());
569 return QString(":/images/unknown.svgz");
576 bool getPixmap(QPixmap & pixmap, QString const & path)
578 return pixmap.load(path);
582 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
584 QString imagedir = path;
585 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
586 QString fpath = toqstr(fname.absFileName());
587 QPixmap pixmap = QPixmap();
589 if (getPixmap(pixmap, fpath)) {
593 QStringList exts = ext.split(",");
594 fpath = ":/" + path + name + ".";
595 for (int i = 0; i < exts.size(); ++i) {
596 if (getPixmap(pixmap, fpath + exts.at(i))) {
601 bool const list = ext.contains(",");
602 LYXERR0("Cannot load pixmap \""
603 << path << name << "." << (list ? "{" : "") << ext
604 << (list ? "}" : "") << "\", please verify resource system!");
610 QIcon getIcon(FuncRequest const & f, bool unknown)
612 #if (QT_VERSION >= 0x040600)
613 if (lyxrc.use_system_theme_icons) {
614 // use the icons from system theme that are available
615 QString action = toqstr(lyxaction.getActionName(f.action()));
616 if (!f.argument().empty())
617 action += " " + toqstr(f.argument());
618 QString const theme_icon = themeIconName(action);
619 if (QIcon::hasThemeIcon(theme_icon)) {
620 QIcon const thmicn = QIcon::fromTheme(theme_icon);
621 if (!thmicn.isNull())
627 QString icon = iconName(f, unknown);
631 //LYXERR(Debug::GUI, "Found icon: " << icon);
632 QPixmap pixmap = QPixmap();
633 if (!getPixmap(pixmap,icon)) {
634 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
638 return QIcon(pixmap);
642 ////////////////////////////////////////////////////////////////////////
644 // LyX server support code.
646 ////////////////////////////////////////////////////////////////////////
648 class SocketNotifier : public QSocketNotifier
651 /// connect a connection notification from the LyXServerSocket
652 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
653 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
657 /// The callback function
658 Application::SocketCallback func_;
662 ////////////////////////////////////////////////////////////////////////
664 // Mac specific stuff goes here...
666 ////////////////////////////////////////////////////////////////////////
668 class MenuTranslator : public QTranslator
671 MenuTranslator(QObject * parent)
672 : QTranslator(parent)
675 #if QT_VERSION >= 0x050000
676 virtual QString translate(const char * /* context */,
677 const char *sourceText,
678 const char * /* disambiguation */ = 0, int /* n */ = -1) const
680 QString translate(const char * /*context*/,
681 const char * sourceText,
682 const char * /*comment*/ = 0) const
685 string const s = sourceText;
686 if (s == N_("About %1") || s == N_("Preferences")
687 || s == N_("Reconfigure") || s == N_("Quit %1"))
695 // QMacPasteboardMimeGraphics can only be compiled on Mac.
697 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
700 QMacPasteboardMimeGraphics()
701 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
704 QString convertorName() { return "Graphics"; }
706 QString flavorFor(QString const & mime)
708 LYXERR(Debug::ACTION, "flavorFor " << mime);
709 if (mime == pdfMimeType())
710 return QLatin1String("com.adobe.pdf");
714 QString mimeFor(QString flav)
716 LYXERR(Debug::ACTION, "mimeFor " << flav);
717 if (flav == QLatin1String("com.adobe.pdf"))
718 return pdfMimeType();
722 bool canConvert(QString const & mime, QString flav)
724 return mimeFor(flav) == mime;
727 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
731 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
735 QList<QByteArray> convertFromMime(QString const & /*mime*/,
736 QVariant data, QString /*flav*/)
738 QList<QByteArray> ret;
739 ret.append(data.toByteArray());
745 ///////////////////////////////////////////////////////////////
747 // You can find more platform specific stuff at the end of this file...
749 ///////////////////////////////////////////////////////////////
751 ////////////////////////////////////////////////////////////////////////
752 // Windows specific stuff goes here...
754 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
755 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
756 // QWindowsMimeMetafile can only be compiled on Windows.
758 static FORMATETC cfFromMime(QString const & mimetype)
761 if (mimetype == emfMimeType()) {
762 formatetc.cfFormat = CF_ENHMETAFILE;
763 formatetc.tymed = TYMED_ENHMF;
764 } else if (mimetype == wmfMimeType()) {
765 formatetc.cfFormat = CF_METAFILEPICT;
766 formatetc.tymed = TYMED_MFPICT;
769 formatetc.dwAspect = DVASPECT_CONTENT;
770 formatetc.lindex = -1;
775 class QWindowsMimeMetafile : public QWINDOWSMIME {
777 QWindowsMimeMetafile() {}
779 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
780 QMimeData const * /*mimedata*/) const
785 bool canConvertToMime(QString const & mimetype,
786 IDataObject * pDataObj) const
788 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
790 FORMATETC formatetc = cfFromMime(mimetype);
791 return pDataObj->QueryGetData(&formatetc) == S_OK;
794 bool convertFromMime(FORMATETC const & /*formatetc*/,
795 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
800 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
801 QVariant::Type /*preferredType*/) const
804 if (!canConvertToMime(mimetype, pDataObj))
807 FORMATETC formatetc = cfFromMime(mimetype);
809 if (pDataObj->GetData(&formatetc, &s) != S_OK)
813 if (s.tymed == TYMED_ENHMF) {
814 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
815 data.resize(dataSize);
816 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
817 (LPBYTE)data.data());
818 } else if (s.tymed == TYMED_MFPICT) {
819 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
820 data.resize(dataSize);
821 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
822 (LPBYTE)data.data());
825 ReleaseStgMedium(&s);
831 QVector<FORMATETC> formatsForMime(QString const & mimetype,
832 QMimeData const * /*mimedata*/) const
834 QVector<FORMATETC> formats;
835 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
836 formats += cfFromMime(mimetype);
840 QString mimeForFormat(FORMATETC const & formatetc) const
842 switch (formatetc.cfFormat) {
844 return emfMimeType();
845 case CF_METAFILEPICT:
846 return wmfMimeType();
856 /// Allows to check whether ESC was pressed during a long operation
857 class KeyChecker : public QObject {
862 KeyChecker() : pressed_(false), started_(false) {}
865 QCoreApplication::instance()->installEventFilter(this);
870 QCoreApplication::instance()->removeEventFilter(this);
874 QCoreApplication::processEvents();
877 bool started() const {
880 bool eventFilter(QObject *obj, QEvent *event) {
881 LYXERR(Debug::ACTION, "Event Type: " << event->type());
882 switch (event->type()) {
886 case QEvent::UpdateRequest:
887 case QEvent::CursorChange:
888 case QEvent::ActionChanged:
889 case QEvent::EnabledChange:
890 case QEvent::SockAct:
893 case QEvent::ToolTipChange:
894 case QEvent::LayoutRequest:
895 case QEvent::MetaCall:
896 return QObject::eventFilter(obj, event);
898 // FIXME Blocking all these events is a bad idea.
899 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
900 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
908 ////////////////////////////////////////////////////////////////////////
909 // GuiApplication::Private definition and implementation.
910 ////////////////////////////////////////////////////////////////////////
912 struct GuiApplication::Private
914 Private(): language_model_(0), meta_fake_bit(NoModifier),
917 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
918 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
919 /// WMF Mime handler for Windows clipboard.
920 wmf_mime_ = new QWindowsMimeMetafile;
923 initKeySequences(&theTopLevelKeymap());
926 void initKeySequences(KeyMap * kb)
928 keyseq = KeySequence(kb, kb);
929 cancel_meta_seq = KeySequence(kb, kb);
933 QSortFilterProxyModel * language_model_;
935 GuiClipboard clipboard_;
937 GuiSelection selection_;
939 FontLoader font_loader_;
941 ColorCache color_cache_;
943 QTranslator qt_trans_;
945 QHash<int, SocketNotifier *> socket_notifiers_;
949 /// The global instance
952 /// this timer is used for any regular events one wants to
953 /// perform. at present it is used to check if forked processes
955 QTimer general_timer_;
957 /// delayed FuncRequests
958 std::queue<FuncRequest> func_request_queue_;
963 KeySequence cancel_meta_seq;
965 KeyModifier meta_fake_bit;
967 /// The result of last dispatch action
968 DispatchResult dispatch_result_;
970 /// Multiple views container.
972 * Warning: This must not be a smart pointer as the destruction of the
973 * object is handled by Qt when the view is closed
974 * \sa Qt::WA_DeleteOnClose attribute.
976 QHash<int, GuiView *> views_;
978 /// Only used on mac.
979 QMenuBar * global_menubar_;
982 /// Linkback mime handler for MacOSX.
983 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
986 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
987 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
988 /// WMF Mime handler for Windows clipboard.
989 QWindowsMimeMetafile * wmf_mime_;
993 /// Allows to check whether ESC was pressed during a long operation
994 KeyChecker key_checker_;
998 GuiApplication * guiApp;
1000 GuiApplication::~GuiApplication()
1003 closeAllLinkBackLinks();
1009 GuiApplication::GuiApplication(int & argc, char ** argv)
1010 : QApplication(argc, argv), current_view_(0),
1011 d(new GuiApplication::Private)
1013 QString app_name = "LyX";
1014 QCoreApplication::setOrganizationName(app_name);
1015 QCoreApplication::setOrganizationDomain("lyx.org");
1016 QCoreApplication::setApplicationName(lyx_package);
1018 qsrand(QDateTime::currentDateTime().toTime_t());
1020 // Install translator for GUI elements.
1021 installTranslator(&d->qt_trans_);
1024 // Enable reception of XCB events.
1025 installNativeEventFilter(this);
1028 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1029 // lyxrc setting for this in order to let the application stay resident.
1030 // But then we need some kind of dock icon, at least on Windows.
1032 if (lyxrc.quit_on_last_window_closed)
1033 setQuitOnLastWindowClosed(false);
1036 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1037 // seems to be the default case for applications like LyX.
1038 setQuitOnLastWindowClosed(false);
1039 // This allows to translate the strings that appear in the LyX menu.
1040 /// A translator suitable for the entries in the LyX menu.
1041 /// Only needed with Qt/Mac.
1042 installTranslator(new MenuTranslator(this));
1047 #if defined(Q_WS_X11) || defined(QPA_XCB)
1048 // doubleClickInterval() is 400 ms on X11 which is just too long.
1049 // On Windows and Mac OS X, the operating system's value is used.
1050 // On Microsoft Windows, calling this function sets the double
1051 // click interval for all applications. So we don't!
1052 QApplication::setDoubleClickInterval(300);
1055 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1057 // needs to be done before reading lyxrc
1059 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1063 // Set the cache to 5120 kilobytes which corresponds to screen size of
1064 // 1280 by 1024 pixels with a color depth of 32 bits.
1065 QPixmapCache::setCacheLimit(5120);
1067 // Initialize RC Fonts
1068 if (lyxrc.roman_font_name.empty())
1069 lyxrc.roman_font_name = fromqstr(romanFontName());
1071 if (lyxrc.sans_font_name.empty())
1072 lyxrc.sans_font_name = fromqstr(sansFontName());
1074 if (lyxrc.typewriter_font_name.empty())
1075 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1077 d->general_timer_.setInterval(500);
1078 connect(&d->general_timer_, SIGNAL(timeout()),
1079 this, SLOT(handleRegularEvents()));
1080 d->general_timer_.start();
1082 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1083 // This is clearly not enough in a time where we use threads for
1084 // document preview and/or export. 20 should be OK.
1085 QThreadPool::globalInstance()->setMaxThreadCount(20);
1089 GuiApplication * theGuiApp()
1091 return dynamic_cast<GuiApplication *>(theApp());
1095 double GuiApplication::pixelRatio() const
1097 #if QT_VERSION >= 0x050000
1098 return devicePixelRatio();
1105 void GuiApplication::clearSession()
1112 docstring Application::iconName(FuncRequest const & f, bool unknown)
1114 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1118 docstring Application::mathIcon(docstring const & c)
1120 return qstring_to_ucs4(findImg(toqstr(c)));
1124 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1128 BufferView * bv = 0;
1129 BufferView * doc_bv = 0;
1131 if (cmd.action() == LFUN_NOACTION) {
1132 status.message(from_utf8(N_("Nothing to do")));
1133 status.setEnabled(false);
1136 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1137 status.setUnknown(true);
1138 status.message(from_utf8(N_("Unknown action")));
1139 status.setEnabled(false);
1142 // Does the GuiApplication know something?
1143 else if (getStatus(cmd, status)) { }
1145 // If we do not have a GuiView, then other functions are disabled
1146 else if (!current_view_)
1147 status.setEnabled(false);
1149 // Does the GuiView know something?
1150 else if (current_view_->getStatus(cmd, status)) { }
1152 // In LyX/Mac, when a dialog is open, the menus of the
1153 // application can still be accessed without giving focus to
1154 // the main window. In this case, we want to disable the menu
1155 // entries that are buffer or view-related.
1156 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1158 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1159 status.setEnabled(false);
1162 // If we do not have a BufferView, then other functions are disabled
1163 else if (!(bv = current_view_->currentBufferView()))
1164 status.setEnabled(false);
1166 // Does the current BufferView know something?
1167 else if (bv->getStatus(cmd, status)) { }
1169 // Does the current Buffer know something?
1170 else if (bv->buffer().getStatus(cmd, status)) { }
1172 // If we do not have a document BufferView, different from the
1173 // current BufferView, then other functions are disabled
1174 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1175 status.setEnabled(false);
1177 // Does the document Buffer know something?
1178 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1181 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1182 status.message(from_utf8(N_("Command not handled")));
1183 status.setEnabled(false);
1186 // the default error message if we disable the command
1187 if (!status.enabled() && status.message().empty())
1188 status.message(from_utf8(N_("Command disabled")));
1194 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1196 // I would really like to avoid having this switch and rather try to
1197 // encode this in the function itself.
1198 // -- And I'd rather let an inset decide which LFUNs it is willing
1199 // to handle (Andre')
1201 switch (cmd.action()) {
1203 // This could be used for the no-GUI version. The GUI version is handled in
1204 // GuiView::getStatus(). See above.
1206 case LFUN_BUFFER_WRITE:
1207 case LFUN_BUFFER_WRITE_AS: {
1208 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1209 enable = b && (b->isUnnamed() || !b->isClean());
1214 case LFUN_BOOKMARK_GOTO: {
1215 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1216 enable = theSession().bookmarks().isValid(num);
1220 case LFUN_BOOKMARK_CLEAR:
1221 enable = theSession().bookmarks().hasValid();
1224 // this one is difficult to get right. As a half-baked
1225 // solution, we consider only the first action of the sequence
1226 case LFUN_COMMAND_SEQUENCE: {
1227 // argument contains ';'-terminated commands
1228 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1229 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1230 func.setOrigin(cmd.origin());
1231 flag = getStatus(func);
1235 // we want to check if at least one of these is enabled
1236 case LFUN_COMMAND_ALTERNATIVES: {
1237 // argument contains ';'-terminated commands
1238 string arg = to_utf8(cmd.argument());
1239 while (!arg.empty()) {
1241 arg = split(arg, first, ';');
1242 FuncRequest func(lyxaction.lookupFunc(first));
1243 func.setOrigin(cmd.origin());
1244 flag = getStatus(func);
1245 // if this one is enabled, the whole thing is
1254 string name = to_utf8(cmd.argument());
1255 if (theTopLevelCmdDef().lock(name, func)) {
1256 func.setOrigin(cmd.origin());
1257 flag = getStatus(func);
1258 theTopLevelCmdDef().release(name);
1260 // catch recursion or unknown command
1261 // definition. all operations until the
1262 // recursion or unknown command definition
1263 // occurs are performed, so set the state to
1270 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1272 case LFUN_PREFERENCES_SAVE:
1273 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1274 case LFUN_DEBUG_LEVEL_SET:
1275 // these are handled in our dispatch()
1278 case LFUN_WINDOW_CLOSE:
1279 enable = d->views_.size() > 0;
1282 case LFUN_BUFFER_NEW:
1283 case LFUN_BUFFER_NEW_TEMPLATE:
1284 case LFUN_FILE_OPEN:
1285 case LFUN_HELP_OPEN:
1286 case LFUN_SCREEN_FONT_UPDATE:
1287 case LFUN_SET_COLOR:
1288 case LFUN_WINDOW_NEW:
1290 case LFUN_LYXRC_APPLY:
1291 case LFUN_COMMAND_PREFIX:
1293 case LFUN_META_PREFIX:
1294 case LFUN_RECONFIGURE:
1295 case LFUN_SERVER_GET_FILENAME:
1296 case LFUN_SERVER_NOTIFY:
1300 case LFUN_BUFFER_FORALL: {
1301 if (theBufferList().empty()) {
1302 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1303 flag.setEnabled(false);
1307 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1308 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1309 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1310 flag.setEnabled(false);
1315 case LFUN_DIALOG_SHOW: {
1316 string const name = cmd.getArg(0);
1317 return name == "aboutlyx"
1319 || name == "texinfo"
1320 || name == "progress"
1321 || name == "compare";
1329 flag.setEnabled(false);
1333 /// make a post-dispatch status message
1334 static docstring makeDispatchMessage(docstring const & msg,
1335 FuncRequest const & cmd)
1337 const bool verbose = (cmd.origin() == FuncRequest::MENU
1338 || cmd.origin() == FuncRequest::TOOLBAR
1339 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1341 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1342 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1346 docstring dispatch_msg = msg;
1347 if (!dispatch_msg.empty())
1348 dispatch_msg += ' ';
1350 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1352 bool argsadded = false;
1354 if (!cmd.argument().empty()) {
1355 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1356 comname += ' ' + cmd.argument();
1360 docstring const shortcuts = theTopLevelKeymap().
1361 printBindings(cmd, KeySequence::ForGui);
1363 if (!shortcuts.empty())
1364 comname += ": " + shortcuts;
1365 else if (!argsadded && !cmd.argument().empty())
1366 comname += ' ' + cmd.argument();
1368 if (!comname.empty()) {
1369 comname = rtrim(comname);
1370 dispatch_msg += '(' + rtrim(comname) + ')';
1372 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1373 return dispatch_msg;
1377 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1379 Buffer * buffer = 0;
1380 if (current_view_ && current_view_->currentBufferView()) {
1381 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1382 buffer = ¤t_view_->currentBufferView()->buffer();
1384 buffer->undo().beginUndoGroup();
1388 // redraw the screen at the end (first of the two drawing steps).
1389 // This is done unless explicitly requested otherwise
1390 dr.screenUpdate(Update::FitCursor);
1392 updateCurrentView(cmd, dr);
1394 // the buffer may have been closed by one action
1395 if (theBufferList().isLoaded(buffer))
1396 buffer->undo().endUndoGroup();
1398 d->dispatch_result_ = dr;
1399 return d->dispatch_result_;
1403 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1408 BufferView * bv = current_view_->currentBufferView();
1410 if (dr.needBufferUpdate()) {
1411 bv->cursor().clearBufferUpdate();
1412 bv->buffer().updateBuffer();
1413 } else if (dr.needChangesUpdate()) {
1414 // updateBuffer() already updates the change-tracking presence flag
1415 bv->buffer().updateChangesPresent();
1417 // BufferView::update() updates the ViewMetricsInfo and
1418 // also initializes the position cache for all insets in
1419 // (at least partially) visible top-level paragraphs.
1420 // We will redraw the screen only if needed.
1421 bv->processUpdateFlags(dr.screenUpdate());
1423 // Do we have a selection?
1424 theSelection().haveSelection(bv->cursor().selection());
1427 current_view_->restartCursor();
1429 if (dr.needMessageUpdate()) {
1430 // Some messages may already be translated, so we cannot use _()
1431 current_view_->message(makeDispatchMessage(
1432 translateIfPossible(dr.message()), cmd));
1437 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1438 bool switchToBuffer)
1440 if (!theSession().bookmarks().isValid(idx))
1442 BookmarksSection::Bookmark const & bm =
1443 theSession().bookmarks().bookmark(idx);
1444 LASSERT(!bm.filename.empty(), return);
1445 string const file = bm.filename.absFileName();
1446 // if the file is not opened, open it.
1447 if (!theBufferList().exists(bm.filename)) {
1449 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1453 // open may fail, so we need to test it again
1454 if (!theBufferList().exists(bm.filename))
1457 // bm can be changed when saving
1458 BookmarksSection::Bookmark tmp = bm;
1460 // Special case idx == 0 used for back-from-back jump navigation
1462 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1464 // if the current buffer is not that one, switch to it.
1465 BufferView * doc_bv = current_view_ ?
1466 current_view_->documentBufferView() : 0;
1467 Cursor const old = doc_bv->cursor();
1468 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1469 if (switchToBuffer) {
1470 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1473 doc_bv = current_view_->documentBufferView();
1478 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1479 if (!doc_bv->moveToPosition(
1480 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1483 Cursor & cur = doc_bv->cursor();
1485 notifyCursorLeavesOrEnters(old, cur);
1491 // Cursor jump succeeded!
1492 pit_type new_pit = cur.pit();
1493 pos_type new_pos = cur.pos();
1494 int new_id = cur.paragraph().id();
1496 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1497 // see http://www.lyx.org/trac/ticket/3092
1498 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1499 || bm.top_id != new_id) {
1500 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1501 new_pit, new_pos, new_id);
1505 // This function runs "configure" and then rereads lyx.defaults to
1506 // reconfigure the automatic settings.
1507 void GuiApplication::reconfigure(string const & option)
1509 // emit message signal.
1511 current_view_->message(_("Running configure..."));
1513 // Run configure in user lyx directory
1514 string const lock_file = package().getConfigureLockName();
1515 int fd = fileLock(lock_file.c_str());
1516 int const ret = package().reconfigureUserLyXDir(option);
1517 // emit message signal.
1519 current_view_->message(_("Reloading configuration..."));
1520 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1521 // Re-read packages.lst
1522 LaTeXPackages::getAvailable();
1523 fileUnlock(fd, lock_file.c_str());
1526 Alert::information(_("System reconfiguration failed"),
1527 _("The system reconfiguration has failed.\n"
1528 "Default textclass is used but LyX may\n"
1529 "not be able to work properly.\n"
1530 "Please reconfigure again if needed."));
1532 Alert::information(_("System reconfigured"),
1533 _("The system has been reconfigured.\n"
1534 "You need to restart LyX to make use of any\n"
1535 "updated document class specifications."));
1538 void GuiApplication::validateCurrentView()
1540 if (!d->views_.empty() && !current_view_) {
1541 // currently at least one view exists but no view has the focus.
1542 // choose the last view to make it current.
1543 // a view without any open document is preferred.
1544 GuiView * candidate = 0;
1545 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1546 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1547 for (; it != end; ++it) {
1549 if (!candidate->documentBufferView())
1552 setCurrentView(candidate);
1556 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1558 string const argument = to_utf8(cmd.argument());
1559 FuncCode const action = cmd.action();
1561 LYXERR(Debug::ACTION, "cmd: " << cmd);
1563 // we have not done anything wrong yet.
1566 FuncStatus const flag = getStatus(cmd);
1567 if (!flag.enabled()) {
1568 // We cannot use this function here
1569 LYXERR(Debug::ACTION, "action "
1570 << lyxaction.getActionName(action)
1571 << " [" << action << "] is disabled at this location");
1572 dr.setMessage(flag.message());
1574 dr.dispatched(false);
1575 dr.screenUpdate(Update::None);
1576 dr.clearBufferUpdate();
1580 if (cmd.origin() == FuncRequest::LYXSERVER) {
1581 if (current_view_ && current_view_->currentBufferView())
1582 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1583 // we will also need to redraw the screen at the end
1584 dr.screenUpdate(Update::FitCursor);
1587 // Assumes that the action will be dispatched.
1588 dr.dispatched(true);
1590 switch (cmd.action()) {
1592 case LFUN_WINDOW_NEW:
1593 createView(toqstr(cmd.argument()));
1596 case LFUN_WINDOW_CLOSE:
1597 // update bookmark pit of the current buffer before window close
1598 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1599 gotoBookmark(i+1, false, false);
1600 // clear the last opened list, because
1601 // maybe this will end the session
1602 theSession().lastOpened().clear();
1603 // check for valid current_view_
1604 validateCurrentView();
1606 current_view_->closeScheduled();
1610 // quitting is triggered by the gui code
1611 // (leaving the event loop).
1613 current_view_->message(from_utf8(N_("Exiting.")));
1614 if (closeAllViews())
1618 case LFUN_SCREEN_FONT_UPDATE: {
1619 // handle the screen font changes.
1620 d->font_loader_.update();
1621 // Backup current_view_
1622 GuiView * view = current_view_;
1623 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1624 // to skip the refresh.
1626 theBufferList().changed(false);
1627 // Restore current_view_
1628 current_view_ = view;
1632 case LFUN_BUFFER_NEW:
1633 validateCurrentView();
1634 if (d->views_.empty()
1635 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1636 createView(QString(), false); // keep hidden
1637 current_view_->newDocument(to_utf8(cmd.argument()), false);
1638 current_view_->show();
1639 setActiveWindow(current_view_);
1641 current_view_->newDocument(to_utf8(cmd.argument()), false);
1645 case LFUN_BUFFER_NEW_TEMPLATE:
1646 validateCurrentView();
1647 if (d->views_.empty()
1648 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1650 current_view_->newDocument(to_utf8(cmd.argument()), true);
1651 if (!current_view_->documentBufferView())
1652 current_view_->close();
1654 current_view_->newDocument(to_utf8(cmd.argument()), true);
1658 case LFUN_FILE_OPEN: {
1659 validateCurrentView();
1660 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1661 string const fname = to_utf8(cmd.argument());
1662 bool const is_open = FileName::isAbsolute(fname)
1663 && theBufferList().getBuffer(FileName(fname));
1664 if (d->views_.empty()
1665 || (!lyxrc.open_buffers_in_tabs
1666 && current_view_->documentBufferView() != 0
1668 // We want the ui session to be saved per document and not per
1669 // window number. The filename crc is a good enough identifier.
1670 boost::crc_32_type crc;
1671 crc = for_each(fname.begin(), fname.end(), crc);
1672 createView(crc.checksum());
1673 // we know current_view_ is non-null, because createView sets it.
1674 // coverity[FORWARD_NULL]
1675 current_view_->openDocument(fname);
1676 // FIXME but then why check current_view_ here?
1677 if (current_view_ && !current_view_->documentBufferView())
1678 current_view_->close();
1680 // we know !d->views.empty(), so this should be ok
1681 // coverity[FORWARD_NULL]
1682 current_view_->openDocument(fname);
1687 case LFUN_HELP_OPEN: {
1688 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1689 if (current_view_ == 0)
1691 string const arg = to_utf8(cmd.argument());
1693 current_view_->message(_("Missing argument"));
1696 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1698 fname = i18nLibFileSearch("examples", arg, "lyx");
1700 if (fname.empty()) {
1701 lyxerr << "LyX: unable to find documentation file `"
1702 << arg << "'. Bad installation?" << endl;
1705 current_view_->message(bformat(_("Opening help file %1$s..."),
1706 makeDisplayPath(fname.absFileName())));
1707 Buffer * buf = current_view_->loadDocument(fname, false);
1709 #ifndef DEVEL_VERSION
1711 buf->setReadonly(true);
1718 case LFUN_SET_COLOR: {
1720 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1721 if (lyx_name.empty() || x11_name.empty()) {
1723 current_view_->message(
1724 _("Syntax: set-color <lyx_name> <x11_name>"));
1729 // FIXME: The graphics cache no longer has a changeDisplay method.
1730 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1731 bool const graphicsbg_changed =
1732 lyx_name == graphicsbg && x11_name != graphicsbg;
1733 if (graphicsbg_changed)
1734 graphics::GCache::get().changeDisplay(true);
1737 if (!lcolor.setColor(lyx_name, x11_name)) {
1739 current_view_->message(
1740 bformat(_("Set-color \"%1$s\" failed "
1741 "- color is undefined or "
1742 "may not be redefined"),
1743 from_utf8(lyx_name)));
1746 // Make sure we don't keep old colors in cache.
1747 d->color_cache_.clear();
1748 // Update the current view
1749 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1753 case LFUN_LYXRC_APPLY: {
1754 // reset active key sequences, since the bindings
1755 // are updated (bug 6064)
1757 LyXRC const lyxrc_orig = lyxrc;
1759 istringstream ss(to_utf8(cmd.argument()));
1760 bool const success = lyxrc.read(ss);
1763 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1764 << "Unable to read lyxrc data"
1769 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1771 // If the request comes from the minibuffer, then we can't reset
1772 // the GUI, since that would destory the minibuffer itself and
1773 // cause a crash, since we are currently in one of the methods of
1774 // GuiCommandBuffer. See bug #8540.
1775 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1778 // FIXME Unfortunately, that leaves a bug here, since we cannot
1779 // reset the GUI in this case. If the changes to lyxrc affected the
1780 // UI, then, nothing would happen. This seems fairly unlikely, but
1781 // it definitely is a bug.
1786 case LFUN_COMMAND_PREFIX:
1787 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1792 d->meta_fake_bit = NoModifier;
1793 GuiView * gv = currentView();
1794 if (gv && gv->currentBufferView())
1795 // cancel any selection
1796 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1797 dr.setMessage(from_ascii(N_("Cancel")));
1800 case LFUN_META_PREFIX:
1801 d->meta_fake_bit = AltModifier;
1802 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1805 // --- Menus -----------------------------------------------
1806 case LFUN_RECONFIGURE:
1807 // argument is any additional parameter to the configure.py command
1808 reconfigure(to_utf8(cmd.argument()));
1811 // --- lyxserver commands ----------------------------
1812 case LFUN_SERVER_GET_FILENAME: {
1813 if (current_view_ && current_view_->documentBufferView()) {
1814 docstring const fname = from_utf8(
1815 current_view_->documentBufferView()->buffer().absFileName());
1816 dr.setMessage(fname);
1817 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1819 dr.setMessage(docstring());
1820 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1825 case LFUN_SERVER_NOTIFY: {
1826 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1827 dr.setMessage(dispatch_buffer);
1828 theServer().notifyClient(to_utf8(dispatch_buffer));
1832 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1833 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1839 string rest = split(argument, countstr, ' ');
1840 istringstream is(countstr);
1843 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1844 for (int i = 0; i < count; ++i)
1845 dispatch(lyxaction.lookupFunc(rest));
1849 case LFUN_COMMAND_SEQUENCE: {
1850 // argument contains ';'-terminated commands
1851 string arg = argument;
1852 // FIXME: this LFUN should also work without any view.
1853 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1854 ? &(current_view_->documentBufferView()->buffer()) : 0;
1856 buffer->undo().beginUndoGroup();
1857 while (!arg.empty()) {
1859 arg = split(arg, first, ';');
1860 FuncRequest func(lyxaction.lookupFunc(first));
1861 func.setOrigin(cmd.origin());
1864 // the buffer may have been closed by one action
1865 if (theBufferList().isLoaded(buffer))
1866 buffer->undo().endUndoGroup();
1870 case LFUN_BUFFER_FORALL: {
1871 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1873 map<Buffer *, GuiView *> views_lVisible;
1874 map<GuiView *, Buffer *> activeBuffers;
1876 QList<GuiView *> allViews = d->views_.values();
1878 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1879 // and on which buffer is active in each view.
1880 Buffer * const last = theBufferList().last();
1881 foreach (GuiView * view, allViews) {
1882 // all of the buffers might be locally hidden. That is, there is no active buffer.
1883 if (!view || !view->currentBufferView())
1884 activeBuffers[view] = 0;
1886 activeBuffers[view] = &view->currentBufferView()->buffer();
1888 // find out if each is locally visible or locally hidden.
1889 // we don't use a for loop as the buffer list cycles.
1890 Buffer * b = theBufferList().first();
1892 bool const locallyVisible = view && view->workArea(*b);
1893 if (locallyVisible) {
1894 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1895 // only need to overwrite/add if we don't already know a buffer is globally
1896 // visible or we do know but we would prefer to dispatch LFUN from the
1897 // current view because of cursor position issues.
1898 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1899 views_lVisible[b] = view;
1903 b = theBufferList().next(b);
1907 GuiView * const homeView = currentView();
1908 Buffer * b = theBufferList().first();
1909 Buffer * nextBuf = 0;
1910 int numProcessed = 0;
1913 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1915 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1917 // first change to a view where b is locally visible, preferably current_view_.
1918 GuiView * const vLv = views_lVisible[b];
1920 lyx::dispatch(funcToRun);
1928 // put things back to how they were (if possible).
1929 foreach (GuiView * view, allViews) {
1930 Buffer * originalBuf = activeBuffers[view];
1931 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1932 if (theBufferList().isLoaded(originalBuf))
1933 view->setBuffer(originalBuf);
1935 homeView->setFocus();
1937 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1941 case LFUN_COMMAND_ALTERNATIVES: {
1942 // argument contains ';'-terminated commands
1943 string arg = argument;
1944 while (!arg.empty()) {
1946 arg = split(arg, first, ';');
1947 FuncRequest func(lyxaction.lookupFunc(first));
1948 func.setOrigin(cmd.origin());
1949 FuncStatus const stat = getStatus(func);
1950 if (stat.enabled()) {
1960 if (theTopLevelCmdDef().lock(argument, func)) {
1961 func.setOrigin(cmd.origin());
1963 theTopLevelCmdDef().release(argument);
1965 if (func.action() == LFUN_UNKNOWN_ACTION) {
1966 // unknown command definition
1967 lyxerr << "Warning: unknown command definition `"
1971 // recursion detected
1972 lyxerr << "Warning: Recursion in the command definition `"
1973 << argument << "' detected"
1980 case LFUN_PREFERENCES_SAVE:
1981 lyxrc.write(support::makeAbsPath("preferences",
1982 package().user_support().absFileName()), false);
1985 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1986 string const fname = addName(addPath(package().user_support().absFileName(),
1987 "templates/"), "defaults.lyx");
1988 Buffer defaults(fname);
1990 istringstream ss(argument);
1995 // We need to make sure that, after we recreat the DocumentClass,
1996 // which we do in readHeader, we apply it to the document itself.
1997 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1998 int const unknown_tokens = defaults.readHeader(lex);
1999 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2001 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2002 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2004 if (unknown_tokens != 0) {
2005 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2006 << unknown_tokens << " unknown token"
2007 << (unknown_tokens == 1 ? "" : "s")
2011 if (defaults.writeFile(FileName(defaults.absFileName())))
2012 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2013 makeDisplayPath(fname)));
2016 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2021 case LFUN_BOOKMARK_GOTO:
2022 // go to bookmark, open unopened file and switch to buffer if necessary
2023 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2024 dr.screenUpdate(Update::Force | Update::FitCursor);
2027 case LFUN_BOOKMARK_CLEAR:
2028 theSession().bookmarks().clear();
2031 case LFUN_DEBUG_LEVEL_SET:
2032 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2035 case LFUN_DIALOG_SHOW: {
2036 string const name = cmd.getArg(0);
2038 if ( name == "aboutlyx"
2040 || name == "texinfo"
2041 || name == "progress"
2042 || name == "compare")
2044 // work around: on Mac OS the application
2045 // is not terminated when closing the last view.
2046 // Create a new one to be able to dispatch the
2047 // LFUN_DIALOG_SHOW to this view.
2048 if (current_view_ == 0)
2055 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2058 current_view_->dispatch(cmd, dr);
2062 if (cmd.origin() == FuncRequest::LYXSERVER)
2063 updateCurrentView(cmd, dr);
2067 docstring GuiApplication::viewStatusMessage()
2069 // When meta-fake key is pressed, show the key sequence so far + "M-".
2070 if (d->meta_fake_bit != NoModifier)
2071 return d->keyseq.print(KeySequence::ForGui) + "M-";
2073 // Else, when a non-complete key sequence is pressed,
2074 // show the available options.
2075 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2076 return d->keyseq.printOptions(true);
2082 void GuiApplication::handleKeyFunc(FuncCode action)
2086 if (d->keyseq.length())
2088 GuiView * gv = currentView();
2089 LASSERT(gv && gv->currentBufferView(), return);
2090 BufferView * bv = gv->currentBufferView();
2091 bv->getIntl().getTransManager().deadkey(
2092 c, get_accent(action).accent, bv->cursor().innerText(),
2094 // Need to clear, in case the minibuffer calls these
2097 // copied verbatim from do_accent_char
2098 bv->cursor().resetAnchor();
2102 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2104 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2106 // Do nothing if we have nothing (JMarc)
2107 if (!keysym.isOK()) {
2108 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2110 current_view_->restartCursor();
2114 if (keysym.isModifier()) {
2116 current_view_->restartCursor();
2120 char_type encoded_last_key = keysym.getUCSEncoded();
2122 // Do a one-deep top-level lookup for
2123 // cancel and meta-fake keys. RVDK_PATCH_5
2124 d->cancel_meta_seq.reset();
2126 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2127 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2129 // When not cancel or meta-fake, do the normal lookup.
2130 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2131 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2132 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2133 // remove Caps Lock and Mod2 as a modifiers
2134 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2135 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2138 // Dont remove this unless you know what you are doing.
2139 d->meta_fake_bit = NoModifier;
2141 // Can this happen now ?
2142 if (func.action() == LFUN_NOACTION)
2143 func = FuncRequest(LFUN_COMMAND_PREFIX);
2145 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2146 << d->keyseq.print(KeySequence::Portable) << ']');
2148 // already here we know if it any point in going further
2149 // why not return already here if action == -1 and
2150 // num_bytes == 0? (Lgb)
2152 if (d->keyseq.length() > 1 && current_view_)
2153 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2156 // Maybe user can only reach the key via holding down shift.
2157 // Let's see. But only if shift is the only modifier
2158 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2159 LYXERR(Debug::KEY, "Trying without shift");
2160 func = d->keyseq.addkey(keysym, NoModifier);
2161 LYXERR(Debug::KEY, "Action now " << func.action());
2164 if (func.action() == LFUN_UNKNOWN_ACTION) {
2165 // We didn't match any of the key sequences.
2166 // See if it's normal insertable text not already
2167 // covered by a binding
2168 if (keysym.isText() && d->keyseq.length() == 1) {
2169 // Non-printable characters (such as ASCII control characters)
2170 // must not be inserted (#5704)
2171 if (!isPrintable(encoded_last_key)) {
2172 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2174 current_view_->restartCursor();
2177 // The following modifier check is not needed on Mac.
2178 // The keysym is either not text or it is different
2179 // from the non-modifier keysym. See #9875 for the
2180 // broken alt-modifier effect of having this code active.
2181 #if !defined(Q_OS_MAC)
2182 // If a non-Shift Modifier is used we have a non-bound key sequence
2183 // (such as Alt+j = j). This should be omitted (#5575).
2184 // On Windows, AltModifier and ControlModifier are both
2185 // set when AltGr is pressed. Therefore, in order to not
2186 // break AltGr-bound symbols (see #5575 for details),
2187 // unbound Ctrl+Alt key sequences are allowed.
2188 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2189 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2190 && !(state & AltModifier && state & ControlModifier)
2194 if (current_view_) {
2195 current_view_->message(_("Unknown function."));
2196 current_view_->restartCursor();
2201 // Since all checks above were passed, we now really have text that
2202 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2203 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2205 LYXERR(Debug::KEY, "isText() is true, inserting.");
2206 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2208 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2209 if (current_view_) {
2210 current_view_->message(_("Unknown function."));
2211 current_view_->restartCursor();
2217 if (func.action() == LFUN_SELF_INSERT) {
2218 if (encoded_last_key != 0) {
2219 docstring const arg(1, encoded_last_key);
2220 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2221 FuncRequest::KEYBOARD));
2222 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2225 processFuncRequest(func);
2229 void GuiApplication::processFuncRequest(FuncRequest const & func)
2231 lyx::dispatch(func);
2235 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2237 addToFuncRequestQueue(func);
2238 processFuncRequestQueueAsync();
2242 void GuiApplication::processFuncRequestQueue()
2244 while (!d->func_request_queue_.empty()) {
2245 processFuncRequest(d->func_request_queue_.front());
2246 d->func_request_queue_.pop();
2251 void GuiApplication::processFuncRequestQueueAsync()
2253 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2257 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2259 d->func_request_queue_.push(func);
2263 void GuiApplication::resetGui()
2265 // Set the language defined by the user.
2269 if (!readUIFile(toqstr(lyxrc.ui_file)))
2270 // Gives some error box here.
2273 if (d->global_menubar_)
2274 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2276 QHash<int, GuiView *>::iterator it;
2277 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2280 gv->setLayoutDirection(layoutDirection());
2284 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2288 void GuiApplication::createView(int view_id)
2290 createView(QString(), true, view_id);
2294 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2297 // release the keyboard which might have been grabed by the global
2298 // menubar on Mac to catch shortcuts even without any GuiView.
2299 if (d->global_menubar_)
2300 d->global_menubar_->releaseKeyboard();
2304 while (d->views_.find(id) != d->views_.end())
2307 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2308 GuiView * view = new GuiView(id);
2310 d->views_[id] = view;
2314 setActiveWindow(view);
2317 if (!geometry_arg.isEmpty()) {
2318 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2322 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2323 re.indexIn(geometry_arg);
2324 w = re.cap(1).toInt();
2325 h = re.cap(2).toInt();
2326 x = re.cap(3).toInt();
2327 y = re.cap(4).toInt();
2328 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2329 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2330 // Set initial geometry such that we can get the frame size.
2331 view->setGeometry(x, y, w, h);
2332 int framewidth = view->geometry().x() - view->x();
2333 int titleheight = view->geometry().y() - view->y();
2334 // Negative displacements must be interpreted as distances
2335 // from the right or bottom screen borders.
2336 if (sx == '-' || sy == '-') {
2337 QRect rec = QApplication::desktop()->screenGeometry();
2339 x += rec.width() - w - framewidth;
2341 y += rec.height() - h - titleheight;
2342 view->setGeometry(x, y, w, h);
2344 // Make sure that the left and top frame borders are visible.
2345 if (view->x() < 0 || view->y() < 0) {
2350 view->setGeometry(x, y, w, h);
2358 Clipboard & GuiApplication::clipboard()
2360 return d->clipboard_;
2364 Selection & GuiApplication::selection()
2366 return d->selection_;
2370 FontLoader & GuiApplication::fontLoader()
2372 return d->font_loader_;
2376 Toolbars const & GuiApplication::toolbars() const
2378 return d->toolbars_;
2382 Toolbars & GuiApplication::toolbars()
2384 return d->toolbars_;
2388 Menus const & GuiApplication::menus() const
2394 Menus & GuiApplication::menus()
2400 QList<int> GuiApplication::viewIds() const
2402 return d->views_.keys();
2406 ColorCache & GuiApplication::colorCache()
2408 return d->color_cache_;
2412 int GuiApplication::exec()
2414 // asynchronously handle batch commands. This event will be in
2415 // the event queue in front of other asynchronous events. Hence,
2416 // we can assume in the latter that the gui is setup already.
2417 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2419 return QApplication::exec();
2423 void GuiApplication::exit(int status)
2425 QApplication::exit(status);
2429 void GuiApplication::setGuiLanguage()
2433 // install translation file for Qt built-in dialogs
2434 QString const language_name = QString("qt_") + theLocale.name();
2435 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2436 // Short-named translator can be loaded from a long name, but not the
2437 // opposite. Therefore, long name should be used without truncation.
2438 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2439 if (!d->qt_trans_.load(language_name,
2440 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2441 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2444 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2448 switch (theLocale.language()) {
2449 case QLocale::Arabic :
2450 case QLocale::Hebrew :
2451 case QLocale::Persian :
2452 case QLocale::Urdu :
2453 setLayoutDirection(Qt::RightToLeft);
2456 setLayoutDirection(Qt::LeftToRight);
2461 void GuiApplication::execBatchCommands()
2466 if (!readUIFile(toqstr(lyxrc.ui_file)))
2467 // Gives some error box here.
2471 #if QT_VERSION > 0x040600
2472 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2474 #if QT_VERSION > 0x050100
2475 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2477 // Create the global default menubar which is shown for the dialogs
2478 // and if no GuiView is visible.
2479 // This must be done after the session was recovered to know the "last files".
2480 d->global_menubar_ = new QMenuBar(0);
2481 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2484 lyx::execBatchCommands();
2488 QAbstractItemModel * GuiApplication::languageModel()
2490 if (d->language_model_)
2491 return d->language_model_;
2493 QStandardItemModel * lang_model = new QStandardItemModel(this);
2494 lang_model->insertColumns(0, 3);
2495 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2496 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2497 Languages::const_iterator it = lyx::languages.begin();
2498 Languages::const_iterator end = lyx::languages.end();
2499 for (; it != end; ++it) {
2500 int current_row = lang_model->rowCount();
2501 lang_model->insertRows(current_row, 1);
2502 QModelIndex pl_item = lang_model->index(current_row, 0);
2503 QModelIndex sp_item = lang_model->index(current_row, 1);
2504 QModelIndex th_item = lang_model->index(current_row, 2);
2505 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2506 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2507 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2508 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2509 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2510 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2511 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2512 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2513 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2514 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2516 d->language_model_ = new QSortFilterProxyModel(this);
2517 d->language_model_->setSourceModel(lang_model);
2518 d->language_model_->setSortLocaleAware(true);
2519 return d->language_model_;
2523 void GuiApplication::restoreGuiSession()
2525 if (!lyxrc.load_session)
2528 Session & session = theSession();
2529 LastOpenedSection::LastOpened const & lastopened =
2530 session.lastOpened().getfiles();
2532 validateCurrentView();
2534 FileName active_file;
2535 // do not add to the lastfile list since these files are restored from
2536 // last session, and should be already there (regular files), or should
2537 // not be added at all (help files).
2538 for (size_t i = 0; i < lastopened.size(); ++i) {
2539 FileName const & file_name = lastopened[i].file_name;
2540 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2541 && current_view_->documentBufferView() != 0)) {
2542 boost::crc_32_type crc;
2543 string const & fname = file_name.absFileName();
2544 crc = for_each(fname.begin(), fname.end(), crc);
2545 createView(crc.checksum());
2547 current_view_->loadDocument(file_name, false);
2549 if (lastopened[i].active)
2550 active_file = file_name;
2553 // Restore last active buffer
2554 Buffer * buffer = theBufferList().getBuffer(active_file);
2555 if (buffer && current_view_)
2556 current_view_->setBuffer(buffer);
2558 // clear this list to save a few bytes of RAM
2559 session.lastOpened().clear();
2563 QString const GuiApplication::romanFontName()
2566 font.setStyleHint(QFont::Serif);
2567 font.setFamily("serif");
2569 return QFontInfo(font).family();
2573 QString const GuiApplication::sansFontName()
2576 font.setStyleHint(QFont::SansSerif);
2577 font.setFamily("sans");
2579 return QFontInfo(font).family();
2583 QString const GuiApplication::typewriterFontName()
2585 return QFontInfo(typewriterSystemFont()).family();
2590 // We cannot use QFont::fixedPitch() because it doesn't
2591 // return the fact but only if it is requested.
2592 static bool isFixedPitch(const QFont & font) {
2593 const QFontInfo fi(font);
2594 return fi.fixedPitch();
2599 QFont const GuiApplication::typewriterSystemFont()
2601 #if QT_VERSION >= 0x050200
2602 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2604 QFont font("monospace");
2606 if (!isFixedPitch(font)) {
2607 // try to enforce a real monospaced font
2608 font.setStyleHint(QFont::Monospace);
2609 if (!isFixedPitch(font)) {
2610 font.setStyleHint(QFont::TypeWriter);
2611 if (!isFixedPitch(font)) font.setFamily("courier");
2615 // On a Mac the result is too small and it's not practical to
2616 // rely on Qtconfig utility to change the system settings of Qt.
2617 font.setPointSize(12);
2623 void GuiApplication::handleRegularEvents()
2625 ForkedCallsController::handleCompletedProcesses();
2629 bool GuiApplication::event(QEvent * e)
2632 case QEvent::FileOpen: {
2633 // Open a file; this happens only on Mac OS X for now.
2635 // We do this asynchronously because on startup the batch
2636 // commands are not executed here yet and the gui is not ready
2638 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2639 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2640 processFuncRequestAsync(fr);
2645 return QApplication::event(e);
2650 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2653 return QApplication::notify(receiver, event);
2655 catch (ExceptionMessage const & e) {
2657 case ErrorException:
2659 setQuitOnLastWindowClosed(false);
2661 Alert::error(e.title_, e.details_);
2663 // Properly crash in debug mode in order to get a useful backtrace.
2666 // In release mode, try to exit gracefully.
2669 case BufferException: {
2670 if (!current_view_ || !current_view_->documentBufferView())
2672 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2673 docstring details = e.details_ + '\n';
2674 details += buf->emergencyWrite();
2675 theBufferList().release(buf);
2676 details += "\n" + _("The current document was closed.");
2677 Alert::error(e.title_, details);
2680 case WarningException:
2681 Alert::warning(e.title_, e.details_);
2685 catch (exception const & e) {
2686 docstring s = _("LyX has caught an exception, it will now "
2687 "attempt to save all unsaved documents and exit."
2689 s += from_ascii(e.what());
2690 Alert::error(_("Software exception Detected"), s);
2694 docstring s = _("LyX has caught some really weird exception, it will "
2695 "now attempt to save all unsaved documents and exit.");
2696 Alert::error(_("Software exception Detected"), s);
2704 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2706 QColor const & qcol = d->color_cache_.get(col);
2707 if (!qcol.isValid()) {
2713 rgbcol.r = qcol.red();
2714 rgbcol.g = qcol.green();
2715 rgbcol.b = qcol.blue();
2720 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2722 QColor const qcol(lcolor.getX11Name(col).c_str());
2723 if (!qcol.isValid()) {
2729 rgbcol.r = qcol.red();
2730 rgbcol.g = qcol.green();
2731 rgbcol.b = qcol.blue();
2736 string const GuiApplication::hexName(ColorCode col)
2738 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2742 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2744 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2745 d->socket_notifiers_[fd] = sn;
2746 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2750 void GuiApplication::socketDataReceived(int fd)
2752 d->socket_notifiers_[fd]->func_();
2756 void GuiApplication::unregisterSocketCallback(int fd)
2758 d->socket_notifiers_.take(fd)->setEnabled(false);
2762 void GuiApplication::commitData(QSessionManager & sm)
2764 /** The implementation is required to avoid an application exit
2765 ** when session state save is triggered by session manager.
2766 ** The default implementation sends a close event to all
2767 ** visible top level widgets when session managment allows
2769 ** We are changing that to check the state of each buffer in all
2770 ** views and ask the users what to do if buffers are dirty.
2771 ** Furthermore, we save the session state.
2772 ** We do NOT close the views here since the user still can cancel
2773 ** the logout process (see #9277); also, this would hide LyX from
2774 ** an OSes own session handling (application restoration).
2776 #ifdef QT_NO_SESSIONMANAGER
2778 #warning Qt is compiled without session manager
2780 #pragma message("warning: Qt is compiled without session manager")
2784 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2792 void GuiApplication::unregisterView(GuiView * gv)
2794 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2795 d->views_.remove(gv->id());
2796 if (current_view_ == gv)
2802 bool GuiApplication::closeAllViews()
2804 if (d->views_.empty())
2807 // When a view/window was closed before without quitting LyX, there
2808 // are already entries in the lastOpened list.
2809 theSession().lastOpened().clear();
2811 QList<GuiView *> const views = d->views_.values();
2812 foreach (GuiView * view, views) {
2813 if (!view->closeScheduled())
2822 bool GuiApplication::prepareAllViewsForLogout()
2824 if (d->views_.empty())
2827 QList<GuiView *> const views = d->views_.values();
2828 foreach (GuiView * view, views) {
2829 if (!view->prepareAllBuffersForLogout())
2837 GuiView & GuiApplication::view(int id) const
2839 LAPPERR(d->views_.contains(id));
2840 return *d->views_.value(id);
2844 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2846 QList<GuiView *> const views = d->views_.values();
2847 foreach (GuiView * view, views)
2848 view->hideDialog(name, inset);
2852 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2854 Buffer const * buffer_ = 0;
2855 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2856 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2857 if (Buffer const * ptr = (*it)->updateInset(inset))
2864 bool GuiApplication::searchMenu(FuncRequest const & func,
2865 docstring_list & names) const
2867 return d->menus_.searchMenu(func, names);
2871 // Ensure that a file is read only once (prevents include loops)
2872 static QStringList uifiles;
2873 // store which ui files define Toolbars
2874 static QStringList toolbar_uifiles;
2877 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2888 LexerKeyword uitags[] = {
2889 { "format", ui_format },
2890 { "include", ui_include },
2891 { "menuset", ui_menuset },
2892 { "toolbars", ui_toolbars },
2893 { "toolbarset", ui_toolbarset }
2897 lex.setFile(ui_path);
2899 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2903 if (lyxerr.debugging(Debug::PARSER))
2904 lex.printTable(lyxerr);
2907 // format before introduction of format tag
2908 unsigned int format = 0;
2909 while (lex.isOK()) {
2910 int const status = lex.lex();
2912 // we have to do this check here, outside the switch,
2913 // because otherwise we would start reading include files,
2914 // e.g., if the first tag we hit was an include tag.
2915 if (status == ui_format)
2917 format = lex.getInteger();
2921 // this will trigger unless the first tag we hit is a format
2922 // tag, with the right format.
2923 if (format != LFUN_FORMAT)
2924 return FormatMismatch;
2927 case Lexer::LEX_FEOF:
2932 QString const file = toqstr(lex.getString());
2933 bool const success = readUIFile(file, true);
2935 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2942 d->menus_.read(lex);
2946 d->toolbars_.readToolbars(lex);
2950 d->toolbars_.readToolbarSettings(lex);
2951 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2955 if (!rtrim(lex.getString()).empty())
2956 lex.printError("LyX::ReadUIFile: "
2957 "Unknown menu tag: `$$Token'");
2959 LYXERR0("Error with status: " << status);
2965 return (error ? ReadError : ReadOK);
2969 bool GuiApplication::readUIFile(QString const & name, bool include)
2971 LYXERR(Debug::INIT, "About to read " << name << "...");
2975 ui_path = libFileSearch("ui", name, "inc");
2976 if (ui_path.empty())
2977 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2979 ui_path = libFileSearch("ui", name, "ui");
2982 if (ui_path.empty()) {
2983 static const QString defaultUIFile = "default";
2984 LYXERR(Debug::INIT, "Could not find " << name);
2986 Alert::warning(_("Could not find UI definition file"),
2987 bformat(_("Error while reading the included file\n%1$s\n"
2988 "Please check your installation."), qstring_to_ucs4(name)));
2991 if (name == defaultUIFile) {
2992 LYXERR(Debug::INIT, "Could not find default UI file!!");
2993 Alert::warning(_("Could not find default UI file"),
2994 _("LyX could not find the default UI file!\n"
2995 "Please check your installation."));
2998 Alert::warning(_("Could not find UI definition file"),
2999 bformat(_("Error while reading the configuration file\n%1$s\n"
3000 "Falling back to default.\n"
3001 "Please look under Tools>Preferences>User Interface and\n"
3002 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3003 return readUIFile(defaultUIFile, false);
3006 QString const uifile = toqstr(ui_path.absFileName());
3007 if (uifiles.contains(uifile)) {
3009 // We are reading again the top uifile so reset the safeguard:
3012 d->toolbars_.reset();
3014 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3015 << "Is this an include loop?");
3019 uifiles.push_back(uifile);
3021 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3023 ReturnValues retval = readUIFile(ui_path);
3025 if (retval == FormatMismatch) {
3026 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3027 TempFile tmp("convertXXXXXX.ui");
3028 FileName const tempfile = tmp.name();
3029 bool const success = prefs2prefs(ui_path, tempfile, true);
3031 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3032 " to format " << LFUN_FORMAT << ".");
3034 retval = readUIFile(tempfile);
3038 if (retval != ReadOK) {
3039 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3047 settings.beginGroup("ui_files");
3048 bool touched = false;
3049 for (int i = 0; i != uifiles.size(); ++i) {
3050 QFileInfo fi(uifiles[i]);
3051 QDateTime const date_value = fi.lastModified();
3052 QString const name_key = QString::number(i);
3053 // if an ui file which defines Toolbars has changed,
3054 // we have to reset the settings
3055 if (toolbar_uifiles.contains(uifiles[i])
3056 && (!settings.contains(name_key)
3057 || settings.value(name_key).toString() != uifiles[i]
3058 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3060 settings.setValue(name_key, uifiles[i]);
3061 settings.setValue(name_key + "/date", date_value);
3064 settings.endGroup();
3066 settings.remove("views");
3072 void GuiApplication::onLastWindowClosed()
3074 if (d->global_menubar_)
3075 d->global_menubar_->grabKeyboard();
3079 void GuiApplication::startLongOperation() {
3080 d->key_checker_.start();
3084 bool GuiApplication::longOperationCancelled() {
3085 return d->key_checker_.pressed();
3089 void GuiApplication::stopLongOperation() {
3090 d->key_checker_.stop();
3094 bool GuiApplication::longOperationStarted() {
3095 return d->key_checker_.started();
3099 ////////////////////////////////////////////////////////////////////////
3101 // X11 specific stuff goes here...
3104 bool GuiApplication::x11EventFilter(XEvent * xev)
3109 switch (xev->type) {
3110 case SelectionRequest: {
3111 if (xev->xselectionrequest.selection != XA_PRIMARY)
3113 LYXERR(Debug::SELECTION, "X requested selection.");
3114 BufferView * bv = current_view_->currentBufferView();
3116 docstring const sel = bv->requestSelection();
3118 d->selection_.put(sel);
3122 case SelectionClear: {
3123 if (xev->xselectionclear.selection != XA_PRIMARY)
3125 LYXERR(Debug::SELECTION, "Lost selection.");
3126 BufferView * bv = current_view_->currentBufferView();
3128 bv->clearSelection();
3134 #elif defined(QPA_XCB)
3135 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3136 void * message, long *)
3138 if (!current_view_ || eventType != "xcb_generic_event_t")
3141 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3143 switch (ev->response_type) {
3144 case XCB_SELECTION_REQUEST: {
3145 xcb_selection_request_event_t * srev =
3146 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3147 if (srev->selection != XCB_ATOM_PRIMARY)
3149 LYXERR(Debug::SELECTION, "X requested selection.");
3150 BufferView * bv = current_view_->currentBufferView();
3152 docstring const sel = bv->requestSelection();
3154 d->selection_.put(sel);
3158 case XCB_SELECTION_CLEAR: {
3159 xcb_selection_clear_event_t * scev =
3160 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3161 if (scev->selection != XCB_ATOM_PRIMARY)
3163 LYXERR(Debug::SELECTION, "Lost selection.");
3164 BufferView * bv = current_view_->currentBufferView();
3166 bv->clearSelection();
3174 } // namespace frontend
3177 void hideDialogs(std::string const & name, Inset * inset)
3180 frontend::guiApp->hideDialogs(name, inset);
3184 ////////////////////////////////////////////////////////////////////
3188 ////////////////////////////////////////////////////////////////////
3190 frontend::FontLoader & theFontLoader()
3192 LAPPERR(frontend::guiApp);
3193 return frontend::guiApp->fontLoader();
3197 frontend::FontMetrics const & theFontMetrics(Font const & f)
3199 return theFontMetrics(f.fontInfo());
3203 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3205 LAPPERR(frontend::guiApp);
3206 return frontend::guiApp->fontLoader().metrics(f);
3210 ////////////////////////////////////////////////////////////////////
3214 ////////////////////////////////////////////////////////////////////
3216 frontend::Clipboard & theClipboard()
3218 LAPPERR(frontend::guiApp);
3219 return frontend::guiApp->clipboard();
3223 frontend::Selection & theSelection()
3225 LAPPERR(frontend::guiApp);
3226 return frontend::guiApp->selection();
3232 #include "moc_GuiApplication.cpp"