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"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "GuiWorkArea.h"
45 #include "LaTeXPackages.h"
48 #include "LyXAction.h"
50 #include "Paragraph.h"
53 #include "SpellChecker.h"
54 #include "Thesaurus.h"
57 #include "support/convert.h"
58 #include "support/debug.h"
59 #include "support/ExceptionMessage.h"
60 #include "support/FileName.h"
61 #include "support/filetools.h"
62 #include "support/foreach.h"
63 #include "support/ForkedCalls.h"
64 #include "support/gettext.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/lyxalgo.h" // sorted
68 #include "support/Messages.h"
69 #include "support/os.h"
70 #include "support/Package.h"
71 #include "support/PathChanger.h"
72 #include "support/Systemcall.h"
75 #include "support/AppleScript.h"
76 #include "support/linkback/LinkBackProxy.h"
87 #include <QFileOpenEvent>
91 #include <QImageReader>
94 #include <QLibraryInfo>
100 #include <QPixmapCache>
102 #include <QSessionManager>
104 #include <QShowEvent>
105 #include <QSocketNotifier>
106 #include <QSortFilterProxyModel>
107 #include <QStandardItemModel>
108 #include <QTextCodec>
110 #include <QTranslator>
111 #include <QThreadPool>
115 #include <X11/Xatom.h>
116 #include <X11/Xlib.h>
122 #include <QWindowsMime>
130 #include <QMacPasteboardMime>
133 #include "support/bind.h"
134 #include <boost/crc.hpp>
141 using namespace lyx::support;
144 static void initializeResources()
146 static bool initialized = false;
148 Q_INIT_RESOURCE(Resources);
156 frontend::Application * createApplication(int & argc, char * argv[])
159 // prune -geometry argument(s) by shifting
160 // the following ones 2 places down.
161 for (int i = 0 ; i < argc ; ++i) {
162 if (strcmp(argv[i], "-geometry") == 0) {
163 int const remove = (i+1) < argc ? 2 : 1;
165 for (int j = i; j < argc; ++j)
166 argv[j] = argv[j + remove];
171 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
172 // I'd rather do that in the constructor, but I do not think that
173 // the palette is accessible there.
174 guiApp->colorCache().setPalette(guiApp->palette());
182 if (lyxrc.gui_language == "auto") {
183 theLocale = QLocale::system();
185 Language const * l = languages.getLanguage(lyxrc.gui_language);
186 string const code = l ? l->code() : string();
187 theLocale = QLocale(toqstr(code));
189 Messages::guiLanguage(fromqstr(theLocale.name()));
190 QLocale::setDefault(theLocale);
191 setlocale(LC_NUMERIC, "C");
198 /// Return the list of loadable formats.
199 vector<string> loadableImageFormats()
203 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
205 LYXERR(Debug::GRAPHICS,
206 "\nThe image loader can load the following directly:\n");
208 if (qt_formats.empty())
209 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
211 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
213 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
215 string ext = ascii_lowercase((const char *) *it);
226 ////////////////////////////////////////////////////////////////////////
228 // Icon loading support code
230 ////////////////////////////////////////////////////////////////////////
240 bool operator<(PngMap const & lhs, PngMap const & rhs)
242 return lhs.key < rhs.key;
248 CompareKey(QString const & name) : name_(name) {}
249 bool operator()(PngMap const & other) const { return other.key == name_; }
255 // this must be sorted alphabetically
256 // Upper case comes before lower case
257 // Please don't change the formatting, this list is parsed by
258 // development/tools/generate_symbols_images.py.
259 PngMap sorted_png_map[] = {
260 { "Arrownot", "arrownot2"},
261 { "Arrowvert", "arrowvert2"},
262 { "Bowtie", "bowtie2" },
264 { "Bumpeq", "bumpeq2" },
265 { "CIRCLE", "circle3" },
267 { "CheckedBox", "checkedbox2" },
268 { "Circle", "circle2" },
269 { "Colonapprox", "colonapprox2" },
270 { "Coloneq", "coloneq2" },
271 { "Coloneqq", "coloneqq2" },
272 { "Colonsim", "colonsim2" },
274 { "DOWNarrow", "downarrow3" },
275 { "Delta", "delta2" },
276 { "Diamond", "diamond2" },
277 { "Doteq", "doteq2" },
278 { "Downarrow", "downarrow2" },
279 { "Eqcolon", "eqcolon2" },
280 { "Eqqcolon", "eqqcolon2" },
281 { "Gamma", "gamma2" },
283 { "LEFTCIRCLE", "leftcircle3" },
284 { "LEFTarrow", "leftarrow3" },
285 { "LEFTcircle", "leftcircle4" },
287 { "Lambda", "lambda2" },
289 { "Leftarrow", "leftarrow2" },
290 { "Leftcircle", "leftcircle2" },
291 { "Leftrightarrow", "leftrightarrow2" },
292 { "Longarrownot", "longarrownot2"},
293 { "Longleftarrow", "longleftarrow2" },
294 { "Longleftrightarrow", "longleftrightarrow2" },
295 { "Longmapsfrom", "longmapsfrom2"},
296 { "Longmapsto", "longmapsto2"},
297 { "Longrightarrow", "longrightarrow2" },
298 { "Mapsfrom", "mapsfrom2"},
299 { "Mapsfromchar", "mapsfromchar2"},
300 { "Mapsto", "mapsto2"},
301 { "Mapstochar", "mapstochar2"},
302 { "Omega", "omega2" },
307 { "RIGHTCIRCLE", "rightcircle3" },
308 { "RIGHTarrow", "rightarrow3" },
309 { "RIGHTcircle", "rightcircle4" },
311 { "Rightarrow", "rightarrow2" },
312 { "Rightcircle", "rightcircle2" },
313 { "Sigma", "sigma2" },
314 { "Square", "square2" },
315 { "Subset", "subset2" },
316 { "Supset", "supset2" },
317 { "Theta", "theta2" },
318 { "Thorn", "thorn2" },
319 { "UParrow", "uparrow3" },
320 { "Uparrow", "uparrow2" },
321 { "Updownarrow", "updownarrow2" },
322 { "Upsilon", "upsilon2" },
323 { "Vdash", "vdash3" },
328 { "nLeftarrow", "nleftarrow2" },
329 { "nLeftrightarrow", "nleftrightarrow2" },
330 { "nRightarrow", "nrightarrow2" },
331 { "nVDash", "nvdash3" },
332 { "nVdash", "nvdash4" },
333 { "nvDash", "nvdash2" },
334 { "textrm \\AA", "textrm_AA"},
335 { "textrm \\O", "textrm_O"},
336 { "vDash", "vdash2" },
337 { "varDelta", "vardelta2" },
338 { "varGamma", "vargamma2" },
339 { "varLambda", "varlambda2" },
340 { "varOmega", "varomega2" },
341 { "varPhi", "varphi2" },
342 { "varPi", "varpi2" },
343 { "varPsi", "varpsi2" },
344 { "varSigma", "varsigma2" },
345 { "varTheta", "vartheta2" },
346 { "varUpsilon", "varupsilon2" },
347 { "varXi", "varxi2" }
351 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
353 // This list specifies which system's theme icon is related to which lyx
354 // command. It was based on:
355 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
356 // this must be sorted alphabetically
357 // Upper case comes before lower case
358 PngMap sorted_theme_icon_map[] = {
359 { "bookmark-goto 0", "go-jump" },
360 { "buffer-new", "document-new" },
361 { "buffer-print", "document-print" },
362 { "buffer-write", "document-save" },
363 { "buffer-write-as", "document-save-as" },
364 { "buffer-zoom-in", "zoom-in" },
365 { "buffer-zoom-out", "zoom-out" },
366 { "copy", "edit-copy" },
367 { "cut", "edit-cut" },
368 { "depth-decrement", "format-indent-less" },
369 { "depth-increment", "format-indent-more" },
370 { "dialog-show print", "document-print" },
371 { "dialog-show spellchecker", "tools-check-spelling" },
372 { "dialog-show-new-inset graphics", "insert-image" },
373 { "dialog-toggle findreplaceadv", "edit-find-replace" },
374 { "file-open", "document-open" },
375 { "font-bold", "format-text-bold" },
376 { "font-ital", "format-text-italic" },
377 { "font-strikeout", "format-text-strikethrough" },
378 { "font-underline", "format-text-underline" },
379 { "lyx-quit", "application-exit" },
380 { "paste", "edit-paste" },
381 { "redo", "edit-redo" },
382 { "undo", "edit-undo" },
383 { "window-close", "window-close" },
384 { "window-new", "window-new" }
387 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
390 QString findPng(QString const & name)
392 PngMap const * const begin = sorted_png_map;
393 PngMap const * const end = begin + nr_sorted_png_map;
394 LATTEST(sorted(begin, end));
396 PngMap const * const it = find_if(begin, end, CompareKey(name));
400 png_name = it->value;
403 png_name.replace('_', "underscore");
404 png_name.replace(' ', '_');
406 // This way we can have "math-delim { }" on the toolbar.
407 png_name.replace('(', "lparen");
408 png_name.replace(')', "rparen");
409 png_name.replace('[', "lbracket");
410 png_name.replace(']', "rbracket");
411 png_name.replace('{', "lbrace");
412 png_name.replace('}', "rbrace");
413 png_name.replace('|', "bars");
414 png_name.replace(',', "thinspace");
415 png_name.replace(':', "mediumspace");
416 png_name.replace(';', "thickspace");
417 png_name.replace('!', "negthinspace");
420 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
421 << "Looking for math PNG called \"" << png_name << '"');
428 QString themeIconName(QString const & action)
430 PngMap const * const begin = sorted_theme_icon_map;
431 PngMap const * const end = begin + nr_sorted_theme_icon_map;
432 LASSERT(sorted(begin, end), /**/);
434 PngMap const * const it = find_if(begin, end, CompareKey(action));
442 QString iconName(FuncRequest const & f, bool unknown)
444 initializeResources();
448 switch (f.action()) {
449 case LFUN_MATH_INSERT:
450 if (!f.argument().empty()) {
452 name1 = findPng(toqstr(f.argument()).mid(1));
455 case LFUN_MATH_DELIM:
456 case LFUN_MATH_BIGDELIM:
458 name1 = findPng(toqstr(f.argument()));
462 name1 = toqstr(f.argument());
464 case LFUN_COMMAND_ALTERNATIVES: {
465 // use the first of the alternative commands
467 docstring dummy = split(f.argument(), firstcom, ';');
468 name1 = toqstr(firstcom);
469 // FIXME: we should rename the icons to tabular-xxx instead of
470 // "tabular-feature-xxx"
471 name1.replace("inset-modify tabular", "tabular-feature");
472 name1.replace(' ', '_');
475 case LFUN_INSET_MODIFY: {
476 // FIXME: we should rename the icons to tabular-xxx instead of
477 // "tabular-feature-xxx" and generalize this naming to all
478 // insets, not to tabular using ones.
480 string const command = split(to_utf8(f.argument()), inset_name, ' ');
481 if (insetCode(inset_name) == TABULAR_CODE) {
482 name1 = "tabular-feature "+ toqstr(command);
483 name1.replace(' ', '_');
488 name2 = toqstr(lyxaction.getActionName(f.action()));
491 if (!f.argument().empty()) {
492 name1 = name2 + ' ' + toqstr(f.argument());
493 name1.replace(' ', '_');
494 name1.replace('\\', "backslash");
498 QStringList imagedirs;
499 imagedirs << "images/" << "images/ipa/";
500 for (int i = 0; i < imagedirs.size(); ++i) {
501 QString imagedir = imagedirs.at(i) + path;
502 FileName fname = imageLibFileSearch(imagedir, name1, "png");
504 return toqstr(fname.absFileName());
506 fname = imageLibFileSearch(imagedir, name2, "png");
508 return toqstr(fname.absFileName());
511 path = ":/images/" + path;
514 LYXERR0("Directory " << path << " not found in resource!");
518 if (res.exists(name1))
522 if (res.exists(name2))
525 LYXERR(Debug::GUI, "Cannot find icon with filename "
526 << "\"" << name1 << "\""
528 << "\"" << name2 << "\""
530 << lyxaction.getActionName(f.action())
531 << '(' << to_utf8(f.argument()) << ")\"");
534 QString imagedir = "images/";
535 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
537 return toqstr(fname.absFileName());
538 return QString(":/images/unknown.png");
544 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
547 QString imagedir = path;
548 FileName fname = imageLibFileSearch(imagedir, name, ext);
549 QString path1 = toqstr(fname.absFileName());
550 QString path2 = ":/" + path + name + "." + ext;
552 if (pixmap.load(path1)) {
555 else if (pixmap.load(path2)) {
559 LYXERR0("Cannot load pixmap \""
560 << path << name << '.' << ext
561 << "\", please verify resource system!");
566 QIcon getIcon(FuncRequest const & f, bool unknown)
568 #if (QT_VERSION >= 0x040600)
569 if (lyxrc.use_system_theme_icons) {
570 QString action = toqstr(lyxaction.getActionName(f.action()));
571 if (!f.argument().empty())
572 action += " " + toqstr(f.argument());
573 QString const theme_icon = themeIconName(action);
574 if (QIcon::hasThemeIcon(theme_icon))
575 return QIcon::fromTheme(theme_icon);
579 QString icon = iconName(f, unknown);
583 //LYXERR(Debug::GUI, "Found icon: " << icon);
585 if (!pm.load(icon)) {
586 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
594 ////////////////////////////////////////////////////////////////////////
596 // LyX server support code.
598 ////////////////////////////////////////////////////////////////////////
600 class SocketNotifier : public QSocketNotifier
603 /// connect a connection notification from the LyXServerSocket
604 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
605 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
609 /// The callback function
610 Application::SocketCallback func_;
614 ////////////////////////////////////////////////////////////////////////
616 // Mac specific stuff goes here...
618 ////////////////////////////////////////////////////////////////////////
620 class MenuTranslator : public QTranslator
623 MenuTranslator(QObject * parent)
624 : QTranslator(parent)
627 QString translate(const char * /*context*/,
628 const char * sourceText,
629 const char * /*comment*/ = 0) const
631 string const s = sourceText;
632 if (s == N_("About %1") || s == N_("Preferences")
633 || s == N_("Reconfigure") || s == N_("Quit %1"))
640 class GlobalMenuBar : public QMenuBar
644 GlobalMenuBar() : QMenuBar(0) {}
647 bool event(QEvent * e)
649 if (e->type() == QEvent::ShortcutOverride) {
650 // && activeWindow() == 0) {
651 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
653 setKeySymbol(&sym, ke);
654 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
663 // QMacPasteboardMimeGraphics can only be compiled on Mac.
665 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
668 QMacPasteboardMimeGraphics()
669 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
672 QString convertorName() { return "Graphics"; }
674 QString flavorFor(QString const & mime)
676 LYXERR(Debug::ACTION, "flavorFor " << mime);
677 if (mime == pdfMimeType())
678 return QLatin1String("com.adobe.pdf");
682 QString mimeFor(QString flav)
684 LYXERR(Debug::ACTION, "mimeFor " << flav);
685 if (flav == QLatin1String("com.adobe.pdf"))
686 return pdfMimeType();
690 bool canConvert(QString const & mime, QString flav)
692 return mimeFor(flav) == mime;
695 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
699 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
703 QList<QByteArray> convertFromMime(QString const & /*mime*/,
704 QVariant data, QString /*flav*/)
706 QList<QByteArray> ret;
707 ret.append(data.toByteArray());
713 ///////////////////////////////////////////////////////////////
715 // You can find more platform specific stuff at the end of this file...
717 ///////////////////////////////////////////////////////////////
719 ////////////////////////////////////////////////////////////////////////
720 // Windows specific stuff goes here...
723 // QWindowsMimeMetafile can only be compiled on Windows.
725 static FORMATETC cfFromMime(QString const & mimetype)
728 if (mimetype == emfMimeType()) {
729 formatetc.cfFormat = CF_ENHMETAFILE;
730 formatetc.tymed = TYMED_ENHMF;
731 } else if (mimetype == wmfMimeType()) {
732 formatetc.cfFormat = CF_METAFILEPICT;
733 formatetc.tymed = TYMED_MFPICT;
736 formatetc.dwAspect = DVASPECT_CONTENT;
737 formatetc.lindex = -1;
742 class QWindowsMimeMetafile : public QWindowsMime {
744 QWindowsMimeMetafile() {}
746 bool canConvertFromMime(FORMATETC const & formatetc,
747 QMimeData const * mimedata) const
752 bool canConvertToMime(QString const & mimetype,
753 IDataObject * pDataObj) const
755 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
757 FORMATETC formatetc = cfFromMime(mimetype);
758 return pDataObj->QueryGetData(&formatetc) == S_OK;
761 bool convertFromMime(FORMATETC const & formatetc,
762 const QMimeData * mimedata, STGMEDIUM * pmedium) const
767 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
768 QVariant::Type preferredType) const
771 if (!canConvertToMime(mimetype, pDataObj))
774 FORMATETC formatetc = cfFromMime(mimetype);
776 if (pDataObj->GetData(&formatetc, &s) != S_OK)
780 if (s.tymed == TYMED_ENHMF) {
781 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
782 data.resize(dataSize);
783 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
784 (LPBYTE)data.data());
785 } else if (s.tymed == TYMED_MFPICT) {
786 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
787 data.resize(dataSize);
788 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
789 (LPBYTE)data.data());
792 ReleaseStgMedium(&s);
798 QVector<FORMATETC> formatsForMime(QString const & mimetype,
799 QMimeData const * mimedata) const
801 QVector<FORMATETC> formats;
802 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
803 formats += cfFromMime(mimetype);
807 QString mimeForFormat(FORMATETC const & formatetc) const
809 switch (formatetc.cfFormat) {
811 return emfMimeType();
812 case CF_METAFILEPICT:
813 return wmfMimeType();
822 /// Allows to check whether ESC was pressed during a long operation
823 class KeyChecker : public QObject {
828 KeyChecker() : pressed_(false), started_(false) {}
831 QCoreApplication::instance()->installEventFilter(this);
836 QCoreApplication::instance()->removeEventFilter(this);
840 QCoreApplication::processEvents();
843 bool started() const {
846 bool eventFilter(QObject *obj, QEvent *event) {
847 LYXERR(Debug::ACTION, "Event Type: " << event->type());
848 switch (event->type()) {
852 return QObject::eventFilter(obj, event);
854 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
855 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
863 ////////////////////////////////////////////////////////////////////////
864 // GuiApplication::Private definition and implementation.
865 ////////////////////////////////////////////////////////////////////////
867 struct GuiApplication::Private
869 Private(): language_model_(0), meta_fake_bit(NoModifier),
873 /// WMF Mime handler for Windows clipboard.
874 wmf_mime_ = new QWindowsMimeMetafile;
876 initKeySequences(&theTopLevelKeymap());
879 void initKeySequences(KeyMap * kb)
881 keyseq = KeySequence(kb, kb);
882 cancel_meta_seq = KeySequence(kb, kb);
886 QSortFilterProxyModel * language_model_;
888 GuiClipboard clipboard_;
890 GuiSelection selection_;
892 FontLoader font_loader_;
894 ColorCache color_cache_;
896 QTranslator qt_trans_;
898 QHash<int, SocketNotifier *> socket_notifiers_;
902 /// The global instance
905 /// this timer is used for any regular events one wants to
906 /// perform. at present it is used to check if forked processes
908 QTimer general_timer_;
910 /// delayed FuncRequests
911 std::queue<FuncRequest> func_request_queue_;
916 KeySequence cancel_meta_seq;
918 KeyModifier meta_fake_bit;
920 /// Multiple views container.
922 * Warning: This must not be a smart pointer as the destruction of the
923 * object is handled by Qt when the view is closed
924 * \sa Qt::WA_DeleteOnClose attribute.
926 QHash<int, GuiView *> views_;
928 /// Only used on mac.
929 GlobalMenuBar * global_menubar_;
932 /// Linkback mime handler for MacOSX.
933 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
937 /// WMF Mime handler for Windows clipboard.
938 QWindowsMimeMetafile * wmf_mime_;
941 /// Allows to check whether ESC was pressed during a long operation
942 KeyChecker key_checker_;
946 GuiApplication * guiApp;
948 GuiApplication::~GuiApplication()
951 closeAllLinkBackLinks();
957 GuiApplication::GuiApplication(int & argc, char ** argv)
958 : QApplication(argc, argv), current_view_(0),
959 d(new GuiApplication::Private)
961 QString app_name = "LyX";
962 QCoreApplication::setOrganizationName(app_name);
963 QCoreApplication::setOrganizationDomain("lyx.org");
964 QCoreApplication::setApplicationName(lyx_package);
966 qsrand(QDateTime::currentDateTime().toTime_t());
968 // Install translator for GUI elements.
969 installTranslator(&d->qt_trans_);
971 // FIXME: quitOnLastWindowClosed is true by default. We should have a
972 // lyxrc setting for this in order to let the application stay resident.
973 // But then we need some kind of dock icon, at least on Windows.
975 if (lyxrc.quit_on_last_window_closed)
976 setQuitOnLastWindowClosed(false);
979 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
980 // seems to be the default case for applications like LyX.
981 setQuitOnLastWindowClosed(false);
982 // This allows to translate the strings that appear in the LyX menu.
983 /// A translator suitable for the entries in the LyX menu.
984 /// Only needed with Qt/Mac.
985 installTranslator(new MenuTranslator(this));
991 // doubleClickInterval() is 400 ms on X11 which is just too long.
992 // On Windows and Mac OS X, the operating system's value is used.
993 // On Microsoft Windows, calling this function sets the double
994 // click interval for all applications. So we don't!
995 QApplication::setDoubleClickInterval(300);
998 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1000 // needs to be done before reading lyxrc
1002 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1006 // Set the cache to 5120 kilobytes which corresponds to screen size of
1007 // 1280 by 1024 pixels with a color depth of 32 bits.
1008 QPixmapCache::setCacheLimit(5120);
1010 // Initialize RC Fonts
1011 if (lyxrc.roman_font_name.empty())
1012 lyxrc.roman_font_name = fromqstr(romanFontName());
1014 if (lyxrc.sans_font_name.empty())
1015 lyxrc.sans_font_name = fromqstr(sansFontName());
1017 if (lyxrc.typewriter_font_name.empty())
1018 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1020 d->general_timer_.setInterval(500);
1021 connect(&d->general_timer_, SIGNAL(timeout()),
1022 this, SLOT(handleRegularEvents()));
1023 d->general_timer_.start();
1025 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1026 // This is clearly not enough in a time where we use threads for
1027 // document preview and/or export. 20 should be OK.
1028 QThreadPool::globalInstance()->setMaxThreadCount(20);
1032 GuiApplication * theGuiApp()
1034 return dynamic_cast<GuiApplication *>(theApp());
1038 void GuiApplication::clearSession()
1045 docstring Application::iconName(FuncRequest const & f, bool unknown)
1047 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1051 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1055 BufferView * bv = 0;
1056 BufferView * doc_bv = 0;
1058 if (cmd.action() == LFUN_NOACTION) {
1059 status.message(from_utf8(N_("Nothing to do")));
1060 status.setEnabled(false);
1063 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1064 status.setUnknown(true);
1065 status.message(from_utf8(N_("Unknown action")));
1066 status.setEnabled(false);
1069 // Does the GuiApplication know something?
1070 else if (getStatus(cmd, status)) { }
1072 // If we do not have a GuiView, then other functions are disabled
1073 else if (!current_view_)
1074 status.setEnabled(false);
1076 // Does the GuiView know something?
1077 else if (current_view_->getStatus(cmd, status)) { }
1079 // In LyX/Mac, when a dialog is open, the menus of the
1080 // application can still be accessed without giving focus to
1081 // the main window. In this case, we want to disable the menu
1082 // entries that are buffer or view-related.
1083 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1085 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1086 status.setEnabled(false);
1089 // If we do not have a BufferView, then other functions are disabled
1090 else if (!(bv = current_view_->currentBufferView()))
1091 status.setEnabled(false);
1093 // Does the current BufferView know something?
1094 else if (bv->getStatus(cmd, status)) { }
1096 // Does the current Buffer know something?
1097 else if (bv->buffer().getStatus(cmd, status)) { }
1099 // If we do not have a document BufferView, different from the
1100 // current BufferView, then other functions are disabled
1101 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1102 status.setEnabled(false);
1104 // Does the document Buffer know something?
1105 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1108 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1109 status.message(from_utf8(N_("Command not handled")));
1110 status.setEnabled(false);
1113 // the default error message if we disable the command
1114 if (!status.enabled() && status.message().empty())
1115 status.message(from_utf8(N_("Command disabled")));
1121 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1123 // I would really like to avoid having this switch and rather try to
1124 // encode this in the function itself.
1125 // -- And I'd rather let an inset decide which LFUNs it is willing
1126 // to handle (Andre')
1128 switch (cmd.action()) {
1130 // This could be used for the no-GUI version. The GUI version is handled in
1131 // GuiView::getStatus(). See above.
1133 case LFUN_BUFFER_WRITE:
1134 case LFUN_BUFFER_WRITE_AS: {
1135 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1136 enable = b && (b->isUnnamed() || !b->isClean());
1141 case LFUN_BOOKMARK_GOTO: {
1142 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1143 enable = theSession().bookmarks().isValid(num);
1147 case LFUN_BOOKMARK_CLEAR:
1148 enable = theSession().bookmarks().hasValid();
1151 // this one is difficult to get right. As a half-baked
1152 // solution, we consider only the first action of the sequence
1153 case LFUN_COMMAND_SEQUENCE: {
1154 // argument contains ';'-terminated commands
1155 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1156 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1157 func.setOrigin(cmd.origin());
1158 flag = getStatus(func);
1162 // we want to check if at least one of these is enabled
1163 case LFUN_COMMAND_ALTERNATIVES: {
1164 // argument contains ';'-terminated commands
1165 string arg = to_utf8(cmd.argument());
1166 while (!arg.empty()) {
1168 arg = split(arg, first, ';');
1169 FuncRequest func(lyxaction.lookupFunc(first));
1170 func.setOrigin(cmd.origin());
1171 flag = getStatus(func);
1172 // if this one is enabled, the whole thing is
1181 string name = to_utf8(cmd.argument());
1182 if (theTopLevelCmdDef().lock(name, func)) {
1183 func.setOrigin(cmd.origin());
1184 flag = getStatus(func);
1185 theTopLevelCmdDef().release(name);
1187 // catch recursion or unknown command
1188 // definition. all operations until the
1189 // recursion or unknown command definition
1190 // occurs are performed, so set the state to
1197 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1199 case LFUN_PREFERENCES_SAVE:
1200 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1201 case LFUN_DEBUG_LEVEL_SET:
1202 // these are handled in our dispatch()
1205 case LFUN_WINDOW_CLOSE:
1206 enable = d->views_.size() > 0;
1209 case LFUN_BUFFER_NEW:
1210 case LFUN_BUFFER_NEW_TEMPLATE:
1211 case LFUN_FILE_OPEN:
1212 case LFUN_HELP_OPEN:
1213 case LFUN_SCREEN_FONT_UPDATE:
1214 case LFUN_SET_COLOR:
1215 case LFUN_WINDOW_NEW:
1217 case LFUN_LYXRC_APPLY:
1218 case LFUN_COMMAND_PREFIX:
1220 case LFUN_META_PREFIX:
1221 case LFUN_RECONFIGURE:
1222 case LFUN_SERVER_GET_FILENAME:
1223 case LFUN_SERVER_NOTIFY:
1227 case LFUN_BUFFER_FORALL: {
1228 if (theBufferList().empty()) {
1229 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1230 flag.setEnabled(false);
1234 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1235 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1236 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1237 flag.setEnabled(false);
1248 flag.setEnabled(false);
1252 /// make a post-dispatch status message
1253 static docstring makeDispatchMessage(docstring const & msg,
1254 FuncRequest const & cmd)
1256 const bool verbose = (cmd.origin() == FuncRequest::MENU
1257 || cmd.origin() == FuncRequest::TOOLBAR
1258 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1260 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1261 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1265 docstring dispatch_msg = msg;
1266 if (!dispatch_msg.empty())
1267 dispatch_msg += ' ';
1269 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1271 bool argsadded = false;
1273 if (!cmd.argument().empty()) {
1274 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1275 comname += ' ' + cmd.argument();
1279 docstring const shortcuts = theTopLevelKeymap().
1280 printBindings(cmd, KeySequence::ForGui);
1282 if (!shortcuts.empty())
1283 comname += ": " + shortcuts;
1284 else if (!argsadded && !cmd.argument().empty())
1285 comname += ' ' + cmd.argument();
1287 if (!comname.empty()) {
1288 comname = rtrim(comname);
1289 dispatch_msg += '(' + rtrim(comname) + ')';
1291 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1292 return dispatch_msg;
1296 void GuiApplication::dispatch(FuncRequest const & cmd)
1298 Buffer * buffer = 0;
1299 if (current_view_ && current_view_->currentBufferView()) {
1300 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1301 buffer = ¤t_view_->currentBufferView()->buffer();
1303 buffer->undo().beginUndoGroup();
1307 // redraw the screen at the end (first of the two drawing steps).
1308 // This is done unless explicitly requested otherwise
1309 dr.screenUpdate(Update::FitCursor);
1311 updateCurrentView(cmd, dr);
1313 // the buffer may have been closed by one action
1314 if (theBufferList().isLoaded(buffer))
1315 buffer->undo().endUndoGroup();
1319 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1324 BufferView * bv = current_view_->currentBufferView();
1326 if (dr.needBufferUpdate()) {
1327 bv->cursor().clearBufferUpdate();
1328 bv->buffer().updateBuffer();
1330 // BufferView::update() updates the ViewMetricsInfo and
1331 // also initializes the position cache for all insets in
1332 // (at least partially) visible top-level paragraphs.
1333 // We will redraw the screen only if needed.
1334 bv->processUpdateFlags(dr.screenUpdate());
1336 // Do we have a selection?
1337 theSelection().haveSelection(bv->cursor().selection());
1340 current_view_->restartCursor();
1342 if (dr.needMessageUpdate()) {
1343 // Some messages may already be translated, so we cannot use _()
1344 current_view_->message(makeDispatchMessage(
1345 translateIfPossible(dr.message()), cmd));
1350 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1351 bool switchToBuffer)
1353 if (!theSession().bookmarks().isValid(idx))
1355 BookmarksSection::Bookmark const & bm =
1356 theSession().bookmarks().bookmark(idx);
1357 LASSERT(!bm.filename.empty(), return);
1358 string const file = bm.filename.absFileName();
1359 // if the file is not opened, open it.
1360 if (!theBufferList().exists(bm.filename)) {
1362 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1366 // open may fail, so we need to test it again
1367 if (!theBufferList().exists(bm.filename))
1370 // bm can be changed when saving
1371 BookmarksSection::Bookmark tmp = bm;
1373 // Special case idx == 0 used for back-from-back jump navigation
1375 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1377 // if the current buffer is not that one, switch to it.
1378 BufferView * doc_bv = current_view_ ?
1379 current_view_->documentBufferView() : 0;
1380 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1381 if (switchToBuffer) {
1382 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1385 doc_bv = current_view_->documentBufferView();
1390 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1391 if (!doc_bv->moveToPosition(
1392 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1399 // Cursor jump succeeded!
1400 Cursor const & cur = doc_bv->cursor();
1401 pit_type new_pit = cur.pit();
1402 pos_type new_pos = cur.pos();
1403 int new_id = cur.paragraph().id();
1405 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1406 // see http://www.lyx.org/trac/ticket/3092
1407 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1408 || bm.top_id != new_id) {
1409 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1410 new_pit, new_pos, new_id);
1414 // This function runs "configure" and then rereads lyx.defaults to
1415 // reconfigure the automatic settings.
1416 void GuiApplication::reconfigure(string const & option)
1418 // emit message signal.
1420 current_view_->message(_("Running configure..."));
1422 // Run configure in user lyx directory
1423 PathChanger p(package().user_support());
1424 string configure_command = package().configure_command();
1425 configure_command += option;
1427 int const ret = one.startscript(Systemcall::Wait, configure_command);
1429 // emit message signal.
1431 current_view_->message(_("Reloading configuration..."));
1432 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1433 // Re-read packages.lst
1434 LaTeXPackages::getAvailable();
1437 Alert::information(_("System reconfiguration failed"),
1438 _("The system reconfiguration has failed.\n"
1439 "Default textclass is used but LyX may\n"
1440 "not be able to work properly.\n"
1441 "Please reconfigure again if needed."));
1443 Alert::information(_("System reconfigured"),
1444 _("The system has been reconfigured.\n"
1445 "You need to restart LyX to make use of any\n"
1446 "updated document class specifications."));
1449 void GuiApplication::validateCurrentView()
1451 if (!d->views_.empty() && !current_view_) {
1452 // currently at least one view exists but no view has the focus.
1453 // choose the last view to make it current.
1454 // a view without any open document is preferred.
1455 GuiView * candidate = 0;
1456 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1457 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1458 for (; it != end; ++it) {
1460 if (!candidate->documentBufferView())
1463 setCurrentView(candidate);
1467 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1469 string const argument = to_utf8(cmd.argument());
1470 FuncCode const action = cmd.action();
1472 LYXERR(Debug::ACTION, "cmd: " << cmd);
1474 // we have not done anything wrong yet.
1477 FuncStatus const flag = getStatus(cmd);
1478 if (!flag.enabled()) {
1479 // We cannot use this function here
1480 LYXERR(Debug::ACTION, "action "
1481 << lyxaction.getActionName(action)
1482 << " [" << action << "] is disabled at this location");
1483 dr.setMessage(flag.message());
1485 dr.dispatched(false);
1486 dr.screenUpdate(Update::None);
1487 dr.clearBufferUpdate();
1491 if (cmd.origin() == FuncRequest::LYXSERVER) {
1492 if (current_view_ && current_view_->currentBufferView())
1493 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1494 // we will also need to redraw the screen at the end
1495 dr.screenUpdate(Update::FitCursor);
1498 // Assumes that the action will be dispatched.
1499 dr.dispatched(true);
1501 switch (cmd.action()) {
1503 case LFUN_WINDOW_NEW:
1504 createView(toqstr(cmd.argument()));
1507 case LFUN_WINDOW_CLOSE:
1508 // update bookmark pit of the current buffer before window close
1509 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1510 gotoBookmark(i+1, false, false);
1511 // clear the last opened list, because
1512 // maybe this will end the session
1513 theSession().lastOpened().clear();
1514 // check for valid current_view_
1515 validateCurrentView();
1517 current_view_->closeScheduled();
1521 // quitting is triggered by the gui code
1522 // (leaving the event loop).
1524 current_view_->message(from_utf8(N_("Exiting.")));
1525 if (closeAllViews())
1529 case LFUN_SCREEN_FONT_UPDATE: {
1530 // handle the screen font changes.
1531 d->font_loader_.update();
1532 // Backup current_view_
1533 GuiView * view = current_view_;
1534 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1535 // to skip the refresh.
1537 theBufferList().changed(false);
1538 // Restore current_view_
1539 current_view_ = view;
1543 case LFUN_BUFFER_NEW:
1544 validateCurrentView();
1545 if (d->views_.empty()
1546 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1547 createView(QString(), false); // keep hidden
1548 current_view_->newDocument(to_utf8(cmd.argument()), false);
1549 current_view_->show();
1550 setActiveWindow(current_view_);
1552 current_view_->newDocument(to_utf8(cmd.argument()), false);
1556 case LFUN_BUFFER_NEW_TEMPLATE:
1557 validateCurrentView();
1558 if (d->views_.empty()
1559 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1561 current_view_->newDocument(to_utf8(cmd.argument()), true);
1562 if (!current_view_->documentBufferView())
1563 current_view_->close();
1565 current_view_->newDocument(to_utf8(cmd.argument()), true);
1569 case LFUN_FILE_OPEN: {
1570 validateCurrentView();
1571 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1572 string const fname = to_utf8(cmd.argument());
1573 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1574 && current_view_->documentBufferView() != 0)) {
1575 // We want the ui session to be saved per document and not per
1576 // window number. The filename crc is a good enough identifier.
1577 boost::crc_32_type crc;
1578 crc = for_each(fname.begin(), fname.end(), crc);
1579 createView(crc.checksum());
1580 current_view_->openDocument(fname);
1581 if (current_view_ && !current_view_->documentBufferView())
1582 current_view_->close();
1584 current_view_->openDocument(fname);
1588 case LFUN_HELP_OPEN: {
1589 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1590 if (current_view_ == 0)
1592 string const arg = to_utf8(cmd.argument());
1594 current_view_->message(_("Missing argument"));
1597 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1599 fname = i18nLibFileSearch("examples", arg, "lyx");
1601 if (fname.empty()) {
1602 lyxerr << "LyX: unable to find documentation file `"
1603 << arg << "'. Bad installation?" << endl;
1606 current_view_->message(bformat(_("Opening help file %1$s..."),
1607 makeDisplayPath(fname.absFileName())));
1608 Buffer * buf = current_view_->loadDocument(fname, false);
1610 #ifndef DEVEL_VERSION
1612 buf->setReadonly(true);
1619 case LFUN_SET_COLOR: {
1621 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1622 if (lyx_name.empty() || x11_name.empty()) {
1624 current_view_->message(
1625 _("Syntax: set-color <lyx_name> <x11_name>"));
1630 // FIXME: The graphics cache no longer has a changeDisplay method.
1631 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1632 bool const graphicsbg_changed =
1633 lyx_name == graphicsbg && x11_name != graphicsbg;
1634 if (graphicsbg_changed)
1635 graphics::GCache::get().changeDisplay(true);
1638 if (!lcolor.setColor(lyx_name, x11_name)) {
1640 current_view_->message(
1641 bformat(_("Set-color \"%1$s\" failed "
1642 "- color is undefined or "
1643 "may not be redefined"),
1644 from_utf8(lyx_name)));
1647 // Make sure we don't keep old colors in cache.
1648 d->color_cache_.clear();
1652 case LFUN_LYXRC_APPLY: {
1653 // reset active key sequences, since the bindings
1654 // are updated (bug 6064)
1656 LyXRC const lyxrc_orig = lyxrc;
1658 istringstream ss(to_utf8(cmd.argument()));
1659 bool const success = lyxrc.read(ss);
1662 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1663 << "Unable to read lyxrc data"
1668 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1674 case LFUN_COMMAND_PREFIX:
1675 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1680 d->meta_fake_bit = NoModifier;
1681 GuiView * gv = currentView();
1682 if (gv && gv->currentBufferView())
1683 // cancel any selection
1684 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1685 dr.setMessage(from_ascii(N_("Cancel")));
1688 case LFUN_META_PREFIX:
1689 d->meta_fake_bit = AltModifier;
1690 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1693 // --- Menus -----------------------------------------------
1694 case LFUN_RECONFIGURE:
1695 // argument is any additional parameter to the configure.py command
1696 reconfigure(to_utf8(cmd.argument()));
1699 // --- lyxserver commands ----------------------------
1700 case LFUN_SERVER_GET_FILENAME: {
1701 if (current_view_ && current_view_->documentBufferView()) {
1702 docstring const fname = from_utf8(
1703 current_view_->documentBufferView()->buffer().absFileName());
1704 dr.setMessage(fname);
1705 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1707 dr.setMessage(docstring());
1708 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1713 case LFUN_SERVER_NOTIFY: {
1714 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1715 dr.setMessage(dispatch_buffer);
1716 theServer().notifyClient(to_utf8(dispatch_buffer));
1720 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1721 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1727 string rest = split(argument, countstr, ' ');
1728 istringstream is(countstr);
1731 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1732 for (int i = 0; i < count; ++i)
1733 dispatch(lyxaction.lookupFunc(rest));
1737 case LFUN_COMMAND_SEQUENCE: {
1738 // argument contains ';'-terminated commands
1739 string arg = argument;
1740 // FIXME: this LFUN should also work without any view.
1741 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1742 ? &(current_view_->documentBufferView()->buffer()) : 0;
1744 buffer->undo().beginUndoGroup();
1745 while (!arg.empty()) {
1747 arg = split(arg, first, ';');
1748 FuncRequest func(lyxaction.lookupFunc(first));
1749 func.setOrigin(cmd.origin());
1752 // the buffer may have been closed by one action
1753 if (theBufferList().isLoaded(buffer))
1754 buffer->undo().endUndoGroup();
1758 case LFUN_BUFFER_FORALL: {
1759 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1761 map<Buffer *, GuiView *> views_lVisible;
1762 map<GuiView *, Buffer *> activeBuffers;
1764 QList<GuiView *> allViews = d->views_.values();
1766 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1767 // and on which buffer is active in each view.
1768 Buffer * const last = theBufferList().last();
1769 foreach (GuiView * view, allViews) {
1770 // all of the buffers might be locally hidden. That is, there is no active buffer.
1771 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1772 activeBuffers[view] = 0;
1774 activeBuffers[view] = &view->currentBufferView()->buffer();
1776 // find out if each is locally visible or locally hidden.
1777 // we don't use a for loop as the buffer list cycles.
1778 Buffer * b = theBufferList().first();
1780 bool const locallyVisible = view && view->workArea(*b);
1781 if (locallyVisible) {
1782 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1783 // only need to overwrite/add if we don't already know a buffer is globally
1784 // visible or we do know but we would prefer to dispatch LFUN from the
1785 // current view because of cursor position issues.
1786 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1787 views_lVisible[b] = view;
1791 b = theBufferList().next(b);
1795 GuiView * const homeView = currentView();
1796 Buffer * b = theBufferList().first();
1797 Buffer * nextBuf = 0;
1798 int numProcessed = 0;
1801 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1803 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1805 // first change to a view where b is locally visible, preferably current_view_.
1806 GuiView * const vLv = views_lVisible[b];
1808 lyx::dispatch(funcToRun);
1816 // put things back to how they were (if possible).
1817 foreach (GuiView * view, allViews) {
1818 Buffer * originalBuf = activeBuffers[view];
1819 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1820 if (theBufferList().isLoaded(originalBuf))
1821 view->setBuffer(originalBuf);
1823 homeView->setFocus();
1825 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1829 case LFUN_COMMAND_ALTERNATIVES: {
1830 // argument contains ';'-terminated commands
1831 string arg = argument;
1832 while (!arg.empty()) {
1834 arg = split(arg, first, ';');
1835 FuncRequest func(lyxaction.lookupFunc(first));
1836 func.setOrigin(cmd.origin());
1837 FuncStatus const stat = getStatus(func);
1838 if (stat.enabled()) {
1848 if (theTopLevelCmdDef().lock(argument, func)) {
1849 func.setOrigin(cmd.origin());
1851 theTopLevelCmdDef().release(argument);
1853 if (func.action() == LFUN_UNKNOWN_ACTION) {
1854 // unknown command definition
1855 lyxerr << "Warning: unknown command definition `"
1859 // recursion detected
1860 lyxerr << "Warning: Recursion in the command definition `"
1861 << argument << "' detected"
1868 case LFUN_PREFERENCES_SAVE:
1869 lyxrc.write(support::makeAbsPath("preferences",
1870 package().user_support().absFileName()), false);
1873 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1874 string const fname = addName(addPath(package().user_support().absFileName(),
1875 "templates/"), "defaults.lyx");
1876 Buffer defaults(fname);
1878 istringstream ss(argument);
1881 int const unknown_tokens = defaults.readHeader(lex);
1883 if (unknown_tokens != 0) {
1884 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1885 << unknown_tokens << " unknown token"
1886 << (unknown_tokens == 1 ? "" : "s")
1890 if (defaults.writeFile(FileName(defaults.absFileName())))
1891 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1892 makeDisplayPath(fname)));
1895 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1900 case LFUN_BOOKMARK_GOTO:
1901 // go to bookmark, open unopened file and switch to buffer if necessary
1902 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1903 dr.screenUpdate(Update::Force | Update::FitCursor);
1906 case LFUN_BOOKMARK_CLEAR:
1907 theSession().bookmarks().clear();
1910 case LFUN_DEBUG_LEVEL_SET:
1911 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1915 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1918 current_view_->dispatch(cmd, dr);
1922 if (cmd.origin() == FuncRequest::LYXSERVER)
1923 updateCurrentView(cmd, dr);
1927 docstring GuiApplication::viewStatusMessage()
1929 // When meta-fake key is pressed, show the key sequence so far + "M-".
1930 if (d->meta_fake_bit != NoModifier)
1931 return d->keyseq.print(KeySequence::ForGui) + "M-";
1933 // Else, when a non-complete key sequence is pressed,
1934 // show the available options.
1935 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1936 return d->keyseq.printOptions(true);
1942 void GuiApplication::handleKeyFunc(FuncCode action)
1946 if (d->keyseq.length())
1948 GuiView * gv = currentView();
1949 LASSERT(gv && gv->currentBufferView(), return);
1950 BufferView * bv = gv->currentBufferView();
1951 bv->getIntl().getTransManager().deadkey(
1952 c, get_accent(action).accent, bv->cursor().innerText(),
1954 // Need to clear, in case the minibuffer calls these
1957 // copied verbatim from do_accent_char
1958 bv->cursor().resetAnchor();
1962 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1964 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1966 // Do nothing if we have nothing (JMarc)
1967 if (!keysym.isOK()) {
1968 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1970 current_view_->restartCursor();
1974 if (keysym.isModifier()) {
1976 current_view_->restartCursor();
1980 char_type encoded_last_key = keysym.getUCSEncoded();
1982 // Do a one-deep top-level lookup for
1983 // cancel and meta-fake keys. RVDK_PATCH_5
1984 d->cancel_meta_seq.reset();
1986 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1987 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1989 // When not cancel or meta-fake, do the normal lookup.
1990 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1991 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1992 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1993 // remove Caps Lock and Mod2 as a modifiers
1994 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1995 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1998 // Dont remove this unless you know what you are doing.
1999 d->meta_fake_bit = NoModifier;
2001 // Can this happen now ?
2002 if (func.action() == LFUN_NOACTION)
2003 func = FuncRequest(LFUN_COMMAND_PREFIX);
2005 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2006 << d->keyseq.print(KeySequence::Portable) << ']');
2008 // already here we know if it any point in going further
2009 // why not return already here if action == -1 and
2010 // num_bytes == 0? (Lgb)
2012 if (d->keyseq.length() > 1 && current_view_)
2013 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2016 // Maybe user can only reach the key via holding down shift.
2017 // Let's see. But only if shift is the only modifier
2018 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2019 LYXERR(Debug::KEY, "Trying without shift");
2020 func = d->keyseq.addkey(keysym, NoModifier);
2021 LYXERR(Debug::KEY, "Action now " << func.action());
2024 if (func.action() == LFUN_UNKNOWN_ACTION) {
2025 // Hmm, we didn't match any of the keysequences. See
2026 // if it's normal insertable text not already covered
2028 if (keysym.isText() && d->keyseq.length() == 1) {
2029 LYXERR(Debug::KEY, "isText() is true, inserting.");
2030 func = FuncRequest(LFUN_SELF_INSERT,
2031 FuncRequest::KEYBOARD);
2033 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2034 if (current_view_) {
2035 current_view_->message(_("Unknown function."));
2036 current_view_->restartCursor();
2042 if (func.action() == LFUN_SELF_INSERT) {
2043 if (encoded_last_key != 0) {
2044 docstring const arg(1, encoded_last_key);
2045 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2046 FuncRequest::KEYBOARD));
2047 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2050 processFuncRequest(func);
2054 void GuiApplication::processFuncRequest(FuncRequest const & func)
2056 lyx::dispatch(func);
2060 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2062 addToFuncRequestQueue(func);
2063 processFuncRequestQueueAsync();
2067 void GuiApplication::processFuncRequestQueue()
2069 while (!d->func_request_queue_.empty()) {
2070 processFuncRequest(d->func_request_queue_.front());
2071 d->func_request_queue_.pop();
2076 void GuiApplication::processFuncRequestQueueAsync()
2078 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2082 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2084 d->func_request_queue_.push(func);
2088 void GuiApplication::resetGui()
2090 // Set the language defined by the user.
2094 if (!readUIFile(toqstr(lyxrc.ui_file)))
2095 // Gives some error box here.
2098 if (d->global_menubar_)
2099 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2101 QHash<int, GuiView *>::iterator it;
2102 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2105 gv->setLayoutDirection(layoutDirection());
2109 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2113 void GuiApplication::createView(int view_id)
2115 createView(QString(), true, view_id);
2119 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2122 // release the keyboard which might have been grabed by the global
2123 // menubar on Mac to catch shortcuts even without any GuiView.
2124 if (d->global_menubar_)
2125 d->global_menubar_->releaseKeyboard();
2129 while (d->views_.find(id) != d->views_.end())
2132 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2133 GuiView * view = new GuiView(id);
2135 d->views_[id] = view;
2139 setActiveWindow(view);
2142 if (!geometry_arg.isEmpty()) {
2146 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2147 re.indexIn(geometry_arg);
2148 w = re.cap(1).toInt();
2149 h = re.cap(2).toInt();
2150 x = re.cap(3).toInt();
2151 y = re.cap(4).toInt();
2152 view->setGeometry(x, y, w, h);
2159 Clipboard & GuiApplication::clipboard()
2161 return d->clipboard_;
2165 Selection & GuiApplication::selection()
2167 return d->selection_;
2171 FontLoader & GuiApplication::fontLoader()
2173 return d->font_loader_;
2177 Toolbars const & GuiApplication::toolbars() const
2179 return d->toolbars_;
2183 Toolbars & GuiApplication::toolbars()
2185 return d->toolbars_;
2189 Menus const & GuiApplication::menus() const
2195 Menus & GuiApplication::menus()
2201 QList<int> GuiApplication::viewIds() const
2203 return d->views_.keys();
2207 ColorCache & GuiApplication::colorCache()
2209 return d->color_cache_;
2213 int GuiApplication::exec()
2215 // asynchronously handle batch commands. This event will be in
2216 // the event queue in front of other asynchronous events. Hence,
2217 // we can assume in the latter that the gui is setup already.
2218 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2220 return QApplication::exec();
2224 void GuiApplication::exit(int status)
2226 QApplication::exit(status);
2230 void GuiApplication::setGuiLanguage()
2234 // install translation file for Qt built-in dialogs
2235 QString const language_name = QString("qt_") + theLocale.name();
2236 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2237 // Short-named translator can be loaded from a long name, but not the
2238 // opposite. Therefore, long name should be used without truncation.
2239 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2240 if (!d->qt_trans_.load(language_name,
2241 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2242 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2245 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2249 switch (theLocale.language()) {
2250 case QLocale::Arabic :
2251 case QLocale::Hebrew :
2252 case QLocale::Persian :
2253 case QLocale::Urdu :
2254 setLayoutDirection(Qt::RightToLeft);
2257 setLayoutDirection(Qt::LeftToRight);
2262 void GuiApplication::execBatchCommands()
2267 if (!readUIFile(toqstr(lyxrc.ui_file)))
2268 // Gives some error box here.
2272 #if QT_VERSION > 0x040600
2273 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2275 // Create the global default menubar which is shown for the dialogs
2276 // and if no GuiView is visible.
2277 // This must be done after the session was recovered to know the "last files".
2278 d->global_menubar_ = new GlobalMenuBar;
2279 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2282 lyx::execBatchCommands();
2286 QAbstractItemModel * GuiApplication::languageModel()
2288 if (d->language_model_)
2289 return d->language_model_;
2291 QStandardItemModel * lang_model = new QStandardItemModel(this);
2292 lang_model->insertColumns(0, 3);
2294 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2295 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2296 Languages::const_iterator it = lyx::languages.begin();
2297 Languages::const_iterator end = lyx::languages.end();
2298 for (; it != end; ++it) {
2299 current_row = lang_model->rowCount();
2300 lang_model->insertRows(current_row, 1);
2301 QModelIndex pl_item = lang_model->index(current_row, 0);
2302 QModelIndex sp_item = lang_model->index(current_row, 1);
2303 QModelIndex th_item = lang_model->index(current_row, 2);
2304 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2305 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2306 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2307 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2308 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2309 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2310 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2311 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2312 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2313 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2315 d->language_model_ = new QSortFilterProxyModel(this);
2316 d->language_model_->setSourceModel(lang_model);
2317 d->language_model_->setSortLocaleAware(true);
2318 return d->language_model_;
2322 void GuiApplication::restoreGuiSession()
2324 if (!lyxrc.load_session)
2327 Session & session = theSession();
2328 LastOpenedSection::LastOpened const & lastopened =
2329 session.lastOpened().getfiles();
2331 validateCurrentView();
2333 FileName active_file;
2334 // do not add to the lastfile list since these files are restored from
2335 // last session, and should be already there (regular files), or should
2336 // not be added at all (help files).
2337 for (size_t i = 0; i < lastopened.size(); ++i) {
2338 FileName const & file_name = lastopened[i].file_name;
2339 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2340 && current_view_->documentBufferView() != 0)) {
2341 boost::crc_32_type crc;
2342 string const & fname = file_name.absFileName();
2343 crc = for_each(fname.begin(), fname.end(), crc);
2344 createView(crc.checksum());
2346 current_view_->loadDocument(file_name, false);
2348 if (lastopened[i].active)
2349 active_file = file_name;
2352 // Restore last active buffer
2353 Buffer * buffer = theBufferList().getBuffer(active_file);
2354 if (buffer && current_view_)
2355 current_view_->setBuffer(buffer);
2357 // clear this list to save a few bytes of RAM
2358 session.lastOpened().clear();
2362 QString const GuiApplication::romanFontName()
2365 font.setKerning(false);
2366 font.setStyleHint(QFont::Serif);
2367 font.setFamily("serif");
2369 return QFontInfo(font).family();
2373 QString const GuiApplication::sansFontName()
2376 font.setKerning(false);
2377 font.setStyleHint(QFont::SansSerif);
2378 font.setFamily("sans");
2380 return QFontInfo(font).family();
2384 QString const GuiApplication::typewriterFontName()
2387 font.setKerning(false);
2388 font.setStyleHint(QFont::TypeWriter);
2389 font.setFamily("monospace");
2391 return QFontInfo(font).family();
2395 void GuiApplication::handleRegularEvents()
2397 ForkedCallsController::handleCompletedProcesses();
2401 bool GuiApplication::event(QEvent * e)
2404 case QEvent::FileOpen: {
2405 // Open a file; this happens only on Mac OS X for now.
2407 // We do this asynchronously because on startup the batch
2408 // commands are not executed here yet and the gui is not ready
2410 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2411 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2412 processFuncRequestAsync(fr);
2417 return QApplication::event(e);
2422 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2425 return QApplication::notify(receiver, event);
2427 catch (ExceptionMessage const & e) {
2429 case ErrorException:
2431 setQuitOnLastWindowClosed(false);
2433 Alert::error(e.title_, e.details_);
2435 // Properly crash in debug mode in order to get a useful backtrace.
2438 // In release mode, try to exit gracefully.
2441 case BufferException: {
2442 if (!current_view_ || !current_view_->documentBufferView())
2444 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2445 docstring details = e.details_ + '\n';
2446 details += buf->emergencyWrite();
2447 theBufferList().release(buf);
2448 details += "\n" + _("The current document was closed.");
2449 Alert::error(e.title_, details);
2452 case WarningException:
2453 Alert::warning(e.title_, e.details_);
2457 catch (exception const & e) {
2458 docstring s = _("LyX has caught an exception, it will now "
2459 "attempt to save all unsaved documents and exit."
2461 s += from_ascii(e.what());
2462 Alert::error(_("Software exception Detected"), s);
2466 docstring s = _("LyX has caught some really weird exception, it will "
2467 "now attempt to save all unsaved documents and exit.");
2468 Alert::error(_("Software exception Detected"), s);
2476 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2478 QColor const & qcol = d->color_cache_.get(col);
2479 if (!qcol.isValid()) {
2485 rgbcol.r = qcol.red();
2486 rgbcol.g = qcol.green();
2487 rgbcol.b = qcol.blue();
2492 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2494 QColor const qcol(lcolor.getX11Name(col).c_str());
2495 if (!qcol.isValid()) {
2501 rgbcol.r = qcol.red();
2502 rgbcol.g = qcol.green();
2503 rgbcol.b = qcol.blue();
2508 string const GuiApplication::hexName(ColorCode col)
2510 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2514 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2516 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2517 d->socket_notifiers_[fd] = sn;
2518 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2522 void GuiApplication::socketDataReceived(int fd)
2524 d->socket_notifiers_[fd]->func_();
2528 void GuiApplication::unregisterSocketCallback(int fd)
2530 d->socket_notifiers_.take(fd)->setEnabled(false);
2534 void GuiApplication::commitData(QSessionManager & sm)
2536 /// The implementation is required to avoid an application exit
2537 /// when session state save is triggered by session manager.
2538 /// The default implementation sends a close event to all
2539 /// visible top level widgets when session managment allows
2541 /// We are changing that to close all wiew one by one.
2542 /// FIXME: verify if the default implementation is enough now.
2543 #ifdef QT_NO_SESSIONMANAGER
2545 #warning Qt is compiled without session manager
2547 #pragma message("warning: Qt is compiled without session manager")
2551 if (sm.allowsInteraction() && !closeAllViews())
2557 void GuiApplication::unregisterView(GuiView * gv)
2559 LAPPERR(d->views_[gv->id()] == gv);
2560 d->views_.remove(gv->id());
2561 if (current_view_ == gv)
2566 bool GuiApplication::closeAllViews()
2568 if (d->views_.empty())
2571 // When a view/window was closed before without quitting LyX, there
2572 // are already entries in the lastOpened list.
2573 theSession().lastOpened().clear();
2575 QList<GuiView *> const views = d->views_.values();
2576 foreach (GuiView * view, views) {
2577 if (!view->closeScheduled())
2586 GuiView & GuiApplication::view(int id) const
2588 LAPPERR(d->views_.contains(id));
2589 return *d->views_.value(id);
2593 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2595 QList<GuiView *> const views = d->views_.values();
2596 foreach (GuiView * view, views)
2597 view->hideDialog(name, inset);
2601 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2603 Buffer const * buffer_ = 0;
2604 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2605 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2606 if (Buffer const * ptr = (*it)->updateInset(inset))
2613 bool GuiApplication::searchMenu(FuncRequest const & func,
2614 docstring_list & names) const
2616 return d->menus_.searchMenu(func, names);
2620 // Ensure that a file is read only once (prevents include loops)
2621 static QStringList uifiles;
2622 // store which ui files define Toolbars
2623 static QStringList toolbar_uifiles;
2626 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2637 LexerKeyword uitags[] = {
2638 { "format", ui_format },
2639 { "include", ui_include },
2640 { "menuset", ui_menuset },
2641 { "toolbars", ui_toolbars },
2642 { "toolbarset", ui_toolbarset }
2646 lex.setFile(ui_path);
2648 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2652 if (lyxerr.debugging(Debug::PARSER))
2653 lex.printTable(lyxerr);
2656 // format before introduction of format tag
2657 unsigned int format = 0;
2658 while (lex.isOK()) {
2659 int const status = lex.lex();
2661 // we have to do this check here, outside the switch,
2662 // because otherwise we would start reading include files,
2663 // e.g., if the first tag we hit was an include tag.
2664 if (status == ui_format)
2666 format = lex.getInteger();
2670 // this will trigger unless the first tag we hit is a format
2671 // tag, with the right format.
2672 if (format != LFUN_FORMAT)
2673 return FormatMismatch;
2676 case Lexer::LEX_FEOF:
2681 QString const file = toqstr(lex.getString());
2682 bool const success = readUIFile(file, true);
2684 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2691 d->menus_.read(lex);
2695 d->toolbars_.readToolbars(lex);
2699 d->toolbars_.readToolbarSettings(lex);
2700 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2704 if (!rtrim(lex.getString()).empty())
2705 lex.printError("LyX::ReadUIFile: "
2706 "Unknown menu tag: `$$Token'");
2708 LYXERR0("Error with status: " << status);
2714 return (error ? ReadError : ReadOK);
2718 bool GuiApplication::readUIFile(QString const & name, bool include)
2720 LYXERR(Debug::INIT, "About to read " << name << "...");
2724 ui_path = libFileSearch("ui", name, "inc");
2725 if (ui_path.empty())
2726 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2728 ui_path = libFileSearch("ui", name, "ui");
2731 if (ui_path.empty()) {
2732 static const QString defaultUIFile = "default";
2733 LYXERR(Debug::INIT, "Could not find " << name);
2735 Alert::warning(_("Could not find UI definition file"),
2736 bformat(_("Error while reading the included file\n%1$s\n"
2737 "Please check your installation."), qstring_to_ucs4(name)));
2740 if (name == defaultUIFile) {
2741 LYXERR(Debug::INIT, "Could not find default UI file!!");
2742 Alert::warning(_("Could not find default UI file"),
2743 _("LyX could not find the default UI file!\n"
2744 "Please check your installation."));
2747 Alert::warning(_("Could not find UI definition file"),
2748 bformat(_("Error while reading the configuration file\n%1$s\n"
2749 "Falling back to default.\n"
2750 "Please look under Tools>Preferences>User Interface and\n"
2751 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2752 return readUIFile(defaultUIFile, false);
2755 QString const uifile = toqstr(ui_path.absFileName());
2756 if (uifiles.contains(uifile)) {
2758 // We are reading again the top uifile so reset the safeguard:
2761 d->toolbars_.reset();
2763 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2764 << "Is this an include loop?");
2768 uifiles.push_back(uifile);
2770 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2772 ReturnValues retval = readUIFile(ui_path);
2774 if (retval == FormatMismatch) {
2775 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2776 FileName const tempfile = FileName::tempName("convert_ui");
2777 bool const success = prefs2prefs(ui_path, tempfile, true);
2779 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2780 " to format " << LFUN_FORMAT << ".");
2782 retval = readUIFile(tempfile);
2783 tempfile.removeFile();
2787 if (retval != ReadOK) {
2788 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2796 settings.beginGroup("ui_files");
2797 bool touched = false;
2798 for (int i = 0; i != uifiles.size(); ++i) {
2799 QFileInfo fi(uifiles[i]);
2800 QDateTime const date_value = fi.lastModified();
2801 QString const name_key = QString::number(i);
2802 // if an ui file which defines Toolbars has changed,
2803 // we have to reset the settings
2804 if (toolbar_uifiles.contains(uifiles[i])
2805 && (!settings.contains(name_key)
2806 || settings.value(name_key).toString() != uifiles[i]
2807 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2809 settings.setValue(name_key, uifiles[i]);
2810 settings.setValue(name_key + "/date", date_value);
2813 settings.endGroup();
2815 settings.remove("views");
2821 void GuiApplication::onLastWindowClosed()
2823 if (d->global_menubar_)
2824 d->global_menubar_->grabKeyboard();
2828 void GuiApplication::startLongOperation() {
2829 d->key_checker_.start();
2833 bool GuiApplication::longOperationCancelled() {
2834 return d->key_checker_.pressed();
2838 void GuiApplication::stopLongOperation() {
2839 d->key_checker_.stop();
2843 bool GuiApplication::longOperationStarted() {
2844 return d->key_checker_.started();
2848 ////////////////////////////////////////////////////////////////////////
2850 // X11 specific stuff goes here...
2853 bool GuiApplication::x11EventFilter(XEvent * xev)
2858 switch (xev->type) {
2859 case SelectionRequest: {
2860 if (xev->xselectionrequest.selection != XA_PRIMARY)
2862 LYXERR(Debug::SELECTION, "X requested selection.");
2863 BufferView * bv = current_view_->currentBufferView();
2865 docstring const sel = bv->requestSelection();
2867 d->selection_.put(sel);
2871 case SelectionClear: {
2872 if (xev->xselectionclear.selection != XA_PRIMARY)
2874 LYXERR(Debug::SELECTION, "Lost selection.");
2875 BufferView * bv = current_view_->currentBufferView();
2877 bv->clearSelection();
2885 } // namespace frontend
2888 void hideDialogs(std::string const & name, Inset * inset)
2891 frontend::guiApp->hideDialogs(name, inset);
2895 ////////////////////////////////////////////////////////////////////
2899 ////////////////////////////////////////////////////////////////////
2901 frontend::FontLoader & theFontLoader()
2903 LAPPERR(frontend::guiApp);
2904 return frontend::guiApp->fontLoader();
2908 frontend::FontMetrics const & theFontMetrics(Font const & f)
2910 return theFontMetrics(f.fontInfo());
2914 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2916 LAPPERR(frontend::guiApp);
2917 return frontend::guiApp->fontLoader().metrics(f);
2921 ////////////////////////////////////////////////////////////////////
2925 ////////////////////////////////////////////////////////////////////
2927 frontend::Clipboard & theClipboard()
2929 LAPPERR(frontend::guiApp);
2930 return frontend::guiApp->clipboard();
2934 frontend::Selection & theSelection()
2936 LAPPERR(frontend::guiApp);
2937 return frontend::guiApp->selection();
2943 #include "moc_GuiApplication.cpp"