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/Messages.h"
73 #include "support/os.h"
74 #include "support/Package.h"
75 #include "support/TempFile.h"
78 #include "support/AppleScript.h"
79 #include "support/linkback/LinkBackProxy.h"
87 #include <QDesktopWidget>
91 #include <QFileOpenEvent>
95 #include <QImageReader>
98 #include <QLibraryInfo>
104 #include <QPixmapCache>
106 #include <QSessionManager>
108 #include <QShowEvent>
109 #include <QSocketNotifier>
110 #include <QSortFilterProxyModel>
111 #include <QStandardItemModel>
112 #include <QTextCodec>
114 #include <QTranslator>
115 #include <QThreadPool>
119 #include <X11/Xatom.h>
120 #include <X11/Xlib.h>
123 #elif defined(QPA_XCB)
125 #include <X11/Xatom.h>
126 #include <X11/Intrinsic.h>
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 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
233 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
235 string ext = ascii_lowercase((const char *) *it);
246 ////////////////////////////////////////////////////////////////////////
248 // Icon loading support code
250 ////////////////////////////////////////////////////////////////////////
260 bool operator<(PngMap const & lhs, PngMap const & rhs)
262 return lhs.key < rhs.key;
268 CompareKey(QString const & name) : name_(name) {}
269 bool operator()(PngMap const & other) const { return other.key == name_; }
275 // this must be sorted alphabetically
276 // Upper case comes before lower case
277 // Please don't change the formatting, this list is parsed by
278 // development/tools/generate_symbols_images.py.
279 PngMap sorted_png_map[] = {
280 { "Arrownot", "arrownot2"},
281 { "Arrowvert", "arrowvert2"},
282 { "Bowtie", "bowtie2" },
284 { "Bumpeq", "bumpeq2" },
285 { "CIRCLE", "circle3" },
287 { "CheckedBox", "checkedbox2" },
288 { "Circle", "circle2" },
289 { "Colonapprox", "colonapprox2" },
290 { "Coloneq", "coloneq2" },
291 { "Coloneqq", "coloneqq2" },
292 { "Colonsim", "colonsim2" },
294 { "DOWNarrow", "downarrow3" },
295 { "Delta", "delta2" },
296 { "Diamond", "diamond2" },
297 { "Doteq", "doteq2" },
298 { "Downarrow", "downarrow2" },
299 { "Eqcolon", "eqcolon2" },
300 { "Eqqcolon", "eqqcolon2" },
301 { "Gamma", "gamma2" },
303 { "LEFTCIRCLE", "leftcircle3" },
304 { "LEFTarrow", "leftarrow3" },
305 { "LEFTcircle", "leftcircle4" },
307 { "Lambda", "lambda2" },
309 { "Leftarrow", "leftarrow2" },
310 { "Leftcircle", "leftcircle2" },
311 { "Leftrightarrow", "leftrightarrow2" },
312 { "Longarrownot", "longarrownot2"},
313 { "Longleftarrow", "longleftarrow2" },
314 { "Longleftrightarrow", "longleftrightarrow2" },
315 { "Longmapsfrom", "longmapsfrom2"},
316 { "Longmapsto", "longmapsto2"},
317 { "Longrightarrow", "longrightarrow2" },
318 { "Mapsfrom", "mapsfrom2"},
319 { "Mapsfromchar", "mapsfromchar2"},
320 { "Mapsto", "mapsto2"},
321 { "Mapstochar", "mapstochar2"},
322 { "Omega", "omega2" },
327 { "RIGHTCIRCLE", "rightcircle3" },
328 { "RIGHTarrow", "rightarrow3" },
329 { "RIGHTcircle", "rightcircle4" },
331 { "Rightarrow", "rightarrow2" },
332 { "Rightcircle", "rightcircle2" },
333 { "Sigma", "sigma2" },
334 { "Square", "square2" },
335 { "Subset", "subset2" },
336 { "Supset", "supset2" },
337 { "Theta", "theta2" },
338 { "Thorn", "thorn2" },
339 { "UParrow", "uparrow3" },
340 { "Uparrow", "uparrow2" },
341 { "Updownarrow", "updownarrow2" },
342 { "Upsilon", "upsilon2" },
343 { "Vdash", "vdash3" },
348 { "lVert", "vert2" },
350 { "nLeftarrow", "nleftarrow2" },
351 { "nLeftrightarrow", "nleftrightarrow2" },
352 { "nRightarrow", "nrightarrow2" },
353 { "nVDash", "nvdash3" },
354 { "nVdash", "nvdash4" },
355 { "nvDash", "nvdash2" },
356 { "rVert", "vert2" },
358 { "textrm \\AA", "textrm_AA"},
359 { "textrm \\O", "textrm_O"},
360 { "vDash", "vdash2" },
361 { "varDelta", "vardelta2" },
362 { "varGamma", "vargamma2" },
363 { "varLambda", "varlambda2" },
364 { "varOmega", "varomega2" },
365 { "varPhi", "varphi2" },
366 { "varPi", "varpi2" },
367 { "varPsi", "varpsi2" },
368 { "varSigma", "varsigma2" },
369 { "varTheta", "vartheta2" },
370 { "varUpsilon", "varupsilon2" },
371 { "varXi", "varxi2" }
375 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
377 // This list specifies which system's theme icon is related to which lyx
378 // command. It was based on:
379 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
380 // this must be sorted alphabetically
381 // Upper case comes before lower case
382 PngMap sorted_theme_icon_map[] = {
383 { "bookmark-goto 0", "go-jump" },
384 { "buffer-new", "document-new" },
385 { "buffer-print", "document-print" },
386 { "buffer-write", "document-save" },
387 { "buffer-write-as", "document-save-as" },
388 { "buffer-zoom-in", "zoom-in" },
389 { "buffer-zoom-out", "zoom-out" },
390 { "copy", "edit-copy" },
391 { "cut", "edit-cut" },
392 { "depth-decrement", "format-indent-less" },
393 { "depth-increment", "format-indent-more" },
394 { "dialog-show print", "document-print" },
395 { "dialog-show spellchecker", "tools-check-spelling" },
396 { "dialog-show-new-inset graphics", "insert-image" },
397 { "dialog-toggle findreplaceadv", "edit-find-replace" },
398 { "file-open", "document-open" },
399 { "font-bold", "format-text-bold" },
400 { "font-ital", "format-text-italic" },
401 { "font-strikeout", "format-text-strikethrough" },
402 { "font-underline", "format-text-underline" },
403 { "lyx-quit", "application-exit" },
404 { "paste", "edit-paste" },
405 { "redo", "edit-redo" },
406 { "undo", "edit-undo" },
407 { "window-close", "window-close" },
408 { "window-new", "window-new" }
411 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
414 QString findPng(QString const & name)
416 PngMap const * const begin = sorted_png_map;
417 PngMap const * const end = begin + nr_sorted_png_map;
418 LATTEST(sorted(begin, end));
420 PngMap const * const it = find_if(begin, end, CompareKey(name));
424 png_name = it->value;
427 png_name.replace('_', "underscore");
428 png_name.replace(' ', '_');
430 // This way we can have "math-delim { }" on the toolbar.
431 png_name.replace('(', "lparen");
432 png_name.replace(')', "rparen");
433 png_name.replace('[', "lbracket");
434 png_name.replace(']', "rbracket");
435 png_name.replace('{', "lbrace");
436 png_name.replace('}', "rbrace");
437 png_name.replace('|', "bars");
438 png_name.replace(',', "thinspace");
439 png_name.replace(':', "mediumspace");
440 png_name.replace(';', "thickspace");
441 png_name.replace('!', "negthinspace");
444 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
445 << "Looking for math PNG called \"" << png_name << '"');
452 QString themeIconName(QString const & action)
454 PngMap const * const begin = sorted_theme_icon_map;
455 PngMap const * const end = begin + nr_sorted_theme_icon_map;
456 LASSERT(sorted(begin, end), /**/);
458 PngMap const * const it = find_if(begin, end, CompareKey(action));
466 QString iconName(FuncRequest const & f, bool unknown)
468 initializeResources();
472 switch (f.action()) {
473 case LFUN_MATH_INSERT:
474 if (!f.argument().empty()) {
476 name1 = findPng(toqstr(f.argument()).mid(1));
479 case LFUN_MATH_DELIM:
480 case LFUN_MATH_BIGDELIM:
482 name1 = findPng(toqstr(f.argument()));
486 name1 = toqstr(f.argument());
488 case LFUN_COMMAND_ALTERNATIVES: {
489 // use the first of the alternative commands
491 docstring dummy = split(f.argument(), firstcom, ';');
492 name1 = toqstr(firstcom);
493 // FIXME: we should rename the icons to tabular-xxx instead of
494 // "tabular-feature-xxx"
495 name1.replace("inset-modify tabular", "tabular-feature");
496 name1.replace(' ', '_');
499 case LFUN_INSET_MODIFY: {
500 // FIXME: we should rename the icons to tabular-xxx instead of
501 // "tabular-feature-xxx" and generalize this naming to all
502 // insets, not to tabular using ones.
504 string const command = split(to_utf8(f.argument()), inset_name, ' ');
505 if (insetCode(inset_name) == TABULAR_CODE) {
506 name1 = "tabular-feature "+ toqstr(command);
507 name1.replace(' ', '_');
512 name2 = toqstr(lyxaction.getActionName(f.action()));
515 if (!f.argument().empty()) {
516 name1 = name2 + ' ' + toqstr(f.argument());
517 name1.replace(' ', '_');
518 name1.replace('\\', "backslash");
522 QStringList imagedirs;
523 imagedirs << "images/" << "images/ipa/";
524 search_mode mode = theGuiApp()->imageSearchMode();
525 for (int i = 0; i < imagedirs.size(); ++i) {
526 QString imagedir = imagedirs.at(i) + path;
527 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
529 return toqstr(fname.absFileName());
531 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
533 return toqstr(fname.absFileName());
536 path = ":/images/" + path;
539 LYXERR0("Directory " << path << " not found in resource!");
542 if (res.exists(name1 + ".svgz"))
543 return path + name1 + ".svgz";
544 else if (res.exists(name1 + ".png"))
545 return path + name1 + ".png";
547 if (res.exists(name2 + ".svgz"))
548 return path + name2 + ".svgz";
549 else if (res.exists(name2 + ".png"))
550 return path + name2 + ".png";
552 LYXERR(Debug::GUI, "Cannot find icon with filename "
553 << "\"" << name1 << ".{svgz,png}\""
555 << "\"" << name2 << ".{svgz,png}\""
557 << lyxaction.getActionName(f.action())
558 << '(' << to_utf8(f.argument()) << ")\"");
561 QString imagedir = "images/";
562 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
564 return toqstr(fname.absFileName());
565 return QString(":/images/unknown.png");
571 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
574 QString imagedir = path;
575 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
576 QString fpath = toqstr(fname.absFileName());
578 if (pixmap.load(fpath)) {
581 QStringList exts = ext.split(",");
582 fpath = ":/" + path + name + ".";
583 for (int i = 0; i < exts.size(); ++i) {
584 if (pixmap.load(fpath + exts.at(i)))
589 bool const list = ext.contains(",");
590 LYXERR0("Cannot load pixmap \""
591 << path << name << "." << (list ? "{" : "") << ext
592 << (list ? "}" : "") << "\", please verify resource system!");
597 QIcon getIcon(FuncRequest const & f, bool unknown)
599 #if (QT_VERSION >= 0x040600)
600 if (lyxrc.use_system_theme_icons) {
601 QString action = toqstr(lyxaction.getActionName(f.action()));
602 if (!f.argument().empty())
603 action += " " + toqstr(f.argument());
604 QString const theme_icon = themeIconName(action);
605 if (QIcon::hasThemeIcon(theme_icon))
606 return QIcon::fromTheme(theme_icon);
610 QString icon = iconName(f, unknown);
614 //LYXERR(Debug::GUI, "Found icon: " << icon);
616 if (!pm.load(icon)) {
617 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
625 ////////////////////////////////////////////////////////////////////////
627 // LyX server support code.
629 ////////////////////////////////////////////////////////////////////////
631 class SocketNotifier : public QSocketNotifier
634 /// connect a connection notification from the LyXServerSocket
635 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
636 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
640 /// The callback function
641 Application::SocketCallback func_;
645 ////////////////////////////////////////////////////////////////////////
647 // Mac specific stuff goes here...
649 ////////////////////////////////////////////////////////////////////////
651 class MenuTranslator : public QTranslator
654 MenuTranslator(QObject * parent)
655 : QTranslator(parent)
658 #if QT_VERSION >= 0x050000
659 virtual QString translate(const char * /* context */,
660 const char *sourceText,
661 const char * /* disambiguation */ = 0, int /* n */ = -1) const
663 QString translate(const char * /*context*/,
664 const char * sourceText,
665 const char * /*comment*/ = 0) const
668 string const s = sourceText;
669 if (s == N_("About %1") || s == N_("Preferences")
670 || s == N_("Reconfigure") || s == N_("Quit %1"))
678 // QMacPasteboardMimeGraphics can only be compiled on Mac.
680 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
683 QMacPasteboardMimeGraphics()
684 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
687 QString convertorName() { return "Graphics"; }
689 QString flavorFor(QString const & mime)
691 LYXERR(Debug::ACTION, "flavorFor " << mime);
692 if (mime == pdfMimeType())
693 return QLatin1String("com.adobe.pdf");
697 QString mimeFor(QString flav)
699 LYXERR(Debug::ACTION, "mimeFor " << flav);
700 if (flav == QLatin1String("com.adobe.pdf"))
701 return pdfMimeType();
705 bool canConvert(QString const & mime, QString flav)
707 return mimeFor(flav) == mime;
710 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
714 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
718 QList<QByteArray> convertFromMime(QString const & /*mime*/,
719 QVariant data, QString /*flav*/)
721 QList<QByteArray> ret;
722 ret.append(data.toByteArray());
728 ///////////////////////////////////////////////////////////////
730 // You can find more platform specific stuff at the end of this file...
732 ///////////////////////////////////////////////////////////////
734 ////////////////////////////////////////////////////////////////////////
735 // Windows specific stuff goes here...
737 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
738 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
739 // QWindowsMimeMetafile can only be compiled on Windows.
741 static FORMATETC cfFromMime(QString const & mimetype)
744 if (mimetype == emfMimeType()) {
745 formatetc.cfFormat = CF_ENHMETAFILE;
746 formatetc.tymed = TYMED_ENHMF;
747 } else if (mimetype == wmfMimeType()) {
748 formatetc.cfFormat = CF_METAFILEPICT;
749 formatetc.tymed = TYMED_MFPICT;
752 formatetc.dwAspect = DVASPECT_CONTENT;
753 formatetc.lindex = -1;
758 class QWindowsMimeMetafile : public QWINDOWSMIME {
760 QWindowsMimeMetafile() {}
762 bool canConvertFromMime(FORMATETC const & formatetc,
763 QMimeData const * mimedata) const
768 bool canConvertToMime(QString const & mimetype,
769 IDataObject * pDataObj) const
771 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
773 FORMATETC formatetc = cfFromMime(mimetype);
774 return pDataObj->QueryGetData(&formatetc) == S_OK;
777 bool convertFromMime(FORMATETC const & formatetc,
778 const QMimeData * mimedata, STGMEDIUM * pmedium) const
783 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
784 QVariant::Type preferredType) const
787 if (!canConvertToMime(mimetype, pDataObj))
790 FORMATETC formatetc = cfFromMime(mimetype);
792 if (pDataObj->GetData(&formatetc, &s) != S_OK)
796 if (s.tymed == TYMED_ENHMF) {
797 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
798 data.resize(dataSize);
799 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
800 (LPBYTE)data.data());
801 } else if (s.tymed == TYMED_MFPICT) {
802 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
803 data.resize(dataSize);
804 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
805 (LPBYTE)data.data());
808 ReleaseStgMedium(&s);
814 QVector<FORMATETC> formatsForMime(QString const & mimetype,
815 QMimeData const * mimedata) const
817 QVector<FORMATETC> formats;
818 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
819 formats += cfFromMime(mimetype);
823 QString mimeForFormat(FORMATETC const & formatetc) const
825 switch (formatetc.cfFormat) {
827 return emfMimeType();
828 case CF_METAFILEPICT:
829 return wmfMimeType();
839 /// Allows to check whether ESC was pressed during a long operation
840 class KeyChecker : public QObject {
845 KeyChecker() : pressed_(false), started_(false) {}
848 QCoreApplication::instance()->installEventFilter(this);
853 QCoreApplication::instance()->removeEventFilter(this);
857 QCoreApplication::processEvents();
860 bool started() const {
863 bool eventFilter(QObject *obj, QEvent *event) {
864 LYXERR(Debug::ACTION, "Event Type: " << event->type());
865 switch (event->type()) {
869 case QEvent::UpdateRequest:
870 case QEvent::CursorChange:
871 case QEvent::ActionChanged:
872 case QEvent::EnabledChange:
873 case QEvent::SockAct:
876 case QEvent::ToolTipChange:
877 case QEvent::LayoutRequest:
878 case QEvent::MetaCall:
879 return QObject::eventFilter(obj, event);
881 // FIXME Blocking all these events is a bad idea.
882 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
883 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
891 ////////////////////////////////////////////////////////////////////////
892 // GuiApplication::Private definition and implementation.
893 ////////////////////////////////////////////////////////////////////////
895 struct GuiApplication::Private
897 Private(): language_model_(0), meta_fake_bit(NoModifier),
900 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
901 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
902 /// WMF Mime handler for Windows clipboard.
903 wmf_mime_ = new QWindowsMimeMetafile;
906 initKeySequences(&theTopLevelKeymap());
909 void initKeySequences(KeyMap * kb)
911 keyseq = KeySequence(kb, kb);
912 cancel_meta_seq = KeySequence(kb, kb);
916 QSortFilterProxyModel * language_model_;
918 GuiClipboard clipboard_;
920 GuiSelection selection_;
922 FontLoader font_loader_;
924 ColorCache color_cache_;
926 QTranslator qt_trans_;
928 QHash<int, SocketNotifier *> socket_notifiers_;
932 /// The global instance
935 /// this timer is used for any regular events one wants to
936 /// perform. at present it is used to check if forked processes
938 QTimer general_timer_;
940 /// delayed FuncRequests
941 std::queue<FuncRequest> func_request_queue_;
946 KeySequence cancel_meta_seq;
948 KeyModifier meta_fake_bit;
950 /// Multiple views container.
952 * Warning: This must not be a smart pointer as the destruction of the
953 * object is handled by Qt when the view is closed
954 * \sa Qt::WA_DeleteOnClose attribute.
956 QHash<int, GuiView *> views_;
958 /// Only used on mac.
959 QMenuBar * global_menubar_;
962 /// Linkback mime handler for MacOSX.
963 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
966 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
967 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
968 /// WMF Mime handler for Windows clipboard.
969 QWindowsMimeMetafile * wmf_mime_;
973 /// Allows to check whether ESC was pressed during a long operation
974 KeyChecker key_checker_;
978 GuiApplication * guiApp;
980 GuiApplication::~GuiApplication()
983 closeAllLinkBackLinks();
989 GuiApplication::GuiApplication(int & argc, char ** argv)
990 : QApplication(argc, argv), current_view_(0),
991 d(new GuiApplication::Private)
993 QString app_name = "LyX";
994 QCoreApplication::setOrganizationName(app_name);
995 QCoreApplication::setOrganizationDomain("lyx.org");
996 QCoreApplication::setApplicationName(lyx_package);
998 qsrand(QDateTime::currentDateTime().toTime_t());
1000 // Install translator for GUI elements.
1001 installTranslator(&d->qt_trans_);
1004 // Enable reception of XCB events.
1005 installNativeEventFilter(this);
1008 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1009 // lyxrc setting for this in order to let the application stay resident.
1010 // But then we need some kind of dock icon, at least on Windows.
1012 if (lyxrc.quit_on_last_window_closed)
1013 setQuitOnLastWindowClosed(false);
1016 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1017 // seems to be the default case for applications like LyX.
1018 setQuitOnLastWindowClosed(false);
1019 // This allows to translate the strings that appear in the LyX menu.
1020 /// A translator suitable for the entries in the LyX menu.
1021 /// Only needed with Qt/Mac.
1022 installTranslator(new MenuTranslator(this));
1027 #if defined(Q_WS_X11) || defined(QPA_XCB)
1028 // doubleClickInterval() is 400 ms on X11 which is just too long.
1029 // On Windows and Mac OS X, the operating system's value is used.
1030 // On Microsoft Windows, calling this function sets the double
1031 // click interval for all applications. So we don't!
1032 QApplication::setDoubleClickInterval(300);
1035 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1037 // needs to be done before reading lyxrc
1039 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1043 // Set the cache to 5120 kilobytes which corresponds to screen size of
1044 // 1280 by 1024 pixels with a color depth of 32 bits.
1045 QPixmapCache::setCacheLimit(5120);
1047 // Initialize RC Fonts
1048 if (lyxrc.roman_font_name.empty())
1049 lyxrc.roman_font_name = fromqstr(romanFontName());
1051 if (lyxrc.sans_font_name.empty())
1052 lyxrc.sans_font_name = fromqstr(sansFontName());
1054 if (lyxrc.typewriter_font_name.empty())
1055 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1057 d->general_timer_.setInterval(500);
1058 connect(&d->general_timer_, SIGNAL(timeout()),
1059 this, SLOT(handleRegularEvents()));
1060 d->general_timer_.start();
1062 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1063 // This is clearly not enough in a time where we use threads for
1064 // document preview and/or export. 20 should be OK.
1065 QThreadPool::globalInstance()->setMaxThreadCount(20);
1069 GuiApplication * theGuiApp()
1071 return dynamic_cast<GuiApplication *>(theApp());
1075 double GuiApplication::pixelRatio() const
1077 #if QT_VERSION >= 0x050000
1078 return devicePixelRatio();
1085 void GuiApplication::clearSession()
1092 docstring Application::iconName(FuncRequest const & f, bool unknown)
1094 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1098 docstring Application::mathIcon(docstring const & c)
1100 return qstring_to_ucs4(findPng(toqstr(c)));
1104 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1108 BufferView * bv = 0;
1109 BufferView * doc_bv = 0;
1111 if (cmd.action() == LFUN_NOACTION) {
1112 status.message(from_utf8(N_("Nothing to do")));
1113 status.setEnabled(false);
1116 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1117 status.setUnknown(true);
1118 status.message(from_utf8(N_("Unknown action")));
1119 status.setEnabled(false);
1122 // Does the GuiApplication know something?
1123 else if (getStatus(cmd, status)) { }
1125 // If we do not have a GuiView, then other functions are disabled
1126 else if (!current_view_)
1127 status.setEnabled(false);
1129 // Does the GuiView know something?
1130 else if (current_view_->getStatus(cmd, status)) { }
1132 // In LyX/Mac, when a dialog is open, the menus of the
1133 // application can still be accessed without giving focus to
1134 // the main window. In this case, we want to disable the menu
1135 // entries that are buffer or view-related.
1136 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1138 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1139 status.setEnabled(false);
1142 // If we do not have a BufferView, then other functions are disabled
1143 else if (!(bv = current_view_->currentBufferView()))
1144 status.setEnabled(false);
1146 // Does the current BufferView know something?
1147 else if (bv->getStatus(cmd, status)) { }
1149 // Does the current Buffer know something?
1150 else if (bv->buffer().getStatus(cmd, status)) { }
1152 // If we do not have a document BufferView, different from the
1153 // current BufferView, then other functions are disabled
1154 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1155 status.setEnabled(false);
1157 // Does the document Buffer know something?
1158 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1161 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1162 status.message(from_utf8(N_("Command not handled")));
1163 status.setEnabled(false);
1166 // the default error message if we disable the command
1167 if (!status.enabled() && status.message().empty())
1168 status.message(from_utf8(N_("Command disabled")));
1174 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1176 // I would really like to avoid having this switch and rather try to
1177 // encode this in the function itself.
1178 // -- And I'd rather let an inset decide which LFUNs it is willing
1179 // to handle (Andre')
1181 switch (cmd.action()) {
1183 // This could be used for the no-GUI version. The GUI version is handled in
1184 // GuiView::getStatus(). See above.
1186 case LFUN_BUFFER_WRITE:
1187 case LFUN_BUFFER_WRITE_AS: {
1188 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1189 enable = b && (b->isUnnamed() || !b->isClean());
1194 case LFUN_BOOKMARK_GOTO: {
1195 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1196 enable = theSession().bookmarks().isValid(num);
1200 case LFUN_BOOKMARK_CLEAR:
1201 enable = theSession().bookmarks().hasValid();
1204 // this one is difficult to get right. As a half-baked
1205 // solution, we consider only the first action of the sequence
1206 case LFUN_COMMAND_SEQUENCE: {
1207 // argument contains ';'-terminated commands
1208 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1209 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1210 func.setOrigin(cmd.origin());
1211 flag = getStatus(func);
1215 // we want to check if at least one of these is enabled
1216 case LFUN_COMMAND_ALTERNATIVES: {
1217 // argument contains ';'-terminated commands
1218 string arg = to_utf8(cmd.argument());
1219 while (!arg.empty()) {
1221 arg = split(arg, first, ';');
1222 FuncRequest func(lyxaction.lookupFunc(first));
1223 func.setOrigin(cmd.origin());
1224 flag = getStatus(func);
1225 // if this one is enabled, the whole thing is
1234 string name = to_utf8(cmd.argument());
1235 if (theTopLevelCmdDef().lock(name, func)) {
1236 func.setOrigin(cmd.origin());
1237 flag = getStatus(func);
1238 theTopLevelCmdDef().release(name);
1240 // catch recursion or unknown command
1241 // definition. all operations until the
1242 // recursion or unknown command definition
1243 // occurs are performed, so set the state to
1250 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1252 case LFUN_PREFERENCES_SAVE:
1253 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1254 case LFUN_DEBUG_LEVEL_SET:
1255 // these are handled in our dispatch()
1258 case LFUN_WINDOW_CLOSE:
1259 enable = d->views_.size() > 0;
1262 case LFUN_BUFFER_NEW:
1263 case LFUN_BUFFER_NEW_TEMPLATE:
1264 case LFUN_FILE_OPEN:
1265 case LFUN_HELP_OPEN:
1266 case LFUN_SCREEN_FONT_UPDATE:
1267 case LFUN_SET_COLOR:
1268 case LFUN_WINDOW_NEW:
1270 case LFUN_LYXRC_APPLY:
1271 case LFUN_COMMAND_PREFIX:
1273 case LFUN_META_PREFIX:
1274 case LFUN_RECONFIGURE:
1275 case LFUN_SERVER_GET_FILENAME:
1276 case LFUN_SERVER_NOTIFY:
1280 case LFUN_BUFFER_FORALL: {
1281 if (theBufferList().empty()) {
1282 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1283 flag.setEnabled(false);
1287 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1288 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1289 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1290 flag.setEnabled(false);
1295 case LFUN_DIALOG_SHOW: {
1296 string const name = cmd.getArg(0);
1297 return name == "aboutlyx"
1299 || name == "texinfo"
1300 || name == "progress"
1301 || name == "compare";
1309 flag.setEnabled(false);
1313 /// make a post-dispatch status message
1314 static docstring makeDispatchMessage(docstring const & msg,
1315 FuncRequest const & cmd)
1317 const bool verbose = (cmd.origin() == FuncRequest::MENU
1318 || cmd.origin() == FuncRequest::TOOLBAR
1319 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1321 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1322 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1326 docstring dispatch_msg = msg;
1327 if (!dispatch_msg.empty())
1328 dispatch_msg += ' ';
1330 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1332 bool argsadded = false;
1334 if (!cmd.argument().empty()) {
1335 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1336 comname += ' ' + cmd.argument();
1340 docstring const shortcuts = theTopLevelKeymap().
1341 printBindings(cmd, KeySequence::ForGui);
1343 if (!shortcuts.empty())
1344 comname += ": " + shortcuts;
1345 else if (!argsadded && !cmd.argument().empty())
1346 comname += ' ' + cmd.argument();
1348 if (!comname.empty()) {
1349 comname = rtrim(comname);
1350 dispatch_msg += '(' + rtrim(comname) + ')';
1352 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1353 return dispatch_msg;
1357 void GuiApplication::dispatch(FuncRequest const & cmd)
1359 Buffer * buffer = 0;
1360 if (current_view_ && current_view_->currentBufferView()) {
1361 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1362 buffer = ¤t_view_->currentBufferView()->buffer();
1364 buffer->undo().beginUndoGroup();
1368 // redraw the screen at the end (first of the two drawing steps).
1369 // This is done unless explicitly requested otherwise
1370 dr.screenUpdate(Update::FitCursor);
1372 updateCurrentView(cmd, dr);
1374 // the buffer may have been closed by one action
1375 if (theBufferList().isLoaded(buffer))
1376 buffer->undo().endUndoGroup();
1380 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1385 BufferView * bv = current_view_->currentBufferView();
1387 if (dr.needBufferUpdate()) {
1388 bv->cursor().clearBufferUpdate();
1389 bv->buffer().updateBuffer();
1391 // BufferView::update() updates the ViewMetricsInfo and
1392 // also initializes the position cache for all insets in
1393 // (at least partially) visible top-level paragraphs.
1394 // We will redraw the screen only if needed.
1395 bv->processUpdateFlags(dr.screenUpdate());
1397 // Do we have a selection?
1398 theSelection().haveSelection(bv->cursor().selection());
1401 current_view_->restartCursor();
1403 if (dr.needMessageUpdate()) {
1404 // Some messages may already be translated, so we cannot use _()
1405 current_view_->message(makeDispatchMessage(
1406 translateIfPossible(dr.message()), cmd));
1411 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1412 bool switchToBuffer)
1414 if (!theSession().bookmarks().isValid(idx))
1416 BookmarksSection::Bookmark const & bm =
1417 theSession().bookmarks().bookmark(idx);
1418 LASSERT(!bm.filename.empty(), return);
1419 string const file = bm.filename.absFileName();
1420 // if the file is not opened, open it.
1421 if (!theBufferList().exists(bm.filename)) {
1423 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1427 // open may fail, so we need to test it again
1428 if (!theBufferList().exists(bm.filename))
1431 // bm can be changed when saving
1432 BookmarksSection::Bookmark tmp = bm;
1434 // Special case idx == 0 used for back-from-back jump navigation
1436 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1438 // if the current buffer is not that one, switch to it.
1439 BufferView * doc_bv = current_view_ ?
1440 current_view_->documentBufferView() : 0;
1441 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1442 if (switchToBuffer) {
1443 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1446 doc_bv = current_view_->documentBufferView();
1451 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1452 if (!doc_bv->moveToPosition(
1453 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1460 // Cursor jump succeeded!
1461 Cursor const & cur = doc_bv->cursor();
1462 pit_type new_pit = cur.pit();
1463 pos_type new_pos = cur.pos();
1464 int new_id = cur.paragraph().id();
1466 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1467 // see http://www.lyx.org/trac/ticket/3092
1468 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1469 || bm.top_id != new_id) {
1470 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1471 new_pit, new_pos, new_id);
1475 // This function runs "configure" and then rereads lyx.defaults to
1476 // reconfigure the automatic settings.
1477 void GuiApplication::reconfigure(string const & option)
1479 // emit message signal.
1481 current_view_->message(_("Running configure..."));
1483 // Run configure in user lyx directory
1484 string const lock_file = package().getConfigureLockName();
1485 int fd = fileLock(lock_file.c_str());
1486 int const ret = package().reconfigureUserLyXDir(option);
1487 // emit message signal.
1489 current_view_->message(_("Reloading configuration..."));
1490 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1491 // Re-read packages.lst
1492 LaTeXPackages::getAvailable();
1493 fileUnlock(fd, lock_file.c_str());
1496 Alert::information(_("System reconfiguration failed"),
1497 _("The system reconfiguration has failed.\n"
1498 "Default textclass is used but LyX may\n"
1499 "not be able to work properly.\n"
1500 "Please reconfigure again if needed."));
1502 Alert::information(_("System reconfigured"),
1503 _("The system has been reconfigured.\n"
1504 "You need to restart LyX to make use of any\n"
1505 "updated document class specifications."));
1508 void GuiApplication::validateCurrentView()
1510 if (!d->views_.empty() && !current_view_) {
1511 // currently at least one view exists but no view has the focus.
1512 // choose the last view to make it current.
1513 // a view without any open document is preferred.
1514 GuiView * candidate = 0;
1515 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1516 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1517 for (; it != end; ++it) {
1519 if (!candidate->documentBufferView())
1522 setCurrentView(candidate);
1526 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1528 string const argument = to_utf8(cmd.argument());
1529 FuncCode const action = cmd.action();
1531 LYXERR(Debug::ACTION, "cmd: " << cmd);
1533 // we have not done anything wrong yet.
1536 FuncStatus const flag = getStatus(cmd);
1537 if (!flag.enabled()) {
1538 // We cannot use this function here
1539 LYXERR(Debug::ACTION, "action "
1540 << lyxaction.getActionName(action)
1541 << " [" << action << "] is disabled at this location");
1542 dr.setMessage(flag.message());
1544 dr.dispatched(false);
1545 dr.screenUpdate(Update::None);
1546 dr.clearBufferUpdate();
1550 if (cmd.origin() == FuncRequest::LYXSERVER) {
1551 if (current_view_ && current_view_->currentBufferView())
1552 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1553 // we will also need to redraw the screen at the end
1554 dr.screenUpdate(Update::FitCursor);
1557 // Assumes that the action will be dispatched.
1558 dr.dispatched(true);
1560 switch (cmd.action()) {
1562 case LFUN_WINDOW_NEW:
1563 createView(toqstr(cmd.argument()));
1566 case LFUN_WINDOW_CLOSE:
1567 // update bookmark pit of the current buffer before window close
1568 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1569 gotoBookmark(i+1, false, false);
1570 // clear the last opened list, because
1571 // maybe this will end the session
1572 theSession().lastOpened().clear();
1573 // check for valid current_view_
1574 validateCurrentView();
1576 current_view_->closeScheduled();
1580 // quitting is triggered by the gui code
1581 // (leaving the event loop).
1583 current_view_->message(from_utf8(N_("Exiting.")));
1584 if (closeAllViews())
1588 case LFUN_SCREEN_FONT_UPDATE: {
1589 // handle the screen font changes.
1590 d->font_loader_.update();
1591 // Backup current_view_
1592 GuiView * view = current_view_;
1593 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1594 // to skip the refresh.
1596 theBufferList().changed(false);
1597 // Restore current_view_
1598 current_view_ = view;
1602 case LFUN_BUFFER_NEW:
1603 validateCurrentView();
1604 if (d->views_.empty()
1605 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1606 createView(QString(), false); // keep hidden
1607 current_view_->newDocument(to_utf8(cmd.argument()), false);
1608 current_view_->show();
1609 setActiveWindow(current_view_);
1611 current_view_->newDocument(to_utf8(cmd.argument()), false);
1615 case LFUN_BUFFER_NEW_TEMPLATE:
1616 validateCurrentView();
1617 if (d->views_.empty()
1618 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1620 current_view_->newDocument(to_utf8(cmd.argument()), true);
1621 if (!current_view_->documentBufferView())
1622 current_view_->close();
1624 current_view_->newDocument(to_utf8(cmd.argument()), true);
1628 case LFUN_FILE_OPEN: {
1629 validateCurrentView();
1630 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1631 string const fname = to_utf8(cmd.argument());
1632 bool const is_open = FileName::isAbsolute(fname)
1633 && theBufferList().getBuffer(FileName(fname));
1634 if (d->views_.empty()
1635 || (!lyxrc.open_buffers_in_tabs
1636 && current_view_->documentBufferView() != 0
1638 // We want the ui session to be saved per document and not per
1639 // window number. The filename crc is a good enough identifier.
1640 boost::crc_32_type crc;
1641 crc = for_each(fname.begin(), fname.end(), crc);
1642 createView(crc.checksum());
1643 current_view_->openDocument(fname);
1644 if (current_view_ && !current_view_->documentBufferView())
1645 current_view_->close();
1647 current_view_->openDocument(fname);
1651 case LFUN_HELP_OPEN: {
1652 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1653 if (current_view_ == 0)
1655 string const arg = to_utf8(cmd.argument());
1657 current_view_->message(_("Missing argument"));
1660 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1662 fname = i18nLibFileSearch("examples", arg, "lyx");
1664 if (fname.empty()) {
1665 lyxerr << "LyX: unable to find documentation file `"
1666 << arg << "'. Bad installation?" << endl;
1669 current_view_->message(bformat(_("Opening help file %1$s..."),
1670 makeDisplayPath(fname.absFileName())));
1671 Buffer * buf = current_view_->loadDocument(fname, false);
1673 #ifndef DEVEL_VERSION
1675 buf->setReadonly(true);
1682 case LFUN_SET_COLOR: {
1684 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1685 if (lyx_name.empty() || x11_name.empty()) {
1687 current_view_->message(
1688 _("Syntax: set-color <lyx_name> <x11_name>"));
1693 // FIXME: The graphics cache no longer has a changeDisplay method.
1694 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1695 bool const graphicsbg_changed =
1696 lyx_name == graphicsbg && x11_name != graphicsbg;
1697 if (graphicsbg_changed)
1698 graphics::GCache::get().changeDisplay(true);
1701 if (!lcolor.setColor(lyx_name, x11_name)) {
1703 current_view_->message(
1704 bformat(_("Set-color \"%1$s\" failed "
1705 "- color is undefined or "
1706 "may not be redefined"),
1707 from_utf8(lyx_name)));
1710 // Make sure we don't keep old colors in cache.
1711 d->color_cache_.clear();
1715 case LFUN_LYXRC_APPLY: {
1716 // reset active key sequences, since the bindings
1717 // are updated (bug 6064)
1719 LyXRC const lyxrc_orig = lyxrc;
1721 istringstream ss(to_utf8(cmd.argument()));
1722 bool const success = lyxrc.read(ss);
1725 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1726 << "Unable to read lyxrc data"
1731 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1733 // If the request comes from the minibuffer, then we can't reset
1734 // the GUI, since that would destory the minibuffer itself and
1735 // cause a crash, since we are currently in one of the methods of
1736 // GuiCommandBuffer. See bug #8540.
1737 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1740 // FIXME Unfortunately, that leaves a bug here, since we cannot
1741 // reset the GUI in this case. If the changes to lyxrc affected the
1742 // UI, then, nothing would happen. This seems fairly unlikely, but
1743 // it definitely is a bug.
1748 case LFUN_COMMAND_PREFIX:
1749 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1754 d->meta_fake_bit = NoModifier;
1755 GuiView * gv = currentView();
1756 if (gv && gv->currentBufferView())
1757 // cancel any selection
1758 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1759 dr.setMessage(from_ascii(N_("Cancel")));
1762 case LFUN_META_PREFIX:
1763 d->meta_fake_bit = AltModifier;
1764 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1767 // --- Menus -----------------------------------------------
1768 case LFUN_RECONFIGURE:
1769 // argument is any additional parameter to the configure.py command
1770 reconfigure(to_utf8(cmd.argument()));
1773 // --- lyxserver commands ----------------------------
1774 case LFUN_SERVER_GET_FILENAME: {
1775 if (current_view_ && current_view_->documentBufferView()) {
1776 docstring const fname = from_utf8(
1777 current_view_->documentBufferView()->buffer().absFileName());
1778 dr.setMessage(fname);
1779 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1781 dr.setMessage(docstring());
1782 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1787 case LFUN_SERVER_NOTIFY: {
1788 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1789 dr.setMessage(dispatch_buffer);
1790 theServer().notifyClient(to_utf8(dispatch_buffer));
1794 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1795 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1801 string rest = split(argument, countstr, ' ');
1802 istringstream is(countstr);
1805 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1806 for (int i = 0; i < count; ++i)
1807 dispatch(lyxaction.lookupFunc(rest));
1811 case LFUN_COMMAND_SEQUENCE: {
1812 // argument contains ';'-terminated commands
1813 string arg = argument;
1814 // FIXME: this LFUN should also work without any view.
1815 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1816 ? &(current_view_->documentBufferView()->buffer()) : 0;
1818 buffer->undo().beginUndoGroup();
1819 while (!arg.empty()) {
1821 arg = split(arg, first, ';');
1822 FuncRequest func(lyxaction.lookupFunc(first));
1823 func.setOrigin(cmd.origin());
1826 // the buffer may have been closed by one action
1827 if (theBufferList().isLoaded(buffer))
1828 buffer->undo().endUndoGroup();
1832 case LFUN_BUFFER_FORALL: {
1833 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1835 map<Buffer *, GuiView *> views_lVisible;
1836 map<GuiView *, Buffer *> activeBuffers;
1838 QList<GuiView *> allViews = d->views_.values();
1840 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1841 // and on which buffer is active in each view.
1842 Buffer * const last = theBufferList().last();
1843 foreach (GuiView * view, allViews) {
1844 // all of the buffers might be locally hidden. That is, there is no active buffer.
1845 if (!view || !view->currentBufferView())
1846 activeBuffers[view] = 0;
1848 activeBuffers[view] = &view->currentBufferView()->buffer();
1850 // find out if each is locally visible or locally hidden.
1851 // we don't use a for loop as the buffer list cycles.
1852 Buffer * b = theBufferList().first();
1854 bool const locallyVisible = view && view->workArea(*b);
1855 if (locallyVisible) {
1856 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1857 // only need to overwrite/add if we don't already know a buffer is globally
1858 // visible or we do know but we would prefer to dispatch LFUN from the
1859 // current view because of cursor position issues.
1860 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1861 views_lVisible[b] = view;
1865 b = theBufferList().next(b);
1869 GuiView * const homeView = currentView();
1870 Buffer * b = theBufferList().first();
1871 Buffer * nextBuf = 0;
1872 int numProcessed = 0;
1875 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1877 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1879 // first change to a view where b is locally visible, preferably current_view_.
1880 GuiView * const vLv = views_lVisible[b];
1882 lyx::dispatch(funcToRun);
1890 // put things back to how they were (if possible).
1891 foreach (GuiView * view, allViews) {
1892 Buffer * originalBuf = activeBuffers[view];
1893 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1894 if (theBufferList().isLoaded(originalBuf))
1895 view->setBuffer(originalBuf);
1897 homeView->setFocus();
1899 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1903 case LFUN_COMMAND_ALTERNATIVES: {
1904 // argument contains ';'-terminated commands
1905 string arg = argument;
1906 while (!arg.empty()) {
1908 arg = split(arg, first, ';');
1909 FuncRequest func(lyxaction.lookupFunc(first));
1910 func.setOrigin(cmd.origin());
1911 FuncStatus const stat = getStatus(func);
1912 if (stat.enabled()) {
1922 if (theTopLevelCmdDef().lock(argument, func)) {
1923 func.setOrigin(cmd.origin());
1925 theTopLevelCmdDef().release(argument);
1927 if (func.action() == LFUN_UNKNOWN_ACTION) {
1928 // unknown command definition
1929 lyxerr << "Warning: unknown command definition `"
1933 // recursion detected
1934 lyxerr << "Warning: Recursion in the command definition `"
1935 << argument << "' detected"
1942 case LFUN_PREFERENCES_SAVE:
1943 lyxrc.write(support::makeAbsPath("preferences",
1944 package().user_support().absFileName()), false);
1947 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1948 string const fname = addName(addPath(package().user_support().absFileName(),
1949 "templates/"), "defaults.lyx");
1950 Buffer defaults(fname);
1952 istringstream ss(argument);
1957 // We need to make sure that, after we recreat the DocumentClass,
1958 // which we do in readHeader, we apply it to the document itself.
1959 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1960 int const unknown_tokens = defaults.readHeader(lex);
1961 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1963 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1964 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1966 if (unknown_tokens != 0) {
1967 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1968 << unknown_tokens << " unknown token"
1969 << (unknown_tokens == 1 ? "" : "s")
1973 if (defaults.writeFile(FileName(defaults.absFileName())))
1974 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1975 makeDisplayPath(fname)));
1978 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1983 case LFUN_BOOKMARK_GOTO:
1984 // go to bookmark, open unopened file and switch to buffer if necessary
1985 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1986 dr.screenUpdate(Update::Force | Update::FitCursor);
1989 case LFUN_BOOKMARK_CLEAR:
1990 theSession().bookmarks().clear();
1993 case LFUN_DEBUG_LEVEL_SET:
1994 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1997 case LFUN_DIALOG_SHOW: {
1998 string const name = cmd.getArg(0);
2000 if ( name == "aboutlyx"
2002 || name == "texinfo"
2003 || name == "progress"
2004 || name == "compare")
2006 // work around: on Mac OS the application
2007 // is not terminated when closing the last view.
2008 // Create a new one to be able to dispatch the
2009 // LFUN_DIALOG_SHOW to this view.
2010 if (current_view_ == 0)
2016 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2019 current_view_->dispatch(cmd, dr);
2023 if (cmd.origin() == FuncRequest::LYXSERVER)
2024 updateCurrentView(cmd, dr);
2028 docstring GuiApplication::viewStatusMessage()
2030 // When meta-fake key is pressed, show the key sequence so far + "M-".
2031 if (d->meta_fake_bit != NoModifier)
2032 return d->keyseq.print(KeySequence::ForGui) + "M-";
2034 // Else, when a non-complete key sequence is pressed,
2035 // show the available options.
2036 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2037 return d->keyseq.printOptions(true);
2043 void GuiApplication::handleKeyFunc(FuncCode action)
2047 if (d->keyseq.length())
2049 GuiView * gv = currentView();
2050 LASSERT(gv && gv->currentBufferView(), return);
2051 BufferView * bv = gv->currentBufferView();
2052 bv->getIntl().getTransManager().deadkey(
2053 c, get_accent(action).accent, bv->cursor().innerText(),
2055 // Need to clear, in case the minibuffer calls these
2058 // copied verbatim from do_accent_char
2059 bv->cursor().resetAnchor();
2063 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2065 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2067 // Do nothing if we have nothing (JMarc)
2068 if (!keysym.isOK()) {
2069 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2071 current_view_->restartCursor();
2075 if (keysym.isModifier()) {
2077 current_view_->restartCursor();
2081 char_type encoded_last_key = keysym.getUCSEncoded();
2083 // Do a one-deep top-level lookup for
2084 // cancel and meta-fake keys. RVDK_PATCH_5
2085 d->cancel_meta_seq.reset();
2087 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2088 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2090 // When not cancel or meta-fake, do the normal lookup.
2091 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2092 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2093 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2094 // remove Caps Lock and Mod2 as a modifiers
2095 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2096 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2099 // Dont remove this unless you know what you are doing.
2100 d->meta_fake_bit = NoModifier;
2102 // Can this happen now ?
2103 if (func.action() == LFUN_NOACTION)
2104 func = FuncRequest(LFUN_COMMAND_PREFIX);
2106 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2107 << d->keyseq.print(KeySequence::Portable) << ']');
2109 // already here we know if it any point in going further
2110 // why not return already here if action == -1 and
2111 // num_bytes == 0? (Lgb)
2113 if (d->keyseq.length() > 1 && current_view_)
2114 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2117 // Maybe user can only reach the key via holding down shift.
2118 // Let's see. But only if shift is the only modifier
2119 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2120 LYXERR(Debug::KEY, "Trying without shift");
2121 func = d->keyseq.addkey(keysym, NoModifier);
2122 LYXERR(Debug::KEY, "Action now " << func.action());
2125 if (func.action() == LFUN_UNKNOWN_ACTION) {
2126 // Hmm, we didn't match any of the keysequences. See
2127 // if it's normal insertable text not already covered
2129 if (keysym.isText() && d->keyseq.length() == 1) {
2130 LYXERR(Debug::KEY, "isText() is true, inserting.");
2131 func = FuncRequest(LFUN_SELF_INSERT,
2132 FuncRequest::KEYBOARD);
2134 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2135 if (current_view_) {
2136 current_view_->message(_("Unknown function."));
2137 current_view_->restartCursor();
2143 if (func.action() == LFUN_SELF_INSERT) {
2144 if (encoded_last_key != 0) {
2145 docstring const arg(1, encoded_last_key);
2146 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2147 FuncRequest::KEYBOARD));
2148 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2151 processFuncRequest(func);
2155 void GuiApplication::processFuncRequest(FuncRequest const & func)
2157 lyx::dispatch(func);
2161 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2163 addToFuncRequestQueue(func);
2164 processFuncRequestQueueAsync();
2168 void GuiApplication::processFuncRequestQueue()
2170 while (!d->func_request_queue_.empty()) {
2171 processFuncRequest(d->func_request_queue_.front());
2172 d->func_request_queue_.pop();
2177 void GuiApplication::processFuncRequestQueueAsync()
2179 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2183 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2185 d->func_request_queue_.push(func);
2189 void GuiApplication::resetGui()
2191 // Set the language defined by the user.
2195 if (!readUIFile(toqstr(lyxrc.ui_file)))
2196 // Gives some error box here.
2199 if (d->global_menubar_)
2200 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2202 QHash<int, GuiView *>::iterator it;
2203 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2206 gv->setLayoutDirection(layoutDirection());
2210 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2214 void GuiApplication::createView(int view_id)
2216 createView(QString(), true, view_id);
2220 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2223 // release the keyboard which might have been grabed by the global
2224 // menubar on Mac to catch shortcuts even without any GuiView.
2225 if (d->global_menubar_)
2226 d->global_menubar_->releaseKeyboard();
2230 while (d->views_.find(id) != d->views_.end())
2233 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2234 GuiView * view = new GuiView(id);
2236 d->views_[id] = view;
2240 setActiveWindow(view);
2243 if (!geometry_arg.isEmpty()) {
2244 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2248 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2249 re.indexIn(geometry_arg);
2250 w = re.cap(1).toInt();
2251 h = re.cap(2).toInt();
2252 x = re.cap(3).toInt();
2253 y = re.cap(4).toInt();
2254 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2255 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2256 // Set initial geometry such that we can get the frame size.
2257 view->setGeometry(x, y, w, h);
2258 int framewidth = view->geometry().x() - view->x();
2259 int titleheight = view->geometry().y() - view->y();
2260 // Negative displacements must be interpreted as distances
2261 // from the right or bottom screen borders.
2262 if (sx == '-' || sy == '-') {
2263 QRect rec = QApplication::desktop()->screenGeometry();
2265 x += rec.width() - w - framewidth;
2267 y += rec.height() - h - titleheight;
2268 view->setGeometry(x, y, w, h);
2270 // Make sure that the left and top frame borders are visible.
2271 if (view->x() < 0 || view->y() < 0) {
2276 view->setGeometry(x, y, w, h);
2284 Clipboard & GuiApplication::clipboard()
2286 return d->clipboard_;
2290 Selection & GuiApplication::selection()
2292 return d->selection_;
2296 FontLoader & GuiApplication::fontLoader()
2298 return d->font_loader_;
2302 Toolbars const & GuiApplication::toolbars() const
2304 return d->toolbars_;
2308 Toolbars & GuiApplication::toolbars()
2310 return d->toolbars_;
2314 Menus const & GuiApplication::menus() const
2320 Menus & GuiApplication::menus()
2326 QList<int> GuiApplication::viewIds() const
2328 return d->views_.keys();
2332 ColorCache & GuiApplication::colorCache()
2334 return d->color_cache_;
2338 int GuiApplication::exec()
2340 // asynchronously handle batch commands. This event will be in
2341 // the event queue in front of other asynchronous events. Hence,
2342 // we can assume in the latter that the gui is setup already.
2343 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2345 return QApplication::exec();
2349 void GuiApplication::exit(int status)
2351 QApplication::exit(status);
2355 void GuiApplication::setGuiLanguage()
2359 // install translation file for Qt built-in dialogs
2360 QString const language_name = QString("qt_") + theLocale.name();
2361 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2362 // Short-named translator can be loaded from a long name, but not the
2363 // opposite. Therefore, long name should be used without truncation.
2364 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2365 if (!d->qt_trans_.load(language_name,
2366 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2367 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2370 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2374 switch (theLocale.language()) {
2375 case QLocale::Arabic :
2376 case QLocale::Hebrew :
2377 case QLocale::Persian :
2378 case QLocale::Urdu :
2379 setLayoutDirection(Qt::RightToLeft);
2382 setLayoutDirection(Qt::LeftToRight);
2387 void GuiApplication::execBatchCommands()
2392 if (!readUIFile(toqstr(lyxrc.ui_file)))
2393 // Gives some error box here.
2397 #if QT_VERSION > 0x040600
2398 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2400 // Create the global default menubar which is shown for the dialogs
2401 // and if no GuiView is visible.
2402 // This must be done after the session was recovered to know the "last files".
2403 d->global_menubar_ = new QMenuBar(0);
2404 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2407 lyx::execBatchCommands();
2411 QAbstractItemModel * GuiApplication::languageModel()
2413 if (d->language_model_)
2414 return d->language_model_;
2416 QStandardItemModel * lang_model = new QStandardItemModel(this);
2417 lang_model->insertColumns(0, 3);
2419 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2420 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2421 Languages::const_iterator it = lyx::languages.begin();
2422 Languages::const_iterator end = lyx::languages.end();
2423 for (; it != end; ++it) {
2424 current_row = lang_model->rowCount();
2425 lang_model->insertRows(current_row, 1);
2426 QModelIndex pl_item = lang_model->index(current_row, 0);
2427 QModelIndex sp_item = lang_model->index(current_row, 1);
2428 QModelIndex th_item = lang_model->index(current_row, 2);
2429 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2430 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2431 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2432 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2433 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2434 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2435 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2436 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2437 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2438 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2440 d->language_model_ = new QSortFilterProxyModel(this);
2441 d->language_model_->setSourceModel(lang_model);
2442 d->language_model_->setSortLocaleAware(true);
2443 return d->language_model_;
2447 void GuiApplication::restoreGuiSession()
2449 if (!lyxrc.load_session)
2452 Session & session = theSession();
2453 LastOpenedSection::LastOpened const & lastopened =
2454 session.lastOpened().getfiles();
2456 validateCurrentView();
2458 FileName active_file;
2459 // do not add to the lastfile list since these files are restored from
2460 // last session, and should be already there (regular files), or should
2461 // not be added at all (help files).
2462 for (size_t i = 0; i < lastopened.size(); ++i) {
2463 FileName const & file_name = lastopened[i].file_name;
2464 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2465 && current_view_->documentBufferView() != 0)) {
2466 boost::crc_32_type crc;
2467 string const & fname = file_name.absFileName();
2468 crc = for_each(fname.begin(), fname.end(), crc);
2469 createView(crc.checksum());
2471 current_view_->loadDocument(file_name, false);
2473 if (lastopened[i].active)
2474 active_file = file_name;
2477 // Restore last active buffer
2478 Buffer * buffer = theBufferList().getBuffer(active_file);
2479 if (buffer && current_view_)
2480 current_view_->setBuffer(buffer);
2482 // clear this list to save a few bytes of RAM
2483 session.lastOpened().clear();
2487 QString const GuiApplication::romanFontName()
2490 font.setStyleHint(QFont::Serif);
2491 font.setFamily("serif");
2493 return QFontInfo(font).family();
2497 QString const GuiApplication::sansFontName()
2500 font.setStyleHint(QFont::SansSerif);
2501 font.setFamily("sans");
2503 return QFontInfo(font).family();
2507 QString const GuiApplication::typewriterFontName()
2510 font.setStyleHint(QFont::TypeWriter);
2511 font.setFamily("monospace");
2513 return QFontInfo(font).family();
2517 void GuiApplication::handleRegularEvents()
2519 ForkedCallsController::handleCompletedProcesses();
2523 bool GuiApplication::event(QEvent * e)
2526 case QEvent::FileOpen: {
2527 // Open a file; this happens only on Mac OS X for now.
2529 // We do this asynchronously because on startup the batch
2530 // commands are not executed here yet and the gui is not ready
2532 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2533 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2534 processFuncRequestAsync(fr);
2539 return QApplication::event(e);
2544 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2547 return QApplication::notify(receiver, event);
2549 catch (ExceptionMessage const & e) {
2551 case ErrorException:
2553 setQuitOnLastWindowClosed(false);
2555 Alert::error(e.title_, e.details_);
2557 // Properly crash in debug mode in order to get a useful backtrace.
2560 // In release mode, try to exit gracefully.
2563 case BufferException: {
2564 if (!current_view_ || !current_view_->documentBufferView())
2566 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2567 docstring details = e.details_ + '\n';
2568 details += buf->emergencyWrite();
2569 theBufferList().release(buf);
2570 details += "\n" + _("The current document was closed.");
2571 Alert::error(e.title_, details);
2574 case WarningException:
2575 Alert::warning(e.title_, e.details_);
2579 catch (exception const & e) {
2580 docstring s = _("LyX has caught an exception, it will now "
2581 "attempt to save all unsaved documents and exit."
2583 s += from_ascii(e.what());
2584 Alert::error(_("Software exception Detected"), s);
2588 docstring s = _("LyX has caught some really weird exception, it will "
2589 "now attempt to save all unsaved documents and exit.");
2590 Alert::error(_("Software exception Detected"), s);
2598 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2600 QColor const & qcol = d->color_cache_.get(col);
2601 if (!qcol.isValid()) {
2607 rgbcol.r = qcol.red();
2608 rgbcol.g = qcol.green();
2609 rgbcol.b = qcol.blue();
2614 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2616 QColor const qcol(lcolor.getX11Name(col).c_str());
2617 if (!qcol.isValid()) {
2623 rgbcol.r = qcol.red();
2624 rgbcol.g = qcol.green();
2625 rgbcol.b = qcol.blue();
2630 string const GuiApplication::hexName(ColorCode col)
2632 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2636 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2638 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2639 d->socket_notifiers_[fd] = sn;
2640 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2644 void GuiApplication::socketDataReceived(int fd)
2646 d->socket_notifiers_[fd]->func_();
2650 void GuiApplication::unregisterSocketCallback(int fd)
2652 d->socket_notifiers_.take(fd)->setEnabled(false);
2656 void GuiApplication::commitData(QSessionManager & sm)
2658 /** The implementation is required to avoid an application exit
2659 ** when session state save is triggered by session manager.
2660 ** The default implementation sends a close event to all
2661 ** visible top level widgets when session managment allows
2663 ** We are changing that to check the state of each buffer in all
2664 ** views and ask the users what to do if buffers are dirty.
2665 ** Furthermore, we save the session state.
2666 ** We do NOT close the views here since the user still can cancel
2667 ** the logout process (see #9277); also, this would hide LyX from
2668 ** an OSes own session handling (application restoration).
2670 #ifdef QT_NO_SESSIONMANAGER
2672 #warning Qt is compiled without session manager
2674 #pragma message("warning: Qt is compiled without session manager")
2678 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2686 void GuiApplication::unregisterView(GuiView * gv)
2688 LAPPERR(d->views_[gv->id()] == gv);
2689 d->views_.remove(gv->id());
2690 if (current_view_ == gv)
2695 bool GuiApplication::closeAllViews()
2697 if (d->views_.empty())
2700 // When a view/window was closed before without quitting LyX, there
2701 // are already entries in the lastOpened list.
2702 theSession().lastOpened().clear();
2704 QList<GuiView *> const views = d->views_.values();
2705 foreach (GuiView * view, views) {
2706 if (!view->closeScheduled())
2715 bool GuiApplication::prepareAllViewsForLogout()
2717 if (d->views_.empty())
2720 QList<GuiView *> const views = d->views_.values();
2721 foreach (GuiView * view, views) {
2722 if (!view->prepareAllBuffersForLogout())
2730 GuiView & GuiApplication::view(int id) const
2732 LAPPERR(d->views_.contains(id));
2733 return *d->views_.value(id);
2737 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2739 QList<GuiView *> const views = d->views_.values();
2740 foreach (GuiView * view, views)
2741 view->hideDialog(name, inset);
2745 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2747 Buffer const * buffer_ = 0;
2748 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2749 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2750 if (Buffer const * ptr = (*it)->updateInset(inset))
2757 bool GuiApplication::searchMenu(FuncRequest const & func,
2758 docstring_list & names) const
2760 return d->menus_.searchMenu(func, names);
2764 // Ensure that a file is read only once (prevents include loops)
2765 static QStringList uifiles;
2766 // store which ui files define Toolbars
2767 static QStringList toolbar_uifiles;
2770 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2781 LexerKeyword uitags[] = {
2782 { "format", ui_format },
2783 { "include", ui_include },
2784 { "menuset", ui_menuset },
2785 { "toolbars", ui_toolbars },
2786 { "toolbarset", ui_toolbarset }
2790 lex.setFile(ui_path);
2792 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2796 if (lyxerr.debugging(Debug::PARSER))
2797 lex.printTable(lyxerr);
2800 // format before introduction of format tag
2801 unsigned int format = 0;
2802 while (lex.isOK()) {
2803 int const status = lex.lex();
2805 // we have to do this check here, outside the switch,
2806 // because otherwise we would start reading include files,
2807 // e.g., if the first tag we hit was an include tag.
2808 if (status == ui_format)
2810 format = lex.getInteger();
2814 // this will trigger unless the first tag we hit is a format
2815 // tag, with the right format.
2816 if (format != LFUN_FORMAT)
2817 return FormatMismatch;
2820 case Lexer::LEX_FEOF:
2825 QString const file = toqstr(lex.getString());
2826 bool const success = readUIFile(file, true);
2828 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2835 d->menus_.read(lex);
2839 d->toolbars_.readToolbars(lex);
2843 d->toolbars_.readToolbarSettings(lex);
2844 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2848 if (!rtrim(lex.getString()).empty())
2849 lex.printError("LyX::ReadUIFile: "
2850 "Unknown menu tag: `$$Token'");
2852 LYXERR0("Error with status: " << status);
2858 return (error ? ReadError : ReadOK);
2862 bool GuiApplication::readUIFile(QString const & name, bool include)
2864 LYXERR(Debug::INIT, "About to read " << name << "...");
2868 ui_path = libFileSearch("ui", name, "inc");
2869 if (ui_path.empty())
2870 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2872 ui_path = libFileSearch("ui", name, "ui");
2875 if (ui_path.empty()) {
2876 static const QString defaultUIFile = "default";
2877 LYXERR(Debug::INIT, "Could not find " << name);
2879 Alert::warning(_("Could not find UI definition file"),
2880 bformat(_("Error while reading the included file\n%1$s\n"
2881 "Please check your installation."), qstring_to_ucs4(name)));
2884 if (name == defaultUIFile) {
2885 LYXERR(Debug::INIT, "Could not find default UI file!!");
2886 Alert::warning(_("Could not find default UI file"),
2887 _("LyX could not find the default UI file!\n"
2888 "Please check your installation."));
2891 Alert::warning(_("Could not find UI definition file"),
2892 bformat(_("Error while reading the configuration file\n%1$s\n"
2893 "Falling back to default.\n"
2894 "Please look under Tools>Preferences>User Interface and\n"
2895 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2896 return readUIFile(defaultUIFile, false);
2899 QString const uifile = toqstr(ui_path.absFileName());
2900 if (uifiles.contains(uifile)) {
2902 // We are reading again the top uifile so reset the safeguard:
2905 d->toolbars_.reset();
2907 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2908 << "Is this an include loop?");
2912 uifiles.push_back(uifile);
2914 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2916 ReturnValues retval = readUIFile(ui_path);
2918 if (retval == FormatMismatch) {
2919 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2920 TempFile tmp("convertXXXXXX.ui");
2921 FileName const tempfile = tmp.name();
2922 bool const success = prefs2prefs(ui_path, tempfile, true);
2924 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2925 " to format " << LFUN_FORMAT << ".");
2927 retval = readUIFile(tempfile);
2931 if (retval != ReadOK) {
2932 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2940 settings.beginGroup("ui_files");
2941 bool touched = false;
2942 for (int i = 0; i != uifiles.size(); ++i) {
2943 QFileInfo fi(uifiles[i]);
2944 QDateTime const date_value = fi.lastModified();
2945 QString const name_key = QString::number(i);
2946 // if an ui file which defines Toolbars has changed,
2947 // we have to reset the settings
2948 if (toolbar_uifiles.contains(uifiles[i])
2949 && (!settings.contains(name_key)
2950 || settings.value(name_key).toString() != uifiles[i]
2951 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2953 settings.setValue(name_key, uifiles[i]);
2954 settings.setValue(name_key + "/date", date_value);
2957 settings.endGroup();
2959 settings.remove("views");
2965 void GuiApplication::onLastWindowClosed()
2967 if (d->global_menubar_)
2968 d->global_menubar_->grabKeyboard();
2972 void GuiApplication::startLongOperation() {
2973 d->key_checker_.start();
2977 bool GuiApplication::longOperationCancelled() {
2978 return d->key_checker_.pressed();
2982 void GuiApplication::stopLongOperation() {
2983 d->key_checker_.stop();
2987 bool GuiApplication::longOperationStarted() {
2988 return d->key_checker_.started();
2992 ////////////////////////////////////////////////////////////////////////
2994 // X11 specific stuff goes here...
2997 bool GuiApplication::x11EventFilter(XEvent * xev)
3002 switch (xev->type) {
3003 case SelectionRequest: {
3004 if (xev->xselectionrequest.selection != XA_PRIMARY)
3006 LYXERR(Debug::SELECTION, "X requested selection.");
3007 BufferView * bv = current_view_->currentBufferView();
3009 docstring const sel = bv->requestSelection();
3011 d->selection_.put(sel);
3015 case SelectionClear: {
3016 if (xev->xselectionclear.selection != XA_PRIMARY)
3018 LYXERR(Debug::SELECTION, "Lost selection.");
3019 BufferView * bv = current_view_->currentBufferView();
3021 bv->clearSelection();
3027 #elif defined(QPA_XCB)
3028 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3029 void * message, long *) Q_DECL_OVERRIDE
3031 if (!current_view_ || eventType != "xcb_generic_event_t")
3034 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3036 switch (ev->response_type) {
3037 case XCB_SELECTION_REQUEST: {
3038 xcb_selection_request_event_t * srev =
3039 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3040 if (srev->selection != XA_PRIMARY)
3042 LYXERR(Debug::SELECTION, "X requested selection.");
3043 BufferView * bv = current_view_->currentBufferView();
3045 docstring const sel = bv->requestSelection();
3047 d->selection_.put(sel);
3051 case XCB_SELECTION_CLEAR: {
3052 xcb_selection_clear_event_t * scev =
3053 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3054 if (scev->selection != XA_PRIMARY)
3056 LYXERR(Debug::SELECTION, "Lost selection.");
3057 BufferView * bv = current_view_->currentBufferView();
3059 bv->clearSelection();
3067 } // namespace frontend
3070 void hideDialogs(std::string const & name, Inset * inset)
3073 frontend::guiApp->hideDialogs(name, inset);
3077 ////////////////////////////////////////////////////////////////////
3081 ////////////////////////////////////////////////////////////////////
3083 frontend::FontLoader & theFontLoader()
3085 LAPPERR(frontend::guiApp);
3086 return frontend::guiApp->fontLoader();
3090 frontend::FontMetrics const & theFontMetrics(Font const & f)
3092 return theFontMetrics(f.fontInfo());
3096 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3098 LAPPERR(frontend::guiApp);
3099 return frontend::guiApp->fontLoader().metrics(f);
3103 ////////////////////////////////////////////////////////////////////
3107 ////////////////////////////////////////////////////////////////////
3109 frontend::Clipboard & theClipboard()
3111 LAPPERR(frontend::guiApp);
3112 return frontend::guiApp->clipboard();
3116 frontend::Selection & theSelection()
3118 LAPPERR(frontend::guiApp);
3119 return frontend::guiApp->selection();
3125 #include "moc_GuiApplication.cpp"