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 case QEvent::UpdateRequest:
855 case QEvent::CursorChange:
856 case QEvent::ActionChanged:
857 case QEvent::EnabledChange:
858 case QEvent::SockAct:
861 case QEvent::ToolTipChange:
862 case QEvent::LayoutRequest:
863 case QEvent::MetaCall:
864 return QObject::eventFilter(obj, event);
866 // FIXME Blocking all these events is a bad idea.
867 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
868 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
876 ////////////////////////////////////////////////////////////////////////
877 // GuiApplication::Private definition and implementation.
878 ////////////////////////////////////////////////////////////////////////
880 struct GuiApplication::Private
882 Private(): language_model_(0), meta_fake_bit(NoModifier),
886 /// WMF Mime handler for Windows clipboard.
887 wmf_mime_ = new QWindowsMimeMetafile;
889 initKeySequences(&theTopLevelKeymap());
892 void initKeySequences(KeyMap * kb)
894 keyseq = KeySequence(kb, kb);
895 cancel_meta_seq = KeySequence(kb, kb);
899 QSortFilterProxyModel * language_model_;
901 GuiClipboard clipboard_;
903 GuiSelection selection_;
905 FontLoader font_loader_;
907 ColorCache color_cache_;
909 QTranslator qt_trans_;
911 QHash<int, SocketNotifier *> socket_notifiers_;
915 /// The global instance
918 /// this timer is used for any regular events one wants to
919 /// perform. at present it is used to check if forked processes
921 QTimer general_timer_;
923 /// delayed FuncRequests
924 std::queue<FuncRequest> func_request_queue_;
929 KeySequence cancel_meta_seq;
931 KeyModifier meta_fake_bit;
933 /// Multiple views container.
935 * Warning: This must not be a smart pointer as the destruction of the
936 * object is handled by Qt when the view is closed
937 * \sa Qt::WA_DeleteOnClose attribute.
939 QHash<int, GuiView *> views_;
941 /// Only used on mac.
942 GlobalMenuBar * global_menubar_;
945 /// Linkback mime handler for MacOSX.
946 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
950 /// WMF Mime handler for Windows clipboard.
951 QWindowsMimeMetafile * wmf_mime_;
954 /// Allows to check whether ESC was pressed during a long operation
955 KeyChecker key_checker_;
959 GuiApplication * guiApp;
961 GuiApplication::~GuiApplication()
964 closeAllLinkBackLinks();
970 GuiApplication::GuiApplication(int & argc, char ** argv)
971 : QApplication(argc, argv), current_view_(0),
972 d(new GuiApplication::Private)
974 QString app_name = "LyX";
975 QCoreApplication::setOrganizationName(app_name);
976 QCoreApplication::setOrganizationDomain("lyx.org");
977 QCoreApplication::setApplicationName(lyx_package);
979 qsrand(QDateTime::currentDateTime().toTime_t());
981 // Install translator for GUI elements.
982 installTranslator(&d->qt_trans_);
984 // FIXME: quitOnLastWindowClosed is true by default. We should have a
985 // lyxrc setting for this in order to let the application stay resident.
986 // But then we need some kind of dock icon, at least on Windows.
988 if (lyxrc.quit_on_last_window_closed)
989 setQuitOnLastWindowClosed(false);
992 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
993 // seems to be the default case for applications like LyX.
994 setQuitOnLastWindowClosed(false);
995 // This allows to translate the strings that appear in the LyX menu.
996 /// A translator suitable for the entries in the LyX menu.
997 /// Only needed with Qt/Mac.
998 installTranslator(new MenuTranslator(this));
1004 // doubleClickInterval() is 400 ms on X11 which is just too long.
1005 // On Windows and Mac OS X, the operating system's value is used.
1006 // On Microsoft Windows, calling this function sets the double
1007 // click interval for all applications. So we don't!
1008 QApplication::setDoubleClickInterval(300);
1011 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1013 // needs to be done before reading lyxrc
1015 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1019 // Set the cache to 5120 kilobytes which corresponds to screen size of
1020 // 1280 by 1024 pixels with a color depth of 32 bits.
1021 QPixmapCache::setCacheLimit(5120);
1023 // Initialize RC Fonts
1024 if (lyxrc.roman_font_name.empty())
1025 lyxrc.roman_font_name = fromqstr(romanFontName());
1027 if (lyxrc.sans_font_name.empty())
1028 lyxrc.sans_font_name = fromqstr(sansFontName());
1030 if (lyxrc.typewriter_font_name.empty())
1031 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1033 d->general_timer_.setInterval(500);
1034 connect(&d->general_timer_, SIGNAL(timeout()),
1035 this, SLOT(handleRegularEvents()));
1036 d->general_timer_.start();
1038 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1039 // This is clearly not enough in a time where we use threads for
1040 // document preview and/or export. 20 should be OK.
1041 QThreadPool::globalInstance()->setMaxThreadCount(20);
1045 GuiApplication * theGuiApp()
1047 return dynamic_cast<GuiApplication *>(theApp());
1051 void GuiApplication::clearSession()
1058 docstring Application::iconName(FuncRequest const & f, bool unknown)
1060 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1064 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1068 BufferView * bv = 0;
1069 BufferView * doc_bv = 0;
1071 if (cmd.action() == LFUN_NOACTION) {
1072 status.message(from_utf8(N_("Nothing to do")));
1073 status.setEnabled(false);
1076 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1077 status.setUnknown(true);
1078 status.message(from_utf8(N_("Unknown action")));
1079 status.setEnabled(false);
1082 // Does the GuiApplication know something?
1083 else if (getStatus(cmd, status)) { }
1085 // If we do not have a GuiView, then other functions are disabled
1086 else if (!current_view_)
1087 status.setEnabled(false);
1089 // Does the GuiView know something?
1090 else if (current_view_->getStatus(cmd, status)) { }
1092 // In LyX/Mac, when a dialog is open, the menus of the
1093 // application can still be accessed without giving focus to
1094 // the main window. In this case, we want to disable the menu
1095 // entries that are buffer or view-related.
1096 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1098 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1099 status.setEnabled(false);
1102 // If we do not have a BufferView, then other functions are disabled
1103 else if (!(bv = current_view_->currentBufferView()))
1104 status.setEnabled(false);
1106 // Does the current BufferView know something?
1107 else if (bv->getStatus(cmd, status)) { }
1109 // Does the current Buffer know something?
1110 else if (bv->buffer().getStatus(cmd, status)) { }
1112 // If we do not have a document BufferView, different from the
1113 // current BufferView, then other functions are disabled
1114 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1115 status.setEnabled(false);
1117 // Does the document Buffer know something?
1118 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1121 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1122 status.message(from_utf8(N_("Command not handled")));
1123 status.setEnabled(false);
1126 // the default error message if we disable the command
1127 if (!status.enabled() && status.message().empty())
1128 status.message(from_utf8(N_("Command disabled")));
1134 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1136 // I would really like to avoid having this switch and rather try to
1137 // encode this in the function itself.
1138 // -- And I'd rather let an inset decide which LFUNs it is willing
1139 // to handle (Andre')
1141 switch (cmd.action()) {
1143 // This could be used for the no-GUI version. The GUI version is handled in
1144 // GuiView::getStatus(). See above.
1146 case LFUN_BUFFER_WRITE:
1147 case LFUN_BUFFER_WRITE_AS: {
1148 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1149 enable = b && (b->isUnnamed() || !b->isClean());
1154 case LFUN_BOOKMARK_GOTO: {
1155 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1156 enable = theSession().bookmarks().isValid(num);
1160 case LFUN_BOOKMARK_CLEAR:
1161 enable = theSession().bookmarks().hasValid();
1164 // this one is difficult to get right. As a half-baked
1165 // solution, we consider only the first action of the sequence
1166 case LFUN_COMMAND_SEQUENCE: {
1167 // argument contains ';'-terminated commands
1168 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1169 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1170 func.setOrigin(cmd.origin());
1171 flag = getStatus(func);
1175 // we want to check if at least one of these is enabled
1176 case LFUN_COMMAND_ALTERNATIVES: {
1177 // argument contains ';'-terminated commands
1178 string arg = to_utf8(cmd.argument());
1179 while (!arg.empty()) {
1181 arg = split(arg, first, ';');
1182 FuncRequest func(lyxaction.lookupFunc(first));
1183 func.setOrigin(cmd.origin());
1184 flag = getStatus(func);
1185 // if this one is enabled, the whole thing is
1194 string name = to_utf8(cmd.argument());
1195 if (theTopLevelCmdDef().lock(name, func)) {
1196 func.setOrigin(cmd.origin());
1197 flag = getStatus(func);
1198 theTopLevelCmdDef().release(name);
1200 // catch recursion or unknown command
1201 // definition. all operations until the
1202 // recursion or unknown command definition
1203 // occurs are performed, so set the state to
1210 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1212 case LFUN_PREFERENCES_SAVE:
1213 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1214 case LFUN_DEBUG_LEVEL_SET:
1215 // these are handled in our dispatch()
1218 case LFUN_WINDOW_CLOSE:
1219 enable = d->views_.size() > 0;
1222 case LFUN_BUFFER_NEW:
1223 case LFUN_BUFFER_NEW_TEMPLATE:
1224 case LFUN_FILE_OPEN:
1225 case LFUN_HELP_OPEN:
1226 case LFUN_SCREEN_FONT_UPDATE:
1227 case LFUN_SET_COLOR:
1228 case LFUN_WINDOW_NEW:
1230 case LFUN_LYXRC_APPLY:
1231 case LFUN_COMMAND_PREFIX:
1233 case LFUN_META_PREFIX:
1234 case LFUN_RECONFIGURE:
1235 case LFUN_SERVER_GET_FILENAME:
1236 case LFUN_SERVER_NOTIFY:
1240 case LFUN_BUFFER_FORALL: {
1241 if (theBufferList().empty()) {
1242 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1243 flag.setEnabled(false);
1247 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1248 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1249 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1250 flag.setEnabled(false);
1255 case LFUN_DIALOG_SHOW: {
1256 string const name = cmd.getArg(0);
1257 return name == "aboutlyx"
1259 || name == "texinfo"
1260 || name == "progress"
1261 || name == "compare";
1269 flag.setEnabled(false);
1273 /// make a post-dispatch status message
1274 static docstring makeDispatchMessage(docstring const & msg,
1275 FuncRequest const & cmd)
1277 const bool verbose = (cmd.origin() == FuncRequest::MENU
1278 || cmd.origin() == FuncRequest::TOOLBAR
1279 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1281 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1282 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1286 docstring dispatch_msg = msg;
1287 if (!dispatch_msg.empty())
1288 dispatch_msg += ' ';
1290 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1292 bool argsadded = false;
1294 if (!cmd.argument().empty()) {
1295 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1296 comname += ' ' + cmd.argument();
1300 docstring const shortcuts = theTopLevelKeymap().
1301 printBindings(cmd, KeySequence::ForGui);
1303 if (!shortcuts.empty())
1304 comname += ": " + shortcuts;
1305 else if (!argsadded && !cmd.argument().empty())
1306 comname += ' ' + cmd.argument();
1308 if (!comname.empty()) {
1309 comname = rtrim(comname);
1310 dispatch_msg += '(' + rtrim(comname) + ')';
1312 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1313 return dispatch_msg;
1317 void GuiApplication::dispatch(FuncRequest const & cmd)
1319 Buffer * buffer = 0;
1320 if (current_view_ && current_view_->currentBufferView()) {
1321 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1322 buffer = ¤t_view_->currentBufferView()->buffer();
1324 buffer->undo().beginUndoGroup();
1328 // redraw the screen at the end (first of the two drawing steps).
1329 // This is done unless explicitly requested otherwise
1330 dr.screenUpdate(Update::FitCursor);
1332 updateCurrentView(cmd, dr);
1334 // the buffer may have been closed by one action
1335 if (theBufferList().isLoaded(buffer))
1336 buffer->undo().endUndoGroup();
1340 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1345 BufferView * bv = current_view_->currentBufferView();
1347 if (dr.needBufferUpdate()) {
1348 bv->cursor().clearBufferUpdate();
1349 bv->buffer().updateBuffer();
1351 // BufferView::update() updates the ViewMetricsInfo and
1352 // also initializes the position cache for all insets in
1353 // (at least partially) visible top-level paragraphs.
1354 // We will redraw the screen only if needed.
1355 bv->processUpdateFlags(dr.screenUpdate());
1357 // Do we have a selection?
1358 theSelection().haveSelection(bv->cursor().selection());
1361 current_view_->restartCursor();
1363 if (dr.needMessageUpdate()) {
1364 // Some messages may already be translated, so we cannot use _()
1365 current_view_->message(makeDispatchMessage(
1366 translateIfPossible(dr.message()), cmd));
1371 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1372 bool switchToBuffer)
1374 if (!theSession().bookmarks().isValid(idx))
1376 BookmarksSection::Bookmark const & bm =
1377 theSession().bookmarks().bookmark(idx);
1378 LASSERT(!bm.filename.empty(), return);
1379 string const file = bm.filename.absFileName();
1380 // if the file is not opened, open it.
1381 if (!theBufferList().exists(bm.filename)) {
1383 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1387 // open may fail, so we need to test it again
1388 if (!theBufferList().exists(bm.filename))
1391 // bm can be changed when saving
1392 BookmarksSection::Bookmark tmp = bm;
1394 // Special case idx == 0 used for back-from-back jump navigation
1396 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1398 // if the current buffer is not that one, switch to it.
1399 BufferView * doc_bv = current_view_ ?
1400 current_view_->documentBufferView() : 0;
1401 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1402 if (switchToBuffer) {
1403 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1406 doc_bv = current_view_->documentBufferView();
1411 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1412 if (!doc_bv->moveToPosition(
1413 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1420 // Cursor jump succeeded!
1421 Cursor const & cur = doc_bv->cursor();
1422 pit_type new_pit = cur.pit();
1423 pos_type new_pos = cur.pos();
1424 int new_id = cur.paragraph().id();
1426 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1427 // see http://www.lyx.org/trac/ticket/3092
1428 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1429 || bm.top_id != new_id) {
1430 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1431 new_pit, new_pos, new_id);
1435 // This function runs "configure" and then rereads lyx.defaults to
1436 // reconfigure the automatic settings.
1437 void GuiApplication::reconfigure(string const & option)
1439 // emit message signal.
1441 current_view_->message(_("Running configure..."));
1443 // Run configure in user lyx directory
1444 PathChanger p(package().user_support());
1445 string configure_command = package().configure_command();
1446 configure_command += option;
1448 int const ret = one.startscript(Systemcall::Wait, configure_command);
1450 // emit message signal.
1452 current_view_->message(_("Reloading configuration..."));
1453 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1454 // Re-read packages.lst
1455 LaTeXPackages::getAvailable();
1458 Alert::information(_("System reconfiguration failed"),
1459 _("The system reconfiguration has failed.\n"
1460 "Default textclass is used but LyX may\n"
1461 "not be able to work properly.\n"
1462 "Please reconfigure again if needed."));
1464 Alert::information(_("System reconfigured"),
1465 _("The system has been reconfigured.\n"
1466 "You need to restart LyX to make use of any\n"
1467 "updated document class specifications."));
1470 void GuiApplication::validateCurrentView()
1472 if (!d->views_.empty() && !current_view_) {
1473 // currently at least one view exists but no view has the focus.
1474 // choose the last view to make it current.
1475 // a view without any open document is preferred.
1476 GuiView * candidate = 0;
1477 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1478 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1479 for (; it != end; ++it) {
1481 if (!candidate->documentBufferView())
1484 setCurrentView(candidate);
1488 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1490 string const argument = to_utf8(cmd.argument());
1491 FuncCode const action = cmd.action();
1493 LYXERR(Debug::ACTION, "cmd: " << cmd);
1495 // we have not done anything wrong yet.
1498 FuncStatus const flag = getStatus(cmd);
1499 if (!flag.enabled()) {
1500 // We cannot use this function here
1501 LYXERR(Debug::ACTION, "action "
1502 << lyxaction.getActionName(action)
1503 << " [" << action << "] is disabled at this location");
1504 dr.setMessage(flag.message());
1506 dr.dispatched(false);
1507 dr.screenUpdate(Update::None);
1508 dr.clearBufferUpdate();
1512 if (cmd.origin() == FuncRequest::LYXSERVER) {
1513 if (current_view_ && current_view_->currentBufferView())
1514 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1515 // we will also need to redraw the screen at the end
1516 dr.screenUpdate(Update::FitCursor);
1519 // Assumes that the action will be dispatched.
1520 dr.dispatched(true);
1522 switch (cmd.action()) {
1524 case LFUN_WINDOW_NEW:
1525 createView(toqstr(cmd.argument()));
1528 case LFUN_WINDOW_CLOSE:
1529 // update bookmark pit of the current buffer before window close
1530 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1531 gotoBookmark(i+1, false, false);
1532 // clear the last opened list, because
1533 // maybe this will end the session
1534 theSession().lastOpened().clear();
1535 // check for valid current_view_
1536 validateCurrentView();
1538 current_view_->closeScheduled();
1542 // quitting is triggered by the gui code
1543 // (leaving the event loop).
1545 current_view_->message(from_utf8(N_("Exiting.")));
1546 if (closeAllViews())
1550 case LFUN_SCREEN_FONT_UPDATE: {
1551 // handle the screen font changes.
1552 d->font_loader_.update();
1553 // Backup current_view_
1554 GuiView * view = current_view_;
1555 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1556 // to skip the refresh.
1558 theBufferList().changed(false);
1559 // Restore current_view_
1560 current_view_ = view;
1564 case LFUN_BUFFER_NEW:
1565 validateCurrentView();
1566 if (d->views_.empty()
1567 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1568 createView(QString(), false); // keep hidden
1569 current_view_->newDocument(to_utf8(cmd.argument()), false);
1570 current_view_->show();
1571 setActiveWindow(current_view_);
1573 current_view_->newDocument(to_utf8(cmd.argument()), false);
1577 case LFUN_BUFFER_NEW_TEMPLATE:
1578 validateCurrentView();
1579 if (d->views_.empty()
1580 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1582 current_view_->newDocument(to_utf8(cmd.argument()), true);
1583 if (!current_view_->documentBufferView())
1584 current_view_->close();
1586 current_view_->newDocument(to_utf8(cmd.argument()), true);
1590 case LFUN_FILE_OPEN: {
1591 validateCurrentView();
1592 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1593 string const fname = to_utf8(cmd.argument());
1594 if (!FileName::isAbsolute(fname)) {
1596 dr.setMessage(_("Absolute filename expected."));
1599 bool const is_open = theBufferList().getBuffer(FileName(fname));
1600 if (d->views_.empty()
1601 || (!lyxrc.open_buffers_in_tabs
1602 && current_view_->documentBufferView() != 0
1604 // We want the ui session to be saved per document and not per
1605 // window number. The filename crc is a good enough identifier.
1606 boost::crc_32_type crc;
1607 crc = for_each(fname.begin(), fname.end(), crc);
1608 createView(crc.checksum());
1609 current_view_->openDocument(fname);
1610 if (current_view_ && !current_view_->documentBufferView())
1611 current_view_->close();
1613 current_view_->openDocument(fname);
1617 case LFUN_HELP_OPEN: {
1618 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1619 if (current_view_ == 0)
1621 string const arg = to_utf8(cmd.argument());
1623 current_view_->message(_("Missing argument"));
1626 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1628 fname = i18nLibFileSearch("examples", arg, "lyx");
1630 if (fname.empty()) {
1631 lyxerr << "LyX: unable to find documentation file `"
1632 << arg << "'. Bad installation?" << endl;
1635 current_view_->message(bformat(_("Opening help file %1$s..."),
1636 makeDisplayPath(fname.absFileName())));
1637 Buffer * buf = current_view_->loadDocument(fname, false);
1639 #ifndef DEVEL_VERSION
1641 buf->setReadonly(true);
1648 case LFUN_SET_COLOR: {
1650 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1651 if (lyx_name.empty() || x11_name.empty()) {
1653 current_view_->message(
1654 _("Syntax: set-color <lyx_name> <x11_name>"));
1659 // FIXME: The graphics cache no longer has a changeDisplay method.
1660 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1661 bool const graphicsbg_changed =
1662 lyx_name == graphicsbg && x11_name != graphicsbg;
1663 if (graphicsbg_changed)
1664 graphics::GCache::get().changeDisplay(true);
1667 if (!lcolor.setColor(lyx_name, x11_name)) {
1669 current_view_->message(
1670 bformat(_("Set-color \"%1$s\" failed "
1671 "- color is undefined or "
1672 "may not be redefined"),
1673 from_utf8(lyx_name)));
1676 // Make sure we don't keep old colors in cache.
1677 d->color_cache_.clear();
1681 case LFUN_LYXRC_APPLY: {
1682 // reset active key sequences, since the bindings
1683 // are updated (bug 6064)
1685 LyXRC const lyxrc_orig = lyxrc;
1687 istringstream ss(to_utf8(cmd.argument()));
1688 bool const success = lyxrc.read(ss);
1691 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1692 << "Unable to read lyxrc data"
1697 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1699 // If the request comes from the minibuffer, then we can't reset
1700 // the GUI, since that would destory the minibuffer itself and
1701 // cause a crash, since we are currently in one of the methods of
1702 // GuiCommandBuffer. See bug #8540.
1703 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1706 // FIXME Unfortunately, that leaves a bug here, since we cannot
1707 // reset the GUI in this case. If the changes to lyxrc affected the
1708 // UI, then, nothing would happen. This seems fairly unlikely, but
1709 // it definitely is a bug.
1714 case LFUN_COMMAND_PREFIX:
1715 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1720 d->meta_fake_bit = NoModifier;
1721 GuiView * gv = currentView();
1722 if (gv && gv->currentBufferView())
1723 // cancel any selection
1724 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1725 dr.setMessage(from_ascii(N_("Cancel")));
1728 case LFUN_META_PREFIX:
1729 d->meta_fake_bit = AltModifier;
1730 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1733 // --- Menus -----------------------------------------------
1734 case LFUN_RECONFIGURE:
1735 // argument is any additional parameter to the configure.py command
1736 reconfigure(to_utf8(cmd.argument()));
1739 // --- lyxserver commands ----------------------------
1740 case LFUN_SERVER_GET_FILENAME: {
1741 if (current_view_ && current_view_->documentBufferView()) {
1742 docstring const fname = from_utf8(
1743 current_view_->documentBufferView()->buffer().absFileName());
1744 dr.setMessage(fname);
1745 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1747 dr.setMessage(docstring());
1748 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1753 case LFUN_SERVER_NOTIFY: {
1754 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1755 dr.setMessage(dispatch_buffer);
1756 theServer().notifyClient(to_utf8(dispatch_buffer));
1760 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1761 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1767 string rest = split(argument, countstr, ' ');
1768 istringstream is(countstr);
1771 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1772 for (int i = 0; i < count; ++i)
1773 dispatch(lyxaction.lookupFunc(rest));
1777 case LFUN_COMMAND_SEQUENCE: {
1778 // argument contains ';'-terminated commands
1779 string arg = argument;
1780 // FIXME: this LFUN should also work without any view.
1781 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1782 ? &(current_view_->documentBufferView()->buffer()) : 0;
1784 buffer->undo().beginUndoGroup();
1785 while (!arg.empty()) {
1787 arg = split(arg, first, ';');
1788 FuncRequest func(lyxaction.lookupFunc(first));
1789 func.setOrigin(cmd.origin());
1792 // the buffer may have been closed by one action
1793 if (theBufferList().isLoaded(buffer))
1794 buffer->undo().endUndoGroup();
1798 case LFUN_BUFFER_FORALL: {
1799 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1801 map<Buffer *, GuiView *> views_lVisible;
1802 map<GuiView *, Buffer *> activeBuffers;
1804 QList<GuiView *> allViews = d->views_.values();
1806 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1807 // and on which buffer is active in each view.
1808 Buffer * const last = theBufferList().last();
1809 foreach (GuiView * view, allViews) {
1810 // all of the buffers might be locally hidden. That is, there is no active buffer.
1811 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1812 activeBuffers[view] = 0;
1814 activeBuffers[view] = &view->currentBufferView()->buffer();
1816 // find out if each is locally visible or locally hidden.
1817 // we don't use a for loop as the buffer list cycles.
1818 Buffer * b = theBufferList().first();
1820 bool const locallyVisible = view && view->workArea(*b);
1821 if (locallyVisible) {
1822 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1823 // only need to overwrite/add if we don't already know a buffer is globally
1824 // visible or we do know but we would prefer to dispatch LFUN from the
1825 // current view because of cursor position issues.
1826 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1827 views_lVisible[b] = view;
1831 b = theBufferList().next(b);
1835 GuiView * const homeView = currentView();
1836 Buffer * b = theBufferList().first();
1837 Buffer * nextBuf = 0;
1838 int numProcessed = 0;
1841 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1843 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1845 // first change to a view where b is locally visible, preferably current_view_.
1846 GuiView * const vLv = views_lVisible[b];
1848 lyx::dispatch(funcToRun);
1856 // put things back to how they were (if possible).
1857 foreach (GuiView * view, allViews) {
1858 Buffer * originalBuf = activeBuffers[view];
1859 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1860 if (theBufferList().isLoaded(originalBuf))
1861 view->setBuffer(originalBuf);
1863 homeView->setFocus();
1865 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1869 case LFUN_COMMAND_ALTERNATIVES: {
1870 // argument contains ';'-terminated commands
1871 string arg = argument;
1872 while (!arg.empty()) {
1874 arg = split(arg, first, ';');
1875 FuncRequest func(lyxaction.lookupFunc(first));
1876 func.setOrigin(cmd.origin());
1877 FuncStatus const stat = getStatus(func);
1878 if (stat.enabled()) {
1888 if (theTopLevelCmdDef().lock(argument, func)) {
1889 func.setOrigin(cmd.origin());
1891 theTopLevelCmdDef().release(argument);
1893 if (func.action() == LFUN_UNKNOWN_ACTION) {
1894 // unknown command definition
1895 lyxerr << "Warning: unknown command definition `"
1899 // recursion detected
1900 lyxerr << "Warning: Recursion in the command definition `"
1901 << argument << "' detected"
1908 case LFUN_PREFERENCES_SAVE:
1909 lyxrc.write(support::makeAbsPath("preferences",
1910 package().user_support().absFileName()), false);
1913 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1914 string const fname = addName(addPath(package().user_support().absFileName(),
1915 "templates/"), "defaults.lyx");
1916 Buffer defaults(fname);
1918 istringstream ss(argument);
1921 int const unknown_tokens = defaults.readHeader(lex);
1923 if (unknown_tokens != 0) {
1924 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1925 << unknown_tokens << " unknown token"
1926 << (unknown_tokens == 1 ? "" : "s")
1930 if (defaults.writeFile(FileName(defaults.absFileName())))
1931 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1932 makeDisplayPath(fname)));
1935 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1940 case LFUN_BOOKMARK_GOTO:
1941 // go to bookmark, open unopened file and switch to buffer if necessary
1942 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1943 dr.screenUpdate(Update::Force | Update::FitCursor);
1946 case LFUN_BOOKMARK_CLEAR:
1947 theSession().bookmarks().clear();
1950 case LFUN_DEBUG_LEVEL_SET:
1951 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1954 case LFUN_DIALOG_SHOW: {
1955 string const name = cmd.getArg(0);
1957 if ( name == "aboutlyx"
1959 || name == "texinfo"
1960 || name == "progress"
1961 || name == "compare")
1963 // work around: on Mac OS the application
1964 // is not terminated when closing the last view.
1965 // Create a new one to be able to dispatch the
1966 // LFUN_DIALOG_SHOW to this view.
1967 if (current_view_ == 0)
1973 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1976 current_view_->dispatch(cmd, dr);
1980 if (cmd.origin() == FuncRequest::LYXSERVER)
1981 updateCurrentView(cmd, dr);
1985 docstring GuiApplication::viewStatusMessage()
1987 // When meta-fake key is pressed, show the key sequence so far + "M-".
1988 if (d->meta_fake_bit != NoModifier)
1989 return d->keyseq.print(KeySequence::ForGui) + "M-";
1991 // Else, when a non-complete key sequence is pressed,
1992 // show the available options.
1993 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1994 return d->keyseq.printOptions(true);
2000 void GuiApplication::handleKeyFunc(FuncCode action)
2004 if (d->keyseq.length())
2006 GuiView * gv = currentView();
2007 LASSERT(gv && gv->currentBufferView(), return);
2008 BufferView * bv = gv->currentBufferView();
2009 bv->getIntl().getTransManager().deadkey(
2010 c, get_accent(action).accent, bv->cursor().innerText(),
2012 // Need to clear, in case the minibuffer calls these
2015 // copied verbatim from do_accent_char
2016 bv->cursor().resetAnchor();
2020 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2022 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2024 // Do nothing if we have nothing (JMarc)
2025 if (!keysym.isOK()) {
2026 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2028 current_view_->restartCursor();
2032 if (keysym.isModifier()) {
2034 current_view_->restartCursor();
2038 char_type encoded_last_key = keysym.getUCSEncoded();
2040 // Do a one-deep top-level lookup for
2041 // cancel and meta-fake keys. RVDK_PATCH_5
2042 d->cancel_meta_seq.reset();
2044 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2045 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2047 // When not cancel or meta-fake, do the normal lookup.
2048 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2049 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2050 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2051 // remove Caps Lock and Mod2 as a modifiers
2052 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2053 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2056 // Dont remove this unless you know what you are doing.
2057 d->meta_fake_bit = NoModifier;
2059 // Can this happen now ?
2060 if (func.action() == LFUN_NOACTION)
2061 func = FuncRequest(LFUN_COMMAND_PREFIX);
2063 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2064 << d->keyseq.print(KeySequence::Portable) << ']');
2066 // already here we know if it any point in going further
2067 // why not return already here if action == -1 and
2068 // num_bytes == 0? (Lgb)
2070 if (d->keyseq.length() > 1 && current_view_)
2071 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2074 // Maybe user can only reach the key via holding down shift.
2075 // Let's see. But only if shift is the only modifier
2076 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2077 LYXERR(Debug::KEY, "Trying without shift");
2078 func = d->keyseq.addkey(keysym, NoModifier);
2079 LYXERR(Debug::KEY, "Action now " << func.action());
2082 if (func.action() == LFUN_UNKNOWN_ACTION) {
2083 // Hmm, we didn't match any of the keysequences. See
2084 // if it's normal insertable text not already covered
2086 if (keysym.isText() && d->keyseq.length() == 1) {
2087 LYXERR(Debug::KEY, "isText() is true, inserting.");
2088 func = FuncRequest(LFUN_SELF_INSERT,
2089 FuncRequest::KEYBOARD);
2091 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2092 if (current_view_) {
2093 current_view_->message(_("Unknown function."));
2094 current_view_->restartCursor();
2100 if (func.action() == LFUN_SELF_INSERT) {
2101 if (encoded_last_key != 0) {
2102 docstring const arg(1, encoded_last_key);
2103 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2104 FuncRequest::KEYBOARD));
2105 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2108 processFuncRequest(func);
2112 void GuiApplication::processFuncRequest(FuncRequest const & func)
2114 lyx::dispatch(func);
2118 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2120 addToFuncRequestQueue(func);
2121 processFuncRequestQueueAsync();
2125 void GuiApplication::processFuncRequestQueue()
2127 while (!d->func_request_queue_.empty()) {
2128 processFuncRequest(d->func_request_queue_.front());
2129 d->func_request_queue_.pop();
2134 void GuiApplication::processFuncRequestQueueAsync()
2136 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2140 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2142 d->func_request_queue_.push(func);
2146 void GuiApplication::resetGui()
2148 // Set the language defined by the user.
2152 if (!readUIFile(toqstr(lyxrc.ui_file)))
2153 // Gives some error box here.
2156 if (d->global_menubar_)
2157 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2159 QHash<int, GuiView *>::iterator it;
2160 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2163 gv->setLayoutDirection(layoutDirection());
2167 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2171 void GuiApplication::createView(int view_id)
2173 createView(QString(), true, view_id);
2177 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2180 // release the keyboard which might have been grabed by the global
2181 // menubar on Mac to catch shortcuts even without any GuiView.
2182 if (d->global_menubar_)
2183 d->global_menubar_->releaseKeyboard();
2187 while (d->views_.find(id) != d->views_.end())
2190 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2191 GuiView * view = new GuiView(id);
2193 d->views_[id] = view;
2197 setActiveWindow(view);
2200 if (!geometry_arg.isEmpty()) {
2204 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2205 re.indexIn(geometry_arg);
2206 w = re.cap(1).toInt();
2207 h = re.cap(2).toInt();
2208 x = re.cap(3).toInt();
2209 y = re.cap(4).toInt();
2210 view->setGeometry(x, y, w, h);
2217 Clipboard & GuiApplication::clipboard()
2219 return d->clipboard_;
2223 Selection & GuiApplication::selection()
2225 return d->selection_;
2229 FontLoader & GuiApplication::fontLoader()
2231 return d->font_loader_;
2235 Toolbars const & GuiApplication::toolbars() const
2237 return d->toolbars_;
2241 Toolbars & GuiApplication::toolbars()
2243 return d->toolbars_;
2247 Menus const & GuiApplication::menus() const
2253 Menus & GuiApplication::menus()
2259 QList<int> GuiApplication::viewIds() const
2261 return d->views_.keys();
2265 ColorCache & GuiApplication::colorCache()
2267 return d->color_cache_;
2271 int GuiApplication::exec()
2273 // asynchronously handle batch commands. This event will be in
2274 // the event queue in front of other asynchronous events. Hence,
2275 // we can assume in the latter that the gui is setup already.
2276 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2278 return QApplication::exec();
2282 void GuiApplication::exit(int status)
2284 QApplication::exit(status);
2288 void GuiApplication::setGuiLanguage()
2292 // install translation file for Qt built-in dialogs
2293 QString const language_name = QString("qt_") + theLocale.name();
2294 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2295 // Short-named translator can be loaded from a long name, but not the
2296 // opposite. Therefore, long name should be used without truncation.
2297 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2298 if (!d->qt_trans_.load(language_name,
2299 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2300 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2303 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2307 switch (theLocale.language()) {
2308 case QLocale::Arabic :
2309 case QLocale::Hebrew :
2310 case QLocale::Persian :
2311 case QLocale::Urdu :
2312 setLayoutDirection(Qt::RightToLeft);
2315 setLayoutDirection(Qt::LeftToRight);
2320 void GuiApplication::execBatchCommands()
2325 if (!readUIFile(toqstr(lyxrc.ui_file)))
2326 // Gives some error box here.
2330 #if QT_VERSION > 0x040600
2331 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2333 // Create the global default menubar which is shown for the dialogs
2334 // and if no GuiView is visible.
2335 // This must be done after the session was recovered to know the "last files".
2336 d->global_menubar_ = new GlobalMenuBar;
2337 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2340 lyx::execBatchCommands();
2344 QAbstractItemModel * GuiApplication::languageModel()
2346 if (d->language_model_)
2347 return d->language_model_;
2349 QStandardItemModel * lang_model = new QStandardItemModel(this);
2350 lang_model->insertColumns(0, 3);
2352 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2353 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2354 Languages::const_iterator it = lyx::languages.begin();
2355 Languages::const_iterator end = lyx::languages.end();
2356 for (; it != end; ++it) {
2357 current_row = lang_model->rowCount();
2358 lang_model->insertRows(current_row, 1);
2359 QModelIndex pl_item = lang_model->index(current_row, 0);
2360 QModelIndex sp_item = lang_model->index(current_row, 1);
2361 QModelIndex th_item = lang_model->index(current_row, 2);
2362 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2363 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2364 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2365 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2366 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2367 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2368 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2369 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2370 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2371 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2373 d->language_model_ = new QSortFilterProxyModel(this);
2374 d->language_model_->setSourceModel(lang_model);
2375 d->language_model_->setSortLocaleAware(true);
2376 return d->language_model_;
2380 void GuiApplication::restoreGuiSession()
2382 if (!lyxrc.load_session)
2385 Session & session = theSession();
2386 LastOpenedSection::LastOpened const & lastopened =
2387 session.lastOpened().getfiles();
2389 validateCurrentView();
2391 FileName active_file;
2392 // do not add to the lastfile list since these files are restored from
2393 // last session, and should be already there (regular files), or should
2394 // not be added at all (help files).
2395 for (size_t i = 0; i < lastopened.size(); ++i) {
2396 FileName const & file_name = lastopened[i].file_name;
2397 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2398 && current_view_->documentBufferView() != 0)) {
2399 boost::crc_32_type crc;
2400 string const & fname = file_name.absFileName();
2401 crc = for_each(fname.begin(), fname.end(), crc);
2402 createView(crc.checksum());
2404 current_view_->loadDocument(file_name, false);
2406 if (lastopened[i].active)
2407 active_file = file_name;
2410 // Restore last active buffer
2411 Buffer * buffer = theBufferList().getBuffer(active_file);
2412 if (buffer && current_view_)
2413 current_view_->setBuffer(buffer);
2415 // clear this list to save a few bytes of RAM
2416 session.lastOpened().clear();
2420 QString const GuiApplication::romanFontName()
2423 font.setKerning(false);
2424 font.setStyleHint(QFont::Serif);
2425 font.setFamily("serif");
2427 return QFontInfo(font).family();
2431 QString const GuiApplication::sansFontName()
2434 font.setKerning(false);
2435 font.setStyleHint(QFont::SansSerif);
2436 font.setFamily("sans");
2438 return QFontInfo(font).family();
2442 QString const GuiApplication::typewriterFontName()
2445 font.setKerning(false);
2446 font.setStyleHint(QFont::TypeWriter);
2447 font.setFamily("monospace");
2449 return QFontInfo(font).family();
2453 void GuiApplication::handleRegularEvents()
2455 ForkedCallsController::handleCompletedProcesses();
2459 bool GuiApplication::event(QEvent * e)
2462 case QEvent::FileOpen: {
2463 // Open a file; this happens only on Mac OS X for now.
2465 // We do this asynchronously because on startup the batch
2466 // commands are not executed here yet and the gui is not ready
2468 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2469 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2470 processFuncRequestAsync(fr);
2475 return QApplication::event(e);
2480 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2483 return QApplication::notify(receiver, event);
2485 catch (ExceptionMessage const & e) {
2487 case ErrorException:
2489 setQuitOnLastWindowClosed(false);
2491 Alert::error(e.title_, e.details_);
2493 // Properly crash in debug mode in order to get a useful backtrace.
2496 // In release mode, try to exit gracefully.
2499 case BufferException: {
2500 if (!current_view_ || !current_view_->documentBufferView())
2502 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2503 docstring details = e.details_ + '\n';
2504 details += buf->emergencyWrite();
2505 theBufferList().release(buf);
2506 details += "\n" + _("The current document was closed.");
2507 Alert::error(e.title_, details);
2510 case WarningException:
2511 Alert::warning(e.title_, e.details_);
2515 catch (exception const & e) {
2516 docstring s = _("LyX has caught an exception, it will now "
2517 "attempt to save all unsaved documents and exit."
2519 s += from_ascii(e.what());
2520 Alert::error(_("Software exception Detected"), s);
2524 docstring s = _("LyX has caught some really weird exception, it will "
2525 "now attempt to save all unsaved documents and exit.");
2526 Alert::error(_("Software exception Detected"), s);
2534 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2536 QColor const & qcol = d->color_cache_.get(col);
2537 if (!qcol.isValid()) {
2543 rgbcol.r = qcol.red();
2544 rgbcol.g = qcol.green();
2545 rgbcol.b = qcol.blue();
2550 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2552 QColor const qcol(lcolor.getX11Name(col).c_str());
2553 if (!qcol.isValid()) {
2559 rgbcol.r = qcol.red();
2560 rgbcol.g = qcol.green();
2561 rgbcol.b = qcol.blue();
2566 string const GuiApplication::hexName(ColorCode col)
2568 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2572 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2574 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2575 d->socket_notifiers_[fd] = sn;
2576 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2580 void GuiApplication::socketDataReceived(int fd)
2582 d->socket_notifiers_[fd]->func_();
2586 void GuiApplication::unregisterSocketCallback(int fd)
2588 d->socket_notifiers_.take(fd)->setEnabled(false);
2592 void GuiApplication::commitData(QSessionManager & sm)
2594 /// The implementation is required to avoid an application exit
2595 /// when session state save is triggered by session manager.
2596 /// The default implementation sends a close event to all
2597 /// visible top level widgets when session managment allows
2599 /// We are changing that to close all wiew one by one.
2600 /// FIXME: verify if the default implementation is enough now.
2601 #ifdef QT_NO_SESSIONMANAGER
2603 #warning Qt is compiled without session manager
2605 #pragma message("warning: Qt is compiled without session manager")
2609 if (sm.allowsInteraction() && !closeAllViews())
2615 void GuiApplication::unregisterView(GuiView * gv)
2617 LAPPERR(d->views_[gv->id()] == gv);
2618 d->views_.remove(gv->id());
2619 if (current_view_ == gv)
2624 bool GuiApplication::closeAllViews()
2626 if (d->views_.empty())
2629 // When a view/window was closed before without quitting LyX, there
2630 // are already entries in the lastOpened list.
2631 theSession().lastOpened().clear();
2633 QList<GuiView *> const views = d->views_.values();
2634 foreach (GuiView * view, views) {
2635 if (!view->closeScheduled())
2644 GuiView & GuiApplication::view(int id) const
2646 LAPPERR(d->views_.contains(id));
2647 return *d->views_.value(id);
2651 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2653 QList<GuiView *> const views = d->views_.values();
2654 foreach (GuiView * view, views)
2655 view->hideDialog(name, inset);
2659 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2661 Buffer const * buffer_ = 0;
2662 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2663 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2664 if (Buffer const * ptr = (*it)->updateInset(inset))
2671 bool GuiApplication::searchMenu(FuncRequest const & func,
2672 docstring_list & names) const
2674 return d->menus_.searchMenu(func, names);
2678 // Ensure that a file is read only once (prevents include loops)
2679 static QStringList uifiles;
2680 // store which ui files define Toolbars
2681 static QStringList toolbar_uifiles;
2684 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2695 LexerKeyword uitags[] = {
2696 { "format", ui_format },
2697 { "include", ui_include },
2698 { "menuset", ui_menuset },
2699 { "toolbars", ui_toolbars },
2700 { "toolbarset", ui_toolbarset }
2704 lex.setFile(ui_path);
2706 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2710 if (lyxerr.debugging(Debug::PARSER))
2711 lex.printTable(lyxerr);
2714 // format before introduction of format tag
2715 unsigned int format = 0;
2716 while (lex.isOK()) {
2717 int const status = lex.lex();
2719 // we have to do this check here, outside the switch,
2720 // because otherwise we would start reading include files,
2721 // e.g., if the first tag we hit was an include tag.
2722 if (status == ui_format)
2724 format = lex.getInteger();
2728 // this will trigger unless the first tag we hit is a format
2729 // tag, with the right format.
2730 if (format != LFUN_FORMAT)
2731 return FormatMismatch;
2734 case Lexer::LEX_FEOF:
2739 QString const file = toqstr(lex.getString());
2740 bool const success = readUIFile(file, true);
2742 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2749 d->menus_.read(lex);
2753 d->toolbars_.readToolbars(lex);
2757 d->toolbars_.readToolbarSettings(lex);
2758 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2762 if (!rtrim(lex.getString()).empty())
2763 lex.printError("LyX::ReadUIFile: "
2764 "Unknown menu tag: `$$Token'");
2766 LYXERR0("Error with status: " << status);
2772 return (error ? ReadError : ReadOK);
2776 bool GuiApplication::readUIFile(QString const & name, bool include)
2778 LYXERR(Debug::INIT, "About to read " << name << "...");
2782 ui_path = libFileSearch("ui", name, "inc");
2783 if (ui_path.empty())
2784 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2786 ui_path = libFileSearch("ui", name, "ui");
2789 if (ui_path.empty()) {
2790 static const QString defaultUIFile = "default";
2791 LYXERR(Debug::INIT, "Could not find " << name);
2793 Alert::warning(_("Could not find UI definition file"),
2794 bformat(_("Error while reading the included file\n%1$s\n"
2795 "Please check your installation."), qstring_to_ucs4(name)));
2798 if (name == defaultUIFile) {
2799 LYXERR(Debug::INIT, "Could not find default UI file!!");
2800 Alert::warning(_("Could not find default UI file"),
2801 _("LyX could not find the default UI file!\n"
2802 "Please check your installation."));
2805 Alert::warning(_("Could not find UI definition file"),
2806 bformat(_("Error while reading the configuration file\n%1$s\n"
2807 "Falling back to default.\n"
2808 "Please look under Tools>Preferences>User Interface and\n"
2809 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2810 return readUIFile(defaultUIFile, false);
2813 QString const uifile = toqstr(ui_path.absFileName());
2814 if (uifiles.contains(uifile)) {
2816 // We are reading again the top uifile so reset the safeguard:
2819 d->toolbars_.reset();
2821 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2822 << "Is this an include loop?");
2826 uifiles.push_back(uifile);
2828 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2830 ReturnValues retval = readUIFile(ui_path);
2832 if (retval == FormatMismatch) {
2833 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2834 FileName const tempfile = FileName::tempName("convert_ui");
2835 bool const success = prefs2prefs(ui_path, tempfile, true);
2837 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2838 " to format " << LFUN_FORMAT << ".");
2840 retval = readUIFile(tempfile);
2841 tempfile.removeFile();
2845 if (retval != ReadOK) {
2846 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2854 settings.beginGroup("ui_files");
2855 bool touched = false;
2856 for (int i = 0; i != uifiles.size(); ++i) {
2857 QFileInfo fi(uifiles[i]);
2858 QDateTime const date_value = fi.lastModified();
2859 QString const name_key = QString::number(i);
2860 // if an ui file which defines Toolbars has changed,
2861 // we have to reset the settings
2862 if (toolbar_uifiles.contains(uifiles[i])
2863 && (!settings.contains(name_key)
2864 || settings.value(name_key).toString() != uifiles[i]
2865 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2867 settings.setValue(name_key, uifiles[i]);
2868 settings.setValue(name_key + "/date", date_value);
2871 settings.endGroup();
2873 settings.remove("views");
2879 void GuiApplication::onLastWindowClosed()
2881 if (d->global_menubar_)
2882 d->global_menubar_->grabKeyboard();
2886 void GuiApplication::startLongOperation() {
2887 d->key_checker_.start();
2891 bool GuiApplication::longOperationCancelled() {
2892 return d->key_checker_.pressed();
2896 void GuiApplication::stopLongOperation() {
2897 d->key_checker_.stop();
2901 bool GuiApplication::longOperationStarted() {
2902 return d->key_checker_.started();
2906 ////////////////////////////////////////////////////////////////////////
2908 // X11 specific stuff goes here...
2911 bool GuiApplication::x11EventFilter(XEvent * xev)
2916 switch (xev->type) {
2917 case SelectionRequest: {
2918 if (xev->xselectionrequest.selection != XA_PRIMARY)
2920 LYXERR(Debug::SELECTION, "X requested selection.");
2921 BufferView * bv = current_view_->currentBufferView();
2923 docstring const sel = bv->requestSelection();
2925 d->selection_.put(sel);
2929 case SelectionClear: {
2930 if (xev->xselectionclear.selection != XA_PRIMARY)
2932 LYXERR(Debug::SELECTION, "Lost selection.");
2933 BufferView * bv = current_view_->currentBufferView();
2935 bv->clearSelection();
2943 } // namespace frontend
2946 void hideDialogs(std::string const & name, Inset * inset)
2949 frontend::guiApp->hideDialogs(name, inset);
2953 ////////////////////////////////////////////////////////////////////
2957 ////////////////////////////////////////////////////////////////////
2959 frontend::FontLoader & theFontLoader()
2961 LAPPERR(frontend::guiApp);
2962 return frontend::guiApp->fontLoader();
2966 frontend::FontMetrics const & theFontMetrics(Font const & f)
2968 return theFontMetrics(f.fontInfo());
2972 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2974 LAPPERR(frontend::guiApp);
2975 return frontend::guiApp->fontLoader().metrics(f);
2979 ////////////////////////////////////////////////////////////////////
2983 ////////////////////////////////////////////////////////////////////
2985 frontend::Clipboard & theClipboard()
2987 LAPPERR(frontend::guiApp);
2988 return frontend::guiApp->clipboard();
2992 frontend::Selection & theSelection()
2994 LAPPERR(frontend::guiApp);
2995 return frontend::guiApp->selection();
3001 #include "moc_GuiApplication.cpp"