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 string const code = fromqstr(theLocale.name());
190 // Qt tries to outsmart us and transforms en_US to C.
191 Messages::guiLanguage((code == "C") ? "en_US" : code);
192 QLocale::setDefault(theLocale);
193 setlocale(LC_NUMERIC, "C");
200 /// Return the list of loadable formats.
201 vector<string> loadableImageFormats()
205 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
207 LYXERR(Debug::GRAPHICS,
208 "\nThe image loader can load the following directly:\n");
210 if (qt_formats.empty())
211 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
213 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
215 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
217 string ext = ascii_lowercase((const char *) *it);
228 ////////////////////////////////////////////////////////////////////////
230 // Icon loading support code
232 ////////////////////////////////////////////////////////////////////////
242 bool operator<(PngMap const & lhs, PngMap const & rhs)
244 return lhs.key < rhs.key;
250 CompareKey(QString const & name) : name_(name) {}
251 bool operator()(PngMap const & other) const { return other.key == name_; }
257 // this must be sorted alphabetically
258 // Upper case comes before lower case
259 // Please don't change the formatting, this list is parsed by
260 // development/tools/generate_symbols_images.py.
261 PngMap sorted_png_map[] = {
262 { "Arrownot", "arrownot2"},
263 { "Arrowvert", "arrowvert2"},
264 { "Bowtie", "bowtie2" },
266 { "Bumpeq", "bumpeq2" },
267 { "CIRCLE", "circle3" },
269 { "CheckedBox", "checkedbox2" },
270 { "Circle", "circle2" },
271 { "Colonapprox", "colonapprox2" },
272 { "Coloneq", "coloneq2" },
273 { "Coloneqq", "coloneqq2" },
274 { "Colonsim", "colonsim2" },
276 { "DOWNarrow", "downarrow3" },
277 { "Delta", "delta2" },
278 { "Diamond", "diamond2" },
279 { "Doteq", "doteq2" },
280 { "Downarrow", "downarrow2" },
281 { "Eqcolon", "eqcolon2" },
282 { "Eqqcolon", "eqqcolon2" },
283 { "Gamma", "gamma2" },
285 { "LEFTCIRCLE", "leftcircle3" },
286 { "LEFTarrow", "leftarrow3" },
287 { "LEFTcircle", "leftcircle4" },
289 { "Lambda", "lambda2" },
291 { "Leftarrow", "leftarrow2" },
292 { "Leftcircle", "leftcircle2" },
293 { "Leftrightarrow", "leftrightarrow2" },
294 { "Longarrownot", "longarrownot2"},
295 { "Longleftarrow", "longleftarrow2" },
296 { "Longleftrightarrow", "longleftrightarrow2" },
297 { "Longmapsfrom", "longmapsfrom2"},
298 { "Longmapsto", "longmapsto2"},
299 { "Longrightarrow", "longrightarrow2" },
300 { "Mapsfrom", "mapsfrom2"},
301 { "Mapsfromchar", "mapsfromchar2"},
302 { "Mapsto", "mapsto2"},
303 { "Mapstochar", "mapstochar2"},
304 { "Omega", "omega2" },
309 { "RIGHTCIRCLE", "rightcircle3" },
310 { "RIGHTarrow", "rightarrow3" },
311 { "RIGHTcircle", "rightcircle4" },
313 { "Rightarrow", "rightarrow2" },
314 { "Rightcircle", "rightcircle2" },
315 { "Sigma", "sigma2" },
316 { "Square", "square2" },
317 { "Subset", "subset2" },
318 { "Supset", "supset2" },
319 { "Theta", "theta2" },
320 { "Thorn", "thorn2" },
321 { "UParrow", "uparrow3" },
322 { "Uparrow", "uparrow2" },
323 { "Updownarrow", "updownarrow2" },
324 { "Upsilon", "upsilon2" },
325 { "Vdash", "vdash3" },
330 { "nLeftarrow", "nleftarrow2" },
331 { "nLeftrightarrow", "nleftrightarrow2" },
332 { "nRightarrow", "nrightarrow2" },
333 { "nVDash", "nvdash3" },
334 { "nVdash", "nvdash4" },
335 { "nvDash", "nvdash2" },
336 { "textrm \\AA", "textrm_AA"},
337 { "textrm \\O", "textrm_O"},
338 { "vDash", "vdash2" },
339 { "varDelta", "vardelta2" },
340 { "varGamma", "vargamma2" },
341 { "varLambda", "varlambda2" },
342 { "varOmega", "varomega2" },
343 { "varPhi", "varphi2" },
344 { "varPi", "varpi2" },
345 { "varPsi", "varpsi2" },
346 { "varSigma", "varsigma2" },
347 { "varTheta", "vartheta2" },
348 { "varUpsilon", "varupsilon2" },
349 { "varXi", "varxi2" }
353 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
355 // This list specifies which system's theme icon is related to which lyx
356 // command. It was based on:
357 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
358 // this must be sorted alphabetically
359 // Upper case comes before lower case
360 PngMap sorted_theme_icon_map[] = {
361 { "bookmark-goto 0", "go-jump" },
362 { "buffer-new", "document-new" },
363 { "buffer-print", "document-print" },
364 { "buffer-write", "document-save" },
365 { "buffer-write-as", "document-save-as" },
366 { "buffer-zoom-in", "zoom-in" },
367 { "buffer-zoom-out", "zoom-out" },
368 { "copy", "edit-copy" },
369 { "cut", "edit-cut" },
370 { "depth-decrement", "format-indent-less" },
371 { "depth-increment", "format-indent-more" },
372 { "dialog-show print", "document-print" },
373 { "dialog-show spellchecker", "tools-check-spelling" },
374 { "dialog-show-new-inset graphics", "insert-image" },
375 { "dialog-toggle findreplaceadv", "edit-find-replace" },
376 { "file-open", "document-open" },
377 { "font-bold", "format-text-bold" },
378 { "font-ital", "format-text-italic" },
379 { "font-strikeout", "format-text-strikethrough" },
380 { "font-underline", "format-text-underline" },
381 { "lyx-quit", "application-exit" },
382 { "paste", "edit-paste" },
383 { "redo", "edit-redo" },
384 { "undo", "edit-undo" },
385 { "window-close", "window-close" },
386 { "window-new", "window-new" }
389 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
392 QString findPng(QString const & name)
394 PngMap const * const begin = sorted_png_map;
395 PngMap const * const end = begin + nr_sorted_png_map;
396 LATTEST(sorted(begin, end));
398 PngMap const * const it = find_if(begin, end, CompareKey(name));
402 png_name = it->value;
405 png_name.replace('_', "underscore");
406 png_name.replace(' ', '_');
408 // This way we can have "math-delim { }" on the toolbar.
409 png_name.replace('(', "lparen");
410 png_name.replace(')', "rparen");
411 png_name.replace('[', "lbracket");
412 png_name.replace(']', "rbracket");
413 png_name.replace('{', "lbrace");
414 png_name.replace('}', "rbrace");
415 png_name.replace('|', "bars");
416 png_name.replace(',', "thinspace");
417 png_name.replace(':', "mediumspace");
418 png_name.replace(';', "thickspace");
419 png_name.replace('!', "negthinspace");
422 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
423 << "Looking for math PNG called \"" << png_name << '"');
430 QString themeIconName(QString const & action)
432 PngMap const * const begin = sorted_theme_icon_map;
433 PngMap const * const end = begin + nr_sorted_theme_icon_map;
434 LASSERT(sorted(begin, end), /**/);
436 PngMap const * const it = find_if(begin, end, CompareKey(action));
444 QString iconName(FuncRequest const & f, bool unknown)
446 initializeResources();
450 switch (f.action()) {
451 case LFUN_MATH_INSERT:
452 if (!f.argument().empty()) {
454 name1 = findPng(toqstr(f.argument()).mid(1));
457 case LFUN_MATH_DELIM:
458 case LFUN_MATH_BIGDELIM:
460 name1 = findPng(toqstr(f.argument()));
464 name1 = toqstr(f.argument());
466 case LFUN_COMMAND_ALTERNATIVES: {
467 // use the first of the alternative commands
469 docstring dummy = split(f.argument(), firstcom, ';');
470 name1 = toqstr(firstcom);
471 // FIXME: we should rename the icons to tabular-xxx instead of
472 // "tabular-feature-xxx"
473 name1.replace("inset-modify tabular", "tabular-feature");
474 name1.replace(' ', '_');
477 case LFUN_INSET_MODIFY: {
478 // FIXME: we should rename the icons to tabular-xxx instead of
479 // "tabular-feature-xxx" and generalize this naming to all
480 // insets, not to tabular using ones.
482 string const command = split(to_utf8(f.argument()), inset_name, ' ');
483 if (insetCode(inset_name) == TABULAR_CODE) {
484 name1 = "tabular-feature "+ toqstr(command);
485 name1.replace(' ', '_');
490 name2 = toqstr(lyxaction.getActionName(f.action()));
493 if (!f.argument().empty()) {
494 name1 = name2 + ' ' + toqstr(f.argument());
495 name1.replace(' ', '_');
496 name1.replace('\\', "backslash");
500 QStringList imagedirs;
501 imagedirs << "images/" << "images/ipa/";
502 for (int i = 0; i < imagedirs.size(); ++i) {
503 QString imagedir = imagedirs.at(i) + path;
504 FileName fname = imageLibFileSearch(imagedir, name1, "png");
506 return toqstr(fname.absFileName());
508 fname = imageLibFileSearch(imagedir, name2, "png");
510 return toqstr(fname.absFileName());
513 path = ":/images/" + path;
516 LYXERR0("Directory " << path << " not found in resource!");
520 if (res.exists(name1))
524 if (res.exists(name2))
527 LYXERR(Debug::GUI, "Cannot find icon with filename "
528 << "\"" << name1 << "\""
530 << "\"" << name2 << "\""
532 << lyxaction.getActionName(f.action())
533 << '(' << to_utf8(f.argument()) << ")\"");
536 QString imagedir = "images/";
537 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
539 return toqstr(fname.absFileName());
540 return QString(":/images/unknown.png");
546 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
549 QString imagedir = path;
550 FileName fname = imageLibFileSearch(imagedir, name, ext);
551 QString path1 = toqstr(fname.absFileName());
552 QString path2 = ":/" + path + name + "." + ext;
554 if (pixmap.load(path1)) {
557 else if (pixmap.load(path2)) {
561 LYXERR0("Cannot load pixmap \""
562 << path << name << '.' << ext
563 << "\", please verify resource system!");
568 QIcon getIcon(FuncRequest const & f, bool unknown)
570 #if (QT_VERSION >= 0x040600)
571 if (lyxrc.use_system_theme_icons) {
572 QString action = toqstr(lyxaction.getActionName(f.action()));
573 if (!f.argument().empty())
574 action += " " + toqstr(f.argument());
575 QString const theme_icon = themeIconName(action);
576 if (QIcon::hasThemeIcon(theme_icon))
577 return QIcon::fromTheme(theme_icon);
581 QString icon = iconName(f, unknown);
585 //LYXERR(Debug::GUI, "Found icon: " << icon);
587 if (!pm.load(icon)) {
588 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
596 ////////////////////////////////////////////////////////////////////////
598 // LyX server support code.
600 ////////////////////////////////////////////////////////////////////////
602 class SocketNotifier : public QSocketNotifier
605 /// connect a connection notification from the LyXServerSocket
606 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
607 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
611 /// The callback function
612 Application::SocketCallback func_;
616 ////////////////////////////////////////////////////////////////////////
618 // Mac specific stuff goes here...
620 ////////////////////////////////////////////////////////////////////////
622 class MenuTranslator : public QTranslator
625 MenuTranslator(QObject * parent)
626 : QTranslator(parent)
629 QString translate(const char * /*context*/,
630 const char * sourceText,
631 const char * /*comment*/ = 0) const
633 string const s = sourceText;
634 if (s == N_("About %1") || s == N_("Preferences")
635 || s == N_("Reconfigure") || s == N_("Quit %1"))
642 class GlobalMenuBar : public QMenuBar
646 GlobalMenuBar() : QMenuBar(0) {}
649 bool event(QEvent * e)
651 if (e->type() == QEvent::ShortcutOverride) {
652 // && activeWindow() == 0) {
653 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
655 setKeySymbol(&sym, ke);
656 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
665 // QMacPasteboardMimeGraphics can only be compiled on Mac.
667 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
670 QMacPasteboardMimeGraphics()
671 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
674 QString convertorName() { return "Graphics"; }
676 QString flavorFor(QString const & mime)
678 LYXERR(Debug::ACTION, "flavorFor " << mime);
679 if (mime == pdfMimeType())
680 return QLatin1String("com.adobe.pdf");
684 QString mimeFor(QString flav)
686 LYXERR(Debug::ACTION, "mimeFor " << flav);
687 if (flav == QLatin1String("com.adobe.pdf"))
688 return pdfMimeType();
692 bool canConvert(QString const & mime, QString flav)
694 return mimeFor(flav) == mime;
697 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
701 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
705 QList<QByteArray> convertFromMime(QString const & /*mime*/,
706 QVariant data, QString /*flav*/)
708 QList<QByteArray> ret;
709 ret.append(data.toByteArray());
715 ///////////////////////////////////////////////////////////////
717 // You can find more platform specific stuff at the end of this file...
719 ///////////////////////////////////////////////////////////////
721 ////////////////////////////////////////////////////////////////////////
722 // Windows specific stuff goes here...
725 // QWindowsMimeMetafile can only be compiled on Windows.
727 static FORMATETC cfFromMime(QString const & mimetype)
730 if (mimetype == emfMimeType()) {
731 formatetc.cfFormat = CF_ENHMETAFILE;
732 formatetc.tymed = TYMED_ENHMF;
733 } else if (mimetype == wmfMimeType()) {
734 formatetc.cfFormat = CF_METAFILEPICT;
735 formatetc.tymed = TYMED_MFPICT;
738 formatetc.dwAspect = DVASPECT_CONTENT;
739 formatetc.lindex = -1;
744 class QWindowsMimeMetafile : public QWindowsMime {
746 QWindowsMimeMetafile() {}
748 bool canConvertFromMime(FORMATETC const & formatetc,
749 QMimeData const * mimedata) const
754 bool canConvertToMime(QString const & mimetype,
755 IDataObject * pDataObj) const
757 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
759 FORMATETC formatetc = cfFromMime(mimetype);
760 return pDataObj->QueryGetData(&formatetc) == S_OK;
763 bool convertFromMime(FORMATETC const & formatetc,
764 const QMimeData * mimedata, STGMEDIUM * pmedium) const
769 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
770 QVariant::Type preferredType) const
773 if (!canConvertToMime(mimetype, pDataObj))
776 FORMATETC formatetc = cfFromMime(mimetype);
778 if (pDataObj->GetData(&formatetc, &s) != S_OK)
782 if (s.tymed == TYMED_ENHMF) {
783 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
784 data.resize(dataSize);
785 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
786 (LPBYTE)data.data());
787 } else if (s.tymed == TYMED_MFPICT) {
788 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
789 data.resize(dataSize);
790 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
791 (LPBYTE)data.data());
794 ReleaseStgMedium(&s);
800 QVector<FORMATETC> formatsForMime(QString const & mimetype,
801 QMimeData const * mimedata) const
803 QVector<FORMATETC> formats;
804 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
805 formats += cfFromMime(mimetype);
809 QString mimeForFormat(FORMATETC const & formatetc) const
811 switch (formatetc.cfFormat) {
813 return emfMimeType();
814 case CF_METAFILEPICT:
815 return wmfMimeType();
824 /// Allows to check whether ESC was pressed during a long operation
825 class KeyChecker : public QObject {
830 KeyChecker() : pressed_(false), started_(false) {}
833 QCoreApplication::instance()->installEventFilter(this);
838 QCoreApplication::instance()->removeEventFilter(this);
842 QCoreApplication::processEvents();
845 bool started() const {
848 bool eventFilter(QObject *obj, QEvent *event) {
849 LYXERR(Debug::ACTION, "Event Type: " << event->type());
850 switch (event->type()) {
854 return QObject::eventFilter(obj, event);
856 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
857 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
865 ////////////////////////////////////////////////////////////////////////
866 // GuiApplication::Private definition and implementation.
867 ////////////////////////////////////////////////////////////////////////
869 struct GuiApplication::Private
871 Private(): language_model_(0), meta_fake_bit(NoModifier),
875 /// WMF Mime handler for Windows clipboard.
876 wmf_mime_ = new QWindowsMimeMetafile;
878 initKeySequences(&theTopLevelKeymap());
881 void initKeySequences(KeyMap * kb)
883 keyseq = KeySequence(kb, kb);
884 cancel_meta_seq = KeySequence(kb, kb);
888 QSortFilterProxyModel * language_model_;
890 GuiClipboard clipboard_;
892 GuiSelection selection_;
894 FontLoader font_loader_;
896 ColorCache color_cache_;
898 QTranslator qt_trans_;
900 QHash<int, SocketNotifier *> socket_notifiers_;
904 /// The global instance
907 /// this timer is used for any regular events one wants to
908 /// perform. at present it is used to check if forked processes
910 QTimer general_timer_;
912 /// delayed FuncRequests
913 std::queue<FuncRequest> func_request_queue_;
918 KeySequence cancel_meta_seq;
920 KeyModifier meta_fake_bit;
922 /// Multiple views container.
924 * Warning: This must not be a smart pointer as the destruction of the
925 * object is handled by Qt when the view is closed
926 * \sa Qt::WA_DeleteOnClose attribute.
928 QHash<int, GuiView *> views_;
930 /// Only used on mac.
931 GlobalMenuBar * global_menubar_;
934 /// Linkback mime handler for MacOSX.
935 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
939 /// WMF Mime handler for Windows clipboard.
940 QWindowsMimeMetafile * wmf_mime_;
943 /// Allows to check whether ESC was pressed during a long operation
944 KeyChecker key_checker_;
948 GuiApplication * guiApp;
950 GuiApplication::~GuiApplication()
953 closeAllLinkBackLinks();
959 GuiApplication::GuiApplication(int & argc, char ** argv)
960 : QApplication(argc, argv), current_view_(0),
961 d(new GuiApplication::Private)
963 QString app_name = "LyX";
964 QCoreApplication::setOrganizationName(app_name);
965 QCoreApplication::setOrganizationDomain("lyx.org");
966 QCoreApplication::setApplicationName(lyx_package);
968 qsrand(QDateTime::currentDateTime().toTime_t());
970 // Install translator for GUI elements.
971 installTranslator(&d->qt_trans_);
973 // FIXME: quitOnLastWindowClosed is true by default. We should have a
974 // lyxrc setting for this in order to let the application stay resident.
975 // But then we need some kind of dock icon, at least on Windows.
977 if (lyxrc.quit_on_last_window_closed)
978 setQuitOnLastWindowClosed(false);
981 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
982 // seems to be the default case for applications like LyX.
983 setQuitOnLastWindowClosed(false);
984 // This allows to translate the strings that appear in the LyX menu.
985 /// A translator suitable for the entries in the LyX menu.
986 /// Only needed with Qt/Mac.
987 installTranslator(new MenuTranslator(this));
993 // doubleClickInterval() is 400 ms on X11 which is just too long.
994 // On Windows and Mac OS X, the operating system's value is used.
995 // On Microsoft Windows, calling this function sets the double
996 // click interval for all applications. So we don't!
997 QApplication::setDoubleClickInterval(300);
1000 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1002 // needs to be done before reading lyxrc
1004 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1008 // Set the cache to 5120 kilobytes which corresponds to screen size of
1009 // 1280 by 1024 pixels with a color depth of 32 bits.
1010 QPixmapCache::setCacheLimit(5120);
1012 // Initialize RC Fonts
1013 if (lyxrc.roman_font_name.empty())
1014 lyxrc.roman_font_name = fromqstr(romanFontName());
1016 if (lyxrc.sans_font_name.empty())
1017 lyxrc.sans_font_name = fromqstr(sansFontName());
1019 if (lyxrc.typewriter_font_name.empty())
1020 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1022 d->general_timer_.setInterval(500);
1023 connect(&d->general_timer_, SIGNAL(timeout()),
1024 this, SLOT(handleRegularEvents()));
1025 d->general_timer_.start();
1027 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1028 // This is clearly not enough in a time where we use threads for
1029 // document preview and/or export. 20 should be OK.
1030 QThreadPool::globalInstance()->setMaxThreadCount(20);
1034 GuiApplication * theGuiApp()
1036 return dynamic_cast<GuiApplication *>(theApp());
1040 void GuiApplication::clearSession()
1047 docstring Application::iconName(FuncRequest const & f, bool unknown)
1049 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1053 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1057 BufferView * bv = 0;
1058 BufferView * doc_bv = 0;
1060 if (cmd.action() == LFUN_NOACTION) {
1061 status.message(from_utf8(N_("Nothing to do")));
1062 status.setEnabled(false);
1065 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1066 status.setUnknown(true);
1067 status.message(from_utf8(N_("Unknown action")));
1068 status.setEnabled(false);
1071 // Does the GuiApplication know something?
1072 else if (getStatus(cmd, status)) { }
1074 // If we do not have a GuiView, then other functions are disabled
1075 else if (!current_view_)
1076 status.setEnabled(false);
1078 // Does the GuiView know something?
1079 else if (current_view_->getStatus(cmd, status)) { }
1081 // In LyX/Mac, when a dialog is open, the menus of the
1082 // application can still be accessed without giving focus to
1083 // the main window. In this case, we want to disable the menu
1084 // entries that are buffer or view-related.
1085 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1087 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1088 status.setEnabled(false);
1091 // If we do not have a BufferView, then other functions are disabled
1092 else if (!(bv = current_view_->currentBufferView()))
1093 status.setEnabled(false);
1095 // Does the current BufferView know something?
1096 else if (bv->getStatus(cmd, status)) { }
1098 // Does the current Buffer know something?
1099 else if (bv->buffer().getStatus(cmd, status)) { }
1101 // If we do not have a document BufferView, different from the
1102 // current BufferView, then other functions are disabled
1103 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1104 status.setEnabled(false);
1106 // Does the document Buffer know something?
1107 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1110 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1111 status.message(from_utf8(N_("Command not handled")));
1112 status.setEnabled(false);
1115 // the default error message if we disable the command
1116 if (!status.enabled() && status.message().empty())
1117 status.message(from_utf8(N_("Command disabled")));
1123 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1125 // I would really like to avoid having this switch and rather try to
1126 // encode this in the function itself.
1127 // -- And I'd rather let an inset decide which LFUNs it is willing
1128 // to handle (Andre')
1130 switch (cmd.action()) {
1132 // This could be used for the no-GUI version. The GUI version is handled in
1133 // GuiView::getStatus(). See above.
1135 case LFUN_BUFFER_WRITE:
1136 case LFUN_BUFFER_WRITE_AS: {
1137 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1138 enable = b && (b->isUnnamed() || !b->isClean());
1143 case LFUN_BOOKMARK_GOTO: {
1144 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1145 enable = theSession().bookmarks().isValid(num);
1149 case LFUN_BOOKMARK_CLEAR:
1150 enable = theSession().bookmarks().hasValid();
1153 // this one is difficult to get right. As a half-baked
1154 // solution, we consider only the first action of the sequence
1155 case LFUN_COMMAND_SEQUENCE: {
1156 // argument contains ';'-terminated commands
1157 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1158 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1159 func.setOrigin(cmd.origin());
1160 flag = getStatus(func);
1164 // we want to check if at least one of these is enabled
1165 case LFUN_COMMAND_ALTERNATIVES: {
1166 // argument contains ';'-terminated commands
1167 string arg = to_utf8(cmd.argument());
1168 while (!arg.empty()) {
1170 arg = split(arg, first, ';');
1171 FuncRequest func(lyxaction.lookupFunc(first));
1172 func.setOrigin(cmd.origin());
1173 flag = getStatus(func);
1174 // if this one is enabled, the whole thing is
1183 string name = to_utf8(cmd.argument());
1184 if (theTopLevelCmdDef().lock(name, func)) {
1185 func.setOrigin(cmd.origin());
1186 flag = getStatus(func);
1187 theTopLevelCmdDef().release(name);
1189 // catch recursion or unknown command
1190 // definition. all operations until the
1191 // recursion or unknown command definition
1192 // occurs are performed, so set the state to
1199 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1201 case LFUN_PREFERENCES_SAVE:
1202 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1203 case LFUN_DEBUG_LEVEL_SET:
1204 // these are handled in our dispatch()
1207 case LFUN_WINDOW_CLOSE:
1208 enable = d->views_.size() > 0;
1211 case LFUN_BUFFER_NEW:
1212 case LFUN_BUFFER_NEW_TEMPLATE:
1213 case LFUN_FILE_OPEN:
1214 case LFUN_HELP_OPEN:
1215 case LFUN_SCREEN_FONT_UPDATE:
1216 case LFUN_SET_COLOR:
1217 case LFUN_WINDOW_NEW:
1219 case LFUN_LYXRC_APPLY:
1220 case LFUN_COMMAND_PREFIX:
1222 case LFUN_META_PREFIX:
1223 case LFUN_RECONFIGURE:
1224 case LFUN_SERVER_GET_FILENAME:
1225 case LFUN_SERVER_NOTIFY:
1229 case LFUN_BUFFER_FORALL: {
1230 if (theBufferList().empty()) {
1231 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1232 flag.setEnabled(false);
1236 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1237 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1238 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1239 flag.setEnabled(false);
1250 flag.setEnabled(false);
1254 /// make a post-dispatch status message
1255 static docstring makeDispatchMessage(docstring const & msg,
1256 FuncRequest const & cmd)
1258 const bool verbose = (cmd.origin() == FuncRequest::MENU
1259 || cmd.origin() == FuncRequest::TOOLBAR
1260 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1262 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1263 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1267 docstring dispatch_msg = msg;
1268 if (!dispatch_msg.empty())
1269 dispatch_msg += ' ';
1271 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1273 bool argsadded = false;
1275 if (!cmd.argument().empty()) {
1276 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1277 comname += ' ' + cmd.argument();
1281 docstring const shortcuts = theTopLevelKeymap().
1282 printBindings(cmd, KeySequence::ForGui);
1284 if (!shortcuts.empty())
1285 comname += ": " + shortcuts;
1286 else if (!argsadded && !cmd.argument().empty())
1287 comname += ' ' + cmd.argument();
1289 if (!comname.empty()) {
1290 comname = rtrim(comname);
1291 dispatch_msg += '(' + rtrim(comname) + ')';
1293 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1294 return dispatch_msg;
1298 void GuiApplication::dispatch(FuncRequest const & cmd)
1300 Buffer * buffer = 0;
1301 if (current_view_ && current_view_->currentBufferView()) {
1302 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1303 buffer = ¤t_view_->currentBufferView()->buffer();
1305 buffer->undo().beginUndoGroup();
1309 // redraw the screen at the end (first of the two drawing steps).
1310 // This is done unless explicitly requested otherwise
1311 dr.screenUpdate(Update::FitCursor);
1313 updateCurrentView(cmd, dr);
1315 // the buffer may have been closed by one action
1316 if (theBufferList().isLoaded(buffer))
1317 buffer->undo().endUndoGroup();
1321 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1326 BufferView * bv = current_view_->currentBufferView();
1328 if (dr.needBufferUpdate()) {
1329 bv->cursor().clearBufferUpdate();
1330 bv->buffer().updateBuffer();
1332 // BufferView::update() updates the ViewMetricsInfo and
1333 // also initializes the position cache for all insets in
1334 // (at least partially) visible top-level paragraphs.
1335 // We will redraw the screen only if needed.
1336 bv->processUpdateFlags(dr.screenUpdate());
1338 // Do we have a selection?
1339 theSelection().haveSelection(bv->cursor().selection());
1342 current_view_->restartCursor();
1344 if (dr.needMessageUpdate()) {
1345 // Some messages may already be translated, so we cannot use _()
1346 current_view_->message(makeDispatchMessage(
1347 translateIfPossible(dr.message()), cmd));
1352 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1353 bool switchToBuffer)
1355 if (!theSession().bookmarks().isValid(idx))
1357 BookmarksSection::Bookmark const & bm =
1358 theSession().bookmarks().bookmark(idx);
1359 LASSERT(!bm.filename.empty(), return);
1360 string const file = bm.filename.absFileName();
1361 // if the file is not opened, open it.
1362 if (!theBufferList().exists(bm.filename)) {
1364 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1368 // open may fail, so we need to test it again
1369 if (!theBufferList().exists(bm.filename))
1372 // bm can be changed when saving
1373 BookmarksSection::Bookmark tmp = bm;
1375 // Special case idx == 0 used for back-from-back jump navigation
1377 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1379 // if the current buffer is not that one, switch to it.
1380 BufferView * doc_bv = current_view_ ?
1381 current_view_->documentBufferView() : 0;
1382 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1383 if (switchToBuffer) {
1384 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1387 doc_bv = current_view_->documentBufferView();
1392 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1393 if (!doc_bv->moveToPosition(
1394 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1401 // Cursor jump succeeded!
1402 Cursor const & cur = doc_bv->cursor();
1403 pit_type new_pit = cur.pit();
1404 pos_type new_pos = cur.pos();
1405 int new_id = cur.paragraph().id();
1407 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1408 // see http://www.lyx.org/trac/ticket/3092
1409 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1410 || bm.top_id != new_id) {
1411 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1412 new_pit, new_pos, new_id);
1416 // This function runs "configure" and then rereads lyx.defaults to
1417 // reconfigure the automatic settings.
1418 void GuiApplication::reconfigure(string const & option)
1420 // emit message signal.
1422 current_view_->message(_("Running configure..."));
1424 // Run configure in user lyx directory
1425 PathChanger p(package().user_support());
1426 string configure_command = package().configure_command();
1427 configure_command += option;
1429 int const ret = one.startscript(Systemcall::Wait, configure_command);
1431 // emit message signal.
1433 current_view_->message(_("Reloading configuration..."));
1434 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1435 // Re-read packages.lst
1436 LaTeXPackages::getAvailable();
1439 Alert::information(_("System reconfiguration failed"),
1440 _("The system reconfiguration has failed.\n"
1441 "Default textclass is used but LyX may\n"
1442 "not be able to work properly.\n"
1443 "Please reconfigure again if needed."));
1445 Alert::information(_("System reconfigured"),
1446 _("The system has been reconfigured.\n"
1447 "You need to restart LyX to make use of any\n"
1448 "updated document class specifications."));
1451 void GuiApplication::validateCurrentView()
1453 if (!d->views_.empty() && !current_view_) {
1454 // currently at least one view exists but no view has the focus.
1455 // choose the last view to make it current.
1456 // a view without any open document is preferred.
1457 GuiView * candidate = 0;
1458 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1459 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1460 for (; it != end; ++it) {
1462 if (!candidate->documentBufferView())
1465 setCurrentView(candidate);
1469 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1471 string const argument = to_utf8(cmd.argument());
1472 FuncCode const action = cmd.action();
1474 LYXERR(Debug::ACTION, "cmd: " << cmd);
1476 // we have not done anything wrong yet.
1479 FuncStatus const flag = getStatus(cmd);
1480 if (!flag.enabled()) {
1481 // We cannot use this function here
1482 LYXERR(Debug::ACTION, "action "
1483 << lyxaction.getActionName(action)
1484 << " [" << action << "] is disabled at this location");
1485 dr.setMessage(flag.message());
1487 dr.dispatched(false);
1488 dr.screenUpdate(Update::None);
1489 dr.clearBufferUpdate();
1493 if (cmd.origin() == FuncRequest::LYXSERVER) {
1494 if (current_view_ && current_view_->currentBufferView())
1495 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1496 // we will also need to redraw the screen at the end
1497 dr.screenUpdate(Update::FitCursor);
1500 // Assumes that the action will be dispatched.
1501 dr.dispatched(true);
1503 switch (cmd.action()) {
1505 case LFUN_WINDOW_NEW:
1506 createView(toqstr(cmd.argument()));
1509 case LFUN_WINDOW_CLOSE:
1510 // update bookmark pit of the current buffer before window close
1511 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1512 gotoBookmark(i+1, false, false);
1513 // clear the last opened list, because
1514 // maybe this will end the session
1515 theSession().lastOpened().clear();
1516 // check for valid current_view_
1517 validateCurrentView();
1519 current_view_->closeScheduled();
1523 // quitting is triggered by the gui code
1524 // (leaving the event loop).
1526 current_view_->message(from_utf8(N_("Exiting.")));
1527 if (closeAllViews())
1531 case LFUN_SCREEN_FONT_UPDATE: {
1532 // handle the screen font changes.
1533 d->font_loader_.update();
1534 // Backup current_view_
1535 GuiView * view = current_view_;
1536 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1537 // to skip the refresh.
1539 theBufferList().changed(false);
1540 // Restore current_view_
1541 current_view_ = view;
1545 case LFUN_BUFFER_NEW:
1546 validateCurrentView();
1547 if (d->views_.empty()
1548 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1549 createView(QString(), false); // keep hidden
1550 current_view_->newDocument(to_utf8(cmd.argument()), false);
1551 current_view_->show();
1552 setActiveWindow(current_view_);
1554 current_view_->newDocument(to_utf8(cmd.argument()), false);
1558 case LFUN_BUFFER_NEW_TEMPLATE:
1559 validateCurrentView();
1560 if (d->views_.empty()
1561 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1563 current_view_->newDocument(to_utf8(cmd.argument()), true);
1564 if (!current_view_->documentBufferView())
1565 current_view_->close();
1567 current_view_->newDocument(to_utf8(cmd.argument()), true);
1571 case LFUN_FILE_OPEN: {
1572 validateCurrentView();
1573 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1574 string const fname = to_utf8(cmd.argument());
1575 if (!fname.empty() && !FileName::isAbsolute(fname)) {
1577 dr.setMessage(_("Absolute filename expected."));
1580 bool const is_open = FileName::isAbsolute(fname)
1581 && theBufferList().getBuffer(FileName(fname));
1582 if (d->views_.empty()
1583 || (!lyxrc.open_buffers_in_tabs
1584 && current_view_->documentBufferView() != 0
1586 // We want the ui session to be saved per document and not per
1587 // window number. The filename crc is a good enough identifier.
1588 boost::crc_32_type crc;
1589 crc = for_each(fname.begin(), fname.end(), crc);
1590 createView(crc.checksum());
1591 current_view_->openDocument(fname);
1592 if (current_view_ && !current_view_->documentBufferView())
1593 current_view_->close();
1595 current_view_->openDocument(fname);
1599 case LFUN_HELP_OPEN: {
1600 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1601 if (current_view_ == 0)
1603 string const arg = to_utf8(cmd.argument());
1605 current_view_->message(_("Missing argument"));
1608 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1610 fname = i18nLibFileSearch("examples", arg, "lyx");
1612 if (fname.empty()) {
1613 lyxerr << "LyX: unable to find documentation file `"
1614 << arg << "'. Bad installation?" << endl;
1617 current_view_->message(bformat(_("Opening help file %1$s..."),
1618 makeDisplayPath(fname.absFileName())));
1619 Buffer * buf = current_view_->loadDocument(fname, false);
1621 #ifndef DEVEL_VERSION
1623 buf->setReadonly(true);
1630 case LFUN_SET_COLOR: {
1632 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1633 if (lyx_name.empty() || x11_name.empty()) {
1635 current_view_->message(
1636 _("Syntax: set-color <lyx_name> <x11_name>"));
1641 // FIXME: The graphics cache no longer has a changeDisplay method.
1642 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1643 bool const graphicsbg_changed =
1644 lyx_name == graphicsbg && x11_name != graphicsbg;
1645 if (graphicsbg_changed)
1646 graphics::GCache::get().changeDisplay(true);
1649 if (!lcolor.setColor(lyx_name, x11_name)) {
1651 current_view_->message(
1652 bformat(_("Set-color \"%1$s\" failed "
1653 "- color is undefined or "
1654 "may not be redefined"),
1655 from_utf8(lyx_name)));
1658 // Make sure we don't keep old colors in cache.
1659 d->color_cache_.clear();
1663 case LFUN_LYXRC_APPLY: {
1664 // reset active key sequences, since the bindings
1665 // are updated (bug 6064)
1667 LyXRC const lyxrc_orig = lyxrc;
1669 istringstream ss(to_utf8(cmd.argument()));
1670 bool const success = lyxrc.read(ss);
1673 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1674 << "Unable to read lyxrc data"
1679 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1681 // If the request comes from the minibuffer, then we can't reset
1682 // the GUI, since that would destory the minibuffer itself and
1683 // cause a crash, since we are currently in one of the methods of
1684 // GuiCommandBuffer. See bug #8540.
1685 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1688 // FIXME Unfortunately, that leaves a bug here, since we cannot
1689 // reset the GUI in this case. If the changes to lyxrc affected the
1690 // UI, then, nothing would happen. This seems fairly unlikely, but
1691 // it definitely is a bug.
1696 case LFUN_COMMAND_PREFIX:
1697 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1702 d->meta_fake_bit = NoModifier;
1703 GuiView * gv = currentView();
1704 if (gv && gv->currentBufferView())
1705 // cancel any selection
1706 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1707 dr.setMessage(from_ascii(N_("Cancel")));
1710 case LFUN_META_PREFIX:
1711 d->meta_fake_bit = AltModifier;
1712 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1715 // --- Menus -----------------------------------------------
1716 case LFUN_RECONFIGURE:
1717 // argument is any additional parameter to the configure.py command
1718 reconfigure(to_utf8(cmd.argument()));
1721 // --- lyxserver commands ----------------------------
1722 case LFUN_SERVER_GET_FILENAME: {
1723 if (current_view_ && current_view_->documentBufferView()) {
1724 docstring const fname = from_utf8(
1725 current_view_->documentBufferView()->buffer().absFileName());
1726 dr.setMessage(fname);
1727 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1729 dr.setMessage(docstring());
1730 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1735 case LFUN_SERVER_NOTIFY: {
1736 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1737 dr.setMessage(dispatch_buffer);
1738 theServer().notifyClient(to_utf8(dispatch_buffer));
1742 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1743 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1749 string rest = split(argument, countstr, ' ');
1750 istringstream is(countstr);
1753 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1754 for (int i = 0; i < count; ++i)
1755 dispatch(lyxaction.lookupFunc(rest));
1759 case LFUN_COMMAND_SEQUENCE: {
1760 // argument contains ';'-terminated commands
1761 string arg = argument;
1762 // FIXME: this LFUN should also work without any view.
1763 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1764 ? &(current_view_->documentBufferView()->buffer()) : 0;
1766 buffer->undo().beginUndoGroup();
1767 while (!arg.empty()) {
1769 arg = split(arg, first, ';');
1770 FuncRequest func(lyxaction.lookupFunc(first));
1771 func.setOrigin(cmd.origin());
1774 // the buffer may have been closed by one action
1775 if (theBufferList().isLoaded(buffer))
1776 buffer->undo().endUndoGroup();
1780 case LFUN_BUFFER_FORALL: {
1781 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1783 map<Buffer *, GuiView *> views_lVisible;
1784 map<GuiView *, Buffer *> activeBuffers;
1786 QList<GuiView *> allViews = d->views_.values();
1788 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1789 // and on which buffer is active in each view.
1790 Buffer * const last = theBufferList().last();
1791 foreach (GuiView * view, allViews) {
1792 // all of the buffers might be locally hidden. That is, there is no active buffer.
1793 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1794 activeBuffers[view] = 0;
1796 activeBuffers[view] = &view->currentBufferView()->buffer();
1798 // find out if each is locally visible or locally hidden.
1799 // we don't use a for loop as the buffer list cycles.
1800 Buffer * b = theBufferList().first();
1802 bool const locallyVisible = view && view->workArea(*b);
1803 if (locallyVisible) {
1804 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1805 // only need to overwrite/add if we don't already know a buffer is globally
1806 // visible or we do know but we would prefer to dispatch LFUN from the
1807 // current view because of cursor position issues.
1808 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1809 views_lVisible[b] = view;
1813 b = theBufferList().next(b);
1817 GuiView * const homeView = currentView();
1818 Buffer * b = theBufferList().first();
1819 Buffer * nextBuf = 0;
1820 int numProcessed = 0;
1823 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1825 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1827 // first change to a view where b is locally visible, preferably current_view_.
1828 GuiView * const vLv = views_lVisible[b];
1830 lyx::dispatch(funcToRun);
1838 // put things back to how they were (if possible).
1839 foreach (GuiView * view, allViews) {
1840 Buffer * originalBuf = activeBuffers[view];
1841 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1842 if (theBufferList().isLoaded(originalBuf))
1843 view->setBuffer(originalBuf);
1845 homeView->setFocus();
1847 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1851 case LFUN_COMMAND_ALTERNATIVES: {
1852 // argument contains ';'-terminated commands
1853 string arg = argument;
1854 while (!arg.empty()) {
1856 arg = split(arg, first, ';');
1857 FuncRequest func(lyxaction.lookupFunc(first));
1858 func.setOrigin(cmd.origin());
1859 FuncStatus const stat = getStatus(func);
1860 if (stat.enabled()) {
1870 if (theTopLevelCmdDef().lock(argument, func)) {
1871 func.setOrigin(cmd.origin());
1873 theTopLevelCmdDef().release(argument);
1875 if (func.action() == LFUN_UNKNOWN_ACTION) {
1876 // unknown command definition
1877 lyxerr << "Warning: unknown command definition `"
1881 // recursion detected
1882 lyxerr << "Warning: Recursion in the command definition `"
1883 << argument << "' detected"
1890 case LFUN_PREFERENCES_SAVE:
1891 lyxrc.write(support::makeAbsPath("preferences",
1892 package().user_support().absFileName()), false);
1895 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1896 string const fname = addName(addPath(package().user_support().absFileName(),
1897 "templates/"), "defaults.lyx");
1898 Buffer defaults(fname);
1900 istringstream ss(argument);
1903 int const unknown_tokens = defaults.readHeader(lex);
1905 if (unknown_tokens != 0) {
1906 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1907 << unknown_tokens << " unknown token"
1908 << (unknown_tokens == 1 ? "" : "s")
1912 if (defaults.writeFile(FileName(defaults.absFileName())))
1913 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1914 makeDisplayPath(fname)));
1917 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1922 case LFUN_BOOKMARK_GOTO:
1923 // go to bookmark, open unopened file and switch to buffer if necessary
1924 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1925 dr.screenUpdate(Update::Force | Update::FitCursor);
1928 case LFUN_BOOKMARK_CLEAR:
1929 theSession().bookmarks().clear();
1932 case LFUN_DEBUG_LEVEL_SET:
1933 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1937 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1940 current_view_->dispatch(cmd, dr);
1944 if (cmd.origin() == FuncRequest::LYXSERVER)
1945 updateCurrentView(cmd, dr);
1949 docstring GuiApplication::viewStatusMessage()
1951 // When meta-fake key is pressed, show the key sequence so far + "M-".
1952 if (d->meta_fake_bit != NoModifier)
1953 return d->keyseq.print(KeySequence::ForGui) + "M-";
1955 // Else, when a non-complete key sequence is pressed,
1956 // show the available options.
1957 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1958 return d->keyseq.printOptions(true);
1964 void GuiApplication::handleKeyFunc(FuncCode action)
1968 if (d->keyseq.length())
1970 GuiView * gv = currentView();
1971 LASSERT(gv && gv->currentBufferView(), return);
1972 BufferView * bv = gv->currentBufferView();
1973 bv->getIntl().getTransManager().deadkey(
1974 c, get_accent(action).accent, bv->cursor().innerText(),
1976 // Need to clear, in case the minibuffer calls these
1979 // copied verbatim from do_accent_char
1980 bv->cursor().resetAnchor();
1984 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1986 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1988 // Do nothing if we have nothing (JMarc)
1989 if (!keysym.isOK()) {
1990 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1992 current_view_->restartCursor();
1996 if (keysym.isModifier()) {
1998 current_view_->restartCursor();
2002 char_type encoded_last_key = keysym.getUCSEncoded();
2004 // Do a one-deep top-level lookup for
2005 // cancel and meta-fake keys. RVDK_PATCH_5
2006 d->cancel_meta_seq.reset();
2008 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2009 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2011 // When not cancel or meta-fake, do the normal lookup.
2012 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2013 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2014 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2015 // remove Caps Lock and Mod2 as a modifiers
2016 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2017 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2020 // Dont remove this unless you know what you are doing.
2021 d->meta_fake_bit = NoModifier;
2023 // Can this happen now ?
2024 if (func.action() == LFUN_NOACTION)
2025 func = FuncRequest(LFUN_COMMAND_PREFIX);
2027 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2028 << d->keyseq.print(KeySequence::Portable) << ']');
2030 // already here we know if it any point in going further
2031 // why not return already here if action == -1 and
2032 // num_bytes == 0? (Lgb)
2034 if (d->keyseq.length() > 1 && current_view_)
2035 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2038 // Maybe user can only reach the key via holding down shift.
2039 // Let's see. But only if shift is the only modifier
2040 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2041 LYXERR(Debug::KEY, "Trying without shift");
2042 func = d->keyseq.addkey(keysym, NoModifier);
2043 LYXERR(Debug::KEY, "Action now " << func.action());
2046 if (func.action() == LFUN_UNKNOWN_ACTION) {
2047 // Hmm, we didn't match any of the keysequences. See
2048 // if it's normal insertable text not already covered
2050 if (keysym.isText() && d->keyseq.length() == 1) {
2051 LYXERR(Debug::KEY, "isText() is true, inserting.");
2052 func = FuncRequest(LFUN_SELF_INSERT,
2053 FuncRequest::KEYBOARD);
2055 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2056 if (current_view_) {
2057 current_view_->message(_("Unknown function."));
2058 current_view_->restartCursor();
2064 if (func.action() == LFUN_SELF_INSERT) {
2065 if (encoded_last_key != 0) {
2066 docstring const arg(1, encoded_last_key);
2067 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2068 FuncRequest::KEYBOARD));
2069 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2072 processFuncRequest(func);
2076 void GuiApplication::processFuncRequest(FuncRequest const & func)
2078 lyx::dispatch(func);
2082 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2084 addToFuncRequestQueue(func);
2085 processFuncRequestQueueAsync();
2089 void GuiApplication::processFuncRequestQueue()
2091 while (!d->func_request_queue_.empty()) {
2092 processFuncRequest(d->func_request_queue_.front());
2093 d->func_request_queue_.pop();
2098 void GuiApplication::processFuncRequestQueueAsync()
2100 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2104 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2106 d->func_request_queue_.push(func);
2110 void GuiApplication::resetGui()
2112 // Set the language defined by the user.
2116 if (!readUIFile(toqstr(lyxrc.ui_file)))
2117 // Gives some error box here.
2120 if (d->global_menubar_)
2121 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2123 QHash<int, GuiView *>::iterator it;
2124 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2127 gv->setLayoutDirection(layoutDirection());
2131 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2135 void GuiApplication::createView(int view_id)
2137 createView(QString(), true, view_id);
2141 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2144 // release the keyboard which might have been grabed by the global
2145 // menubar on Mac to catch shortcuts even without any GuiView.
2146 if (d->global_menubar_)
2147 d->global_menubar_->releaseKeyboard();
2151 while (d->views_.find(id) != d->views_.end())
2154 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2155 GuiView * view = new GuiView(id);
2157 d->views_[id] = view;
2161 setActiveWindow(view);
2164 if (!geometry_arg.isEmpty()) {
2168 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2169 re.indexIn(geometry_arg);
2170 w = re.cap(1).toInt();
2171 h = re.cap(2).toInt();
2172 x = re.cap(3).toInt();
2173 y = re.cap(4).toInt();
2174 view->setGeometry(x, y, w, h);
2181 Clipboard & GuiApplication::clipboard()
2183 return d->clipboard_;
2187 Selection & GuiApplication::selection()
2189 return d->selection_;
2193 FontLoader & GuiApplication::fontLoader()
2195 return d->font_loader_;
2199 Toolbars const & GuiApplication::toolbars() const
2201 return d->toolbars_;
2205 Toolbars & GuiApplication::toolbars()
2207 return d->toolbars_;
2211 Menus const & GuiApplication::menus() const
2217 Menus & GuiApplication::menus()
2223 QList<int> GuiApplication::viewIds() const
2225 return d->views_.keys();
2229 ColorCache & GuiApplication::colorCache()
2231 return d->color_cache_;
2235 int GuiApplication::exec()
2237 // asynchronously handle batch commands. This event will be in
2238 // the event queue in front of other asynchronous events. Hence,
2239 // we can assume in the latter that the gui is setup already.
2240 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2242 return QApplication::exec();
2246 void GuiApplication::exit(int status)
2248 QApplication::exit(status);
2252 void GuiApplication::setGuiLanguage()
2256 // install translation file for Qt built-in dialogs
2257 QString const language_name = QString("qt_") + theLocale.name();
2258 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2259 // Short-named translator can be loaded from a long name, but not the
2260 // opposite. Therefore, long name should be used without truncation.
2261 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2262 if (!d->qt_trans_.load(language_name,
2263 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2264 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2267 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2271 switch (theLocale.language()) {
2272 case QLocale::Arabic :
2273 case QLocale::Hebrew :
2274 case QLocale::Persian :
2275 case QLocale::Urdu :
2276 setLayoutDirection(Qt::RightToLeft);
2279 setLayoutDirection(Qt::LeftToRight);
2284 void GuiApplication::execBatchCommands()
2289 if (!readUIFile(toqstr(lyxrc.ui_file)))
2290 // Gives some error box here.
2294 #if QT_VERSION > 0x040600
2295 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2297 // Create the global default menubar which is shown for the dialogs
2298 // and if no GuiView is visible.
2299 // This must be done after the session was recovered to know the "last files".
2300 d->global_menubar_ = new GlobalMenuBar;
2301 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2304 lyx::execBatchCommands();
2308 QAbstractItemModel * GuiApplication::languageModel()
2310 if (d->language_model_)
2311 return d->language_model_;
2313 QStandardItemModel * lang_model = new QStandardItemModel(this);
2314 lang_model->insertColumns(0, 3);
2316 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2317 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2318 Languages::const_iterator it = lyx::languages.begin();
2319 Languages::const_iterator end = lyx::languages.end();
2320 for (; it != end; ++it) {
2321 current_row = lang_model->rowCount();
2322 lang_model->insertRows(current_row, 1);
2323 QModelIndex pl_item = lang_model->index(current_row, 0);
2324 QModelIndex sp_item = lang_model->index(current_row, 1);
2325 QModelIndex th_item = lang_model->index(current_row, 2);
2326 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2327 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2328 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2329 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2330 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2331 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2332 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2333 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2334 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2335 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2337 d->language_model_ = new QSortFilterProxyModel(this);
2338 d->language_model_->setSourceModel(lang_model);
2339 d->language_model_->setSortLocaleAware(true);
2340 return d->language_model_;
2344 void GuiApplication::restoreGuiSession()
2346 if (!lyxrc.load_session)
2349 Session & session = theSession();
2350 LastOpenedSection::LastOpened const & lastopened =
2351 session.lastOpened().getfiles();
2353 validateCurrentView();
2355 FileName active_file;
2356 // do not add to the lastfile list since these files are restored from
2357 // last session, and should be already there (regular files), or should
2358 // not be added at all (help files).
2359 for (size_t i = 0; i < lastopened.size(); ++i) {
2360 FileName const & file_name = lastopened[i].file_name;
2361 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2362 && current_view_->documentBufferView() != 0)) {
2363 boost::crc_32_type crc;
2364 string const & fname = file_name.absFileName();
2365 crc = for_each(fname.begin(), fname.end(), crc);
2366 createView(crc.checksum());
2368 current_view_->loadDocument(file_name, false);
2370 if (lastopened[i].active)
2371 active_file = file_name;
2374 // Restore last active buffer
2375 Buffer * buffer = theBufferList().getBuffer(active_file);
2376 if (buffer && current_view_)
2377 current_view_->setBuffer(buffer);
2379 // clear this list to save a few bytes of RAM
2380 session.lastOpened().clear();
2384 QString const GuiApplication::romanFontName()
2387 font.setKerning(false);
2388 font.setStyleHint(QFont::Serif);
2389 font.setFamily("serif");
2391 return QFontInfo(font).family();
2395 QString const GuiApplication::sansFontName()
2398 font.setKerning(false);
2399 font.setStyleHint(QFont::SansSerif);
2400 font.setFamily("sans");
2402 return QFontInfo(font).family();
2406 QString const GuiApplication::typewriterFontName()
2409 font.setKerning(false);
2410 font.setStyleHint(QFont::TypeWriter);
2411 font.setFamily("monospace");
2413 return QFontInfo(font).family();
2417 void GuiApplication::handleRegularEvents()
2419 ForkedCallsController::handleCompletedProcesses();
2423 bool GuiApplication::event(QEvent * e)
2426 case QEvent::FileOpen: {
2427 // Open a file; this happens only on Mac OS X for now.
2429 // We do this asynchronously because on startup the batch
2430 // commands are not executed here yet and the gui is not ready
2432 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2433 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2434 processFuncRequestAsync(fr);
2439 return QApplication::event(e);
2444 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2447 return QApplication::notify(receiver, event);
2449 catch (ExceptionMessage const & e) {
2451 case ErrorException:
2453 setQuitOnLastWindowClosed(false);
2455 Alert::error(e.title_, e.details_);
2457 // Properly crash in debug mode in order to get a useful backtrace.
2460 // In release mode, try to exit gracefully.
2463 case BufferException: {
2464 if (!current_view_ || !current_view_->documentBufferView())
2466 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2467 docstring details = e.details_ + '\n';
2468 details += buf->emergencyWrite();
2469 theBufferList().release(buf);
2470 details += "\n" + _("The current document was closed.");
2471 Alert::error(e.title_, details);
2474 case WarningException:
2475 Alert::warning(e.title_, e.details_);
2479 catch (exception const & e) {
2480 docstring s = _("LyX has caught an exception, it will now "
2481 "attempt to save all unsaved documents and exit."
2483 s += from_ascii(e.what());
2484 Alert::error(_("Software exception Detected"), s);
2488 docstring s = _("LyX has caught some really weird exception, it will "
2489 "now attempt to save all unsaved documents and exit.");
2490 Alert::error(_("Software exception Detected"), s);
2498 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2500 QColor const & qcol = d->color_cache_.get(col);
2501 if (!qcol.isValid()) {
2507 rgbcol.r = qcol.red();
2508 rgbcol.g = qcol.green();
2509 rgbcol.b = qcol.blue();
2514 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2516 QColor const qcol(lcolor.getX11Name(col).c_str());
2517 if (!qcol.isValid()) {
2523 rgbcol.r = qcol.red();
2524 rgbcol.g = qcol.green();
2525 rgbcol.b = qcol.blue();
2530 string const GuiApplication::hexName(ColorCode col)
2532 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2536 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2538 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2539 d->socket_notifiers_[fd] = sn;
2540 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2544 void GuiApplication::socketDataReceived(int fd)
2546 d->socket_notifiers_[fd]->func_();
2550 void GuiApplication::unregisterSocketCallback(int fd)
2552 d->socket_notifiers_.take(fd)->setEnabled(false);
2556 void GuiApplication::commitData(QSessionManager & sm)
2558 /// The implementation is required to avoid an application exit
2559 /// when session state save is triggered by session manager.
2560 /// The default implementation sends a close event to all
2561 /// visible top level widgets when session managment allows
2563 /// We are changing that to close all wiew one by one.
2564 /// FIXME: verify if the default implementation is enough now.
2565 #ifdef QT_NO_SESSIONMANAGER
2567 #warning Qt is compiled without session manager
2569 #pragma message("warning: Qt is compiled without session manager")
2573 if (sm.allowsInteraction() && !closeAllViews())
2579 void GuiApplication::unregisterView(GuiView * gv)
2581 LAPPERR(d->views_[gv->id()] == gv);
2582 d->views_.remove(gv->id());
2583 if (current_view_ == gv)
2588 bool GuiApplication::closeAllViews()
2590 if (d->views_.empty())
2593 // When a view/window was closed before without quitting LyX, there
2594 // are already entries in the lastOpened list.
2595 theSession().lastOpened().clear();
2597 QList<GuiView *> const views = d->views_.values();
2598 foreach (GuiView * view, views) {
2599 if (!view->closeScheduled())
2608 GuiView & GuiApplication::view(int id) const
2610 LAPPERR(d->views_.contains(id));
2611 return *d->views_.value(id);
2615 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2617 QList<GuiView *> const views = d->views_.values();
2618 foreach (GuiView * view, views)
2619 view->hideDialog(name, inset);
2623 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2625 Buffer const * buffer_ = 0;
2626 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2627 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2628 if (Buffer const * ptr = (*it)->updateInset(inset))
2635 bool GuiApplication::searchMenu(FuncRequest const & func,
2636 docstring_list & names) const
2638 return d->menus_.searchMenu(func, names);
2642 // Ensure that a file is read only once (prevents include loops)
2643 static QStringList uifiles;
2644 // store which ui files define Toolbars
2645 static QStringList toolbar_uifiles;
2648 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2659 LexerKeyword uitags[] = {
2660 { "format", ui_format },
2661 { "include", ui_include },
2662 { "menuset", ui_menuset },
2663 { "toolbars", ui_toolbars },
2664 { "toolbarset", ui_toolbarset }
2668 lex.setFile(ui_path);
2670 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2674 if (lyxerr.debugging(Debug::PARSER))
2675 lex.printTable(lyxerr);
2678 // format before introduction of format tag
2679 unsigned int format = 0;
2680 while (lex.isOK()) {
2681 int const status = lex.lex();
2683 // we have to do this check here, outside the switch,
2684 // because otherwise we would start reading include files,
2685 // e.g., if the first tag we hit was an include tag.
2686 if (status == ui_format)
2688 format = lex.getInteger();
2692 // this will trigger unless the first tag we hit is a format
2693 // tag, with the right format.
2694 if (format != LFUN_FORMAT)
2695 return FormatMismatch;
2698 case Lexer::LEX_FEOF:
2703 QString const file = toqstr(lex.getString());
2704 bool const success = readUIFile(file, true);
2706 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2713 d->menus_.read(lex);
2717 d->toolbars_.readToolbars(lex);
2721 d->toolbars_.readToolbarSettings(lex);
2722 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2726 if (!rtrim(lex.getString()).empty())
2727 lex.printError("LyX::ReadUIFile: "
2728 "Unknown menu tag: `$$Token'");
2730 LYXERR0("Error with status: " << status);
2736 return (error ? ReadError : ReadOK);
2740 bool GuiApplication::readUIFile(QString const & name, bool include)
2742 LYXERR(Debug::INIT, "About to read " << name << "...");
2746 ui_path = libFileSearch("ui", name, "inc");
2747 if (ui_path.empty())
2748 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2750 ui_path = libFileSearch("ui", name, "ui");
2753 if (ui_path.empty()) {
2754 static const QString defaultUIFile = "default";
2755 LYXERR(Debug::INIT, "Could not find " << name);
2757 Alert::warning(_("Could not find UI definition file"),
2758 bformat(_("Error while reading the included file\n%1$s\n"
2759 "Please check your installation."), qstring_to_ucs4(name)));
2762 if (name == defaultUIFile) {
2763 LYXERR(Debug::INIT, "Could not find default UI file!!");
2764 Alert::warning(_("Could not find default UI file"),
2765 _("LyX could not find the default UI file!\n"
2766 "Please check your installation."));
2769 Alert::warning(_("Could not find UI definition file"),
2770 bformat(_("Error while reading the configuration file\n%1$s\n"
2771 "Falling back to default.\n"
2772 "Please look under Tools>Preferences>User Interface and\n"
2773 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2774 return readUIFile(defaultUIFile, false);
2777 QString const uifile = toqstr(ui_path.absFileName());
2778 if (uifiles.contains(uifile)) {
2780 // We are reading again the top uifile so reset the safeguard:
2783 d->toolbars_.reset();
2785 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2786 << "Is this an include loop?");
2790 uifiles.push_back(uifile);
2792 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2794 ReturnValues retval = readUIFile(ui_path);
2796 if (retval == FormatMismatch) {
2797 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2798 FileName const tempfile = FileName::tempName("convert_ui");
2799 bool const success = prefs2prefs(ui_path, tempfile, true);
2801 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2802 " to format " << LFUN_FORMAT << ".");
2804 retval = readUIFile(tempfile);
2805 tempfile.removeFile();
2809 if (retval != ReadOK) {
2810 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2818 settings.beginGroup("ui_files");
2819 bool touched = false;
2820 for (int i = 0; i != uifiles.size(); ++i) {
2821 QFileInfo fi(uifiles[i]);
2822 QDateTime const date_value = fi.lastModified();
2823 QString const name_key = QString::number(i);
2824 // if an ui file which defines Toolbars has changed,
2825 // we have to reset the settings
2826 if (toolbar_uifiles.contains(uifiles[i])
2827 && (!settings.contains(name_key)
2828 || settings.value(name_key).toString() != uifiles[i]
2829 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2831 settings.setValue(name_key, uifiles[i]);
2832 settings.setValue(name_key + "/date", date_value);
2835 settings.endGroup();
2837 settings.remove("views");
2843 void GuiApplication::onLastWindowClosed()
2845 if (d->global_menubar_)
2846 d->global_menubar_->grabKeyboard();
2850 void GuiApplication::startLongOperation() {
2851 d->key_checker_.start();
2855 bool GuiApplication::longOperationCancelled() {
2856 return d->key_checker_.pressed();
2860 void GuiApplication::stopLongOperation() {
2861 d->key_checker_.stop();
2865 bool GuiApplication::longOperationStarted() {
2866 return d->key_checker_.started();
2870 ////////////////////////////////////////////////////////////////////////
2872 // X11 specific stuff goes here...
2875 bool GuiApplication::x11EventFilter(XEvent * xev)
2880 switch (xev->type) {
2881 case SelectionRequest: {
2882 if (xev->xselectionrequest.selection != XA_PRIMARY)
2884 LYXERR(Debug::SELECTION, "X requested selection.");
2885 BufferView * bv = current_view_->currentBufferView();
2887 docstring const sel = bv->requestSelection();
2889 d->selection_.put(sel);
2893 case SelectionClear: {
2894 if (xev->xselectionclear.selection != XA_PRIMARY)
2896 LYXERR(Debug::SELECTION, "Lost selection.");
2897 BufferView * bv = current_view_->currentBufferView();
2899 bv->clearSelection();
2907 } // namespace frontend
2910 void hideDialogs(std::string const & name, Inset * inset)
2913 frontend::guiApp->hideDialogs(name, inset);
2917 ////////////////////////////////////////////////////////////////////
2921 ////////////////////////////////////////////////////////////////////
2923 frontend::FontLoader & theFontLoader()
2925 LAPPERR(frontend::guiApp);
2926 return frontend::guiApp->fontLoader();
2930 frontend::FontMetrics const & theFontMetrics(Font const & f)
2932 return theFontMetrics(f.fontInfo());
2936 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2938 LAPPERR(frontend::guiApp);
2939 return frontend::guiApp->fontLoader().metrics(f);
2943 ////////////////////////////////////////////////////////////////////
2947 ////////////////////////////////////////////////////////////////////
2949 frontend::Clipboard & theClipboard()
2951 LAPPERR(frontend::guiApp);
2952 return frontend::guiApp->clipboard();
2956 frontend::Selection & theSelection()
2958 LAPPERR(frontend::guiApp);
2959 return frontend::guiApp->selection();
2965 #include "moc_GuiApplication.cpp"