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());
181 /// Return the list of loadable formats.
182 vector<string> loadableImageFormats()
186 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
188 LYXERR(Debug::GRAPHICS,
189 "\nThe image loader can load the following directly:\n");
191 if (qt_formats.empty())
192 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
194 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
196 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
198 string ext = ascii_lowercase((const char *) *it);
209 ////////////////////////////////////////////////////////////////////////
211 // Icon loading support code
213 ////////////////////////////////////////////////////////////////////////
223 bool operator<(PngMap const & lhs, PngMap const & rhs)
225 return lhs.key < rhs.key;
231 CompareKey(QString const & name) : name_(name) {}
232 bool operator()(PngMap const & other) const { return other.key == name_; }
238 // this must be sorted alphabetically
239 // Upper case comes before lower case
240 // Please don't change the formatting, this list is parsed by
241 // development/tools/generate_symbols_images.py.
242 PngMap sorted_png_map[] = {
243 { "Arrownot", "arrownot2"},
244 { "Arrowvert", "arrowvert2"},
245 { "Bowtie", "bowtie2" },
247 { "Bumpeq", "bumpeq2" },
248 { "CIRCLE", "circle3" },
250 { "CheckedBox", "checkedbox2" },
251 { "Circle", "circle2" },
252 { "Colonapprox", "colonapprox2" },
253 { "Coloneq", "coloneq2" },
254 { "Coloneqq", "coloneqq2" },
255 { "Colonsim", "colonsim2" },
257 { "DOWNarrow", "downarrow3" },
258 { "Delta", "delta2" },
259 { "Diamond", "diamond2" },
260 { "Doteq", "doteq2" },
261 { "Downarrow", "downarrow2" },
262 { "Eqcolon", "eqcolon2" },
263 { "Eqqcolon", "eqqcolon2" },
264 { "Gamma", "gamma2" },
266 { "LEFTCIRCLE", "leftcircle3" },
267 { "LEFTarrow", "leftarrow3" },
268 { "LEFTcircle", "leftcircle4" },
270 { "Lambda", "lambda2" },
272 { "Leftarrow", "leftarrow2" },
273 { "Leftcircle", "leftcircle2" },
274 { "Leftrightarrow", "leftrightarrow2" },
275 { "Longarrownot", "longarrownot2"},
276 { "Longleftarrow", "longleftarrow2" },
277 { "Longleftrightarrow", "longleftrightarrow2" },
278 { "Longmapsfrom", "longmapsfrom2"},
279 { "Longmapsto", "longmapsto2"},
280 { "Longrightarrow", "longrightarrow2" },
281 { "Mapsfrom", "mapsfrom2"},
282 { "Mapsfromchar", "mapsfromchar2"},
283 { "Mapsto", "mapsto2"},
284 { "Mapstochar", "mapstochar2"},
285 { "Omega", "omega2" },
290 { "RIGHTCIRCLE", "rightcircle3" },
291 { "RIGHTarrow", "rightarrow3" },
292 { "RIGHTcircle", "rightcircle4" },
294 { "Rightarrow", "rightarrow2" },
295 { "Rightcircle", "rightcircle2" },
296 { "Sigma", "sigma2" },
297 { "Square", "square2" },
298 { "Subset", "subset2" },
299 { "Supset", "supset2" },
300 { "Theta", "theta2" },
301 { "Thorn", "thorn2" },
302 { "UParrow", "uparrow3" },
303 { "Uparrow", "uparrow2" },
304 { "Updownarrow", "updownarrow2" },
305 { "Upsilon", "upsilon2" },
306 { "Vdash", "vdash3" },
311 { "nLeftarrow", "nleftarrow2" },
312 { "nLeftrightarrow", "nleftrightarrow2" },
313 { "nRightarrow", "nrightarrow2" },
314 { "nVDash", "nvdash3" },
315 { "nVdash", "nvdash4" },
316 { "nvDash", "nvdash2" },
317 { "textrm \\AA", "textrm_AA"},
318 { "textrm \\O", "textrm_O"},
319 { "vDash", "vdash2" },
320 { "varDelta", "vardelta2" },
321 { "varGamma", "vargamma2" },
322 { "varLambda", "varlambda2" },
323 { "varOmega", "varomega2" },
324 { "varPhi", "varphi2" },
325 { "varPi", "varpi2" },
326 { "varPsi", "varpsi2" },
327 { "varSigma", "varsigma2" },
328 { "varTheta", "vartheta2" },
329 { "varUpsilon", "varupsilon2" },
330 { "varXi", "varxi2" }
334 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
336 // This list specifies which system's theme icon is related to which lyx
337 // command. It was based on:
338 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
339 // this must be sorted alphabetically
340 // Upper case comes before lower case
341 PngMap sorted_theme_icon_map[] = {
342 { "bookmark-goto 0", "go-jump" },
343 { "buffer-new", "document-new" },
344 { "buffer-print", "document-print" },
345 { "buffer-write", "document-save" },
346 { "buffer-write-as", "document-save-as" },
347 { "buffer-zoom-in", "zoom-in" },
348 { "buffer-zoom-out", "zoom-out" },
349 { "copy", "edit-copy" },
350 { "cut", "edit-cut" },
351 { "depth-decrement", "format-indent-less" },
352 { "depth-increment", "format-indent-more" },
353 { "dialog-show print", "document-print" },
354 { "dialog-show spellchecker", "tools-check-spelling" },
355 { "dialog-show-new-inset graphics", "insert-image" },
356 { "dialog-toggle findreplaceadv", "edit-find-replace" },
357 { "file-open", "document-open" },
358 { "font-bold", "format-text-bold" },
359 { "font-ital", "format-text-italic" },
360 { "font-strikeout", "format-text-strikethrough" },
361 { "font-underline", "format-text-underline" },
362 { "lyx-quit", "application-exit" },
363 { "paste", "edit-paste" },
364 { "redo", "edit-redo" },
365 { "undo", "edit-undo" },
366 { "window-close", "window-close" },
367 { "window-new", "window-new" }
370 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
373 QString findPng(QString const & name)
375 PngMap const * const begin = sorted_png_map;
376 PngMap const * const end = begin + nr_sorted_png_map;
377 LATTEST(sorted(begin, end));
379 PngMap const * const it = find_if(begin, end, CompareKey(name));
383 png_name = it->value;
386 png_name.replace('_', "underscore");
387 png_name.replace(' ', '_');
389 // This way we can have "math-delim { }" on the toolbar.
390 png_name.replace('(', "lparen");
391 png_name.replace(')', "rparen");
392 png_name.replace('[', "lbracket");
393 png_name.replace(']', "rbracket");
394 png_name.replace('{', "lbrace");
395 png_name.replace('}', "rbrace");
396 png_name.replace('|', "bars");
397 png_name.replace(',', "thinspace");
398 png_name.replace(':', "mediumspace");
399 png_name.replace(';', "thickspace");
400 png_name.replace('!', "negthinspace");
403 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
404 << "Looking for math PNG called \"" << png_name << '"');
411 QString themeIconName(QString const & action)
413 PngMap const * const begin = sorted_theme_icon_map;
414 PngMap const * const end = begin + nr_sorted_theme_icon_map;
415 LASSERT(sorted(begin, end), /**/);
417 PngMap const * const it = find_if(begin, end, CompareKey(action));
425 QString iconName(FuncRequest const & f, bool unknown)
427 initializeResources();
431 switch (f.action()) {
432 case LFUN_MATH_INSERT:
433 if (!f.argument().empty()) {
435 name1 = findPng(toqstr(f.argument()).mid(1));
438 case LFUN_MATH_DELIM:
439 case LFUN_MATH_BIGDELIM:
441 name1 = findPng(toqstr(f.argument()));
445 name1 = toqstr(f.argument());
447 case LFUN_COMMAND_ALTERNATIVES: {
448 // use the first of the alternative commands
450 docstring dummy = split(f.argument(), firstcom, ';');
451 name1 = toqstr(firstcom);
452 // FIXME: we should rename the icons to tabular-xxx instead of
453 // "tabular-feature-xxx"
454 name1.replace("inset-modify tabular", "tabular-feature");
455 name1.replace(' ', '_');
458 case LFUN_INSET_MODIFY: {
459 // FIXME: we should rename the icons to tabular-xxx instead of
460 // "tabular-feature-xxx" and generalize this naming to all
461 // insets, not to tabular using ones.
463 string const command = split(to_utf8(f.argument()), inset_name, ' ');
464 if (insetCode(inset_name) == TABULAR_CODE) {
465 name1 = "tabular-feature "+ toqstr(command);
466 name1.replace(' ', '_');
471 name2 = toqstr(lyxaction.getActionName(f.action()));
474 if (!f.argument().empty()) {
475 name1 = name2 + ' ' + toqstr(f.argument());
476 name1.replace(' ', '_');
477 name1.replace('\\', "backslash");
481 QStringList imagedirs;
482 imagedirs << "images/" << "images/ipa/";
483 for (int i = 0; i < imagedirs.size(); ++i) {
484 QString imagedir = imagedirs.at(i) + path;
485 FileName fname = imageLibFileSearch(imagedir, name1, "png");
487 return toqstr(fname.absFileName());
489 fname = imageLibFileSearch(imagedir, name2, "png");
491 return toqstr(fname.absFileName());
494 path = ":/images/" + path;
497 LYXERR0("Directory " << path << " not found in resource!");
501 if (res.exists(name1))
505 if (res.exists(name2))
508 LYXERR(Debug::GUI, "Cannot find icon with filename "
509 << "\"" << name1 << "\""
511 << "\"" << name2 << "\""
513 << lyxaction.getActionName(f.action())
514 << '(' << to_utf8(f.argument()) << ")\"");
517 QString imagedir = "images/";
518 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
520 return toqstr(fname.absFileName());
521 return QString(":/images/unknown.png");
527 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
530 QString imagedir = path;
531 FileName fname = imageLibFileSearch(imagedir, name, ext);
532 QString path1 = toqstr(fname.absFileName());
533 QString path2 = ":/" + path + name + "." + ext;
535 if (pixmap.load(path1)) {
538 else if (pixmap.load(path2)) {
542 LYXERR0("Cannot load pixmap \""
543 << path << name << '.' << ext
544 << "\", please verify resource system!");
549 QIcon getIcon(FuncRequest const & f, bool unknown)
551 #if (QT_VERSION >= 0x040600)
552 if (lyxrc.use_system_theme_icons) {
553 QString action = toqstr(lyxaction.getActionName(f.action()));
554 if (!f.argument().empty())
555 action += " " + toqstr(f.argument());
556 QString const theme_icon = themeIconName(action);
557 if (QIcon::hasThemeIcon(theme_icon))
558 return QIcon::fromTheme(theme_icon);
562 QString icon = iconName(f, unknown);
566 //LYXERR(Debug::GUI, "Found icon: " << icon);
568 if (!pm.load(icon)) {
569 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
577 ////////////////////////////////////////////////////////////////////////
579 // LyX server support code.
581 ////////////////////////////////////////////////////////////////////////
583 class SocketNotifier : public QSocketNotifier
586 /// connect a connection notification from the LyXServerSocket
587 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
588 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
592 /// The callback function
593 Application::SocketCallback func_;
597 ////////////////////////////////////////////////////////////////////////
599 // Mac specific stuff goes here...
601 ////////////////////////////////////////////////////////////////////////
603 class MenuTranslator : public QTranslator
606 MenuTranslator(QObject * parent)
607 : QTranslator(parent)
610 QString translate(const char * /*context*/,
611 const char * sourceText,
612 const char * /*comment*/ = 0) const
614 string const s = sourceText;
615 if (s == N_("About %1") || s == N_("Preferences")
616 || s == N_("Reconfigure") || s == N_("Quit %1"))
623 class GlobalMenuBar : public QMenuBar
627 GlobalMenuBar() : QMenuBar(0) {}
630 bool event(QEvent * e)
632 if (e->type() == QEvent::ShortcutOverride) {
633 // && activeWindow() == 0) {
634 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
636 setKeySymbol(&sym, ke);
637 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
646 // QMacPasteboardMimeGraphics can only be compiled on Mac.
648 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
651 QMacPasteboardMimeGraphics()
652 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
655 QString convertorName() { return "Graphics"; }
657 QString flavorFor(QString const & mime)
659 LYXERR(Debug::ACTION, "flavorFor " << mime);
660 if (mime == pdfMimeType())
661 return QLatin1String("com.adobe.pdf");
665 QString mimeFor(QString flav)
667 LYXERR(Debug::ACTION, "mimeFor " << flav);
668 if (flav == QLatin1String("com.adobe.pdf"))
669 return pdfMimeType();
673 bool canConvert(QString const & mime, QString flav)
675 return mimeFor(flav) == mime;
678 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
682 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
686 QList<QByteArray> convertFromMime(QString const & /*mime*/,
687 QVariant data, QString /*flav*/)
689 QList<QByteArray> ret;
690 ret.append(data.toByteArray());
696 ///////////////////////////////////////////////////////////////
698 // You can find more platform specific stuff at the end of this file...
700 ///////////////////////////////////////////////////////////////
702 ////////////////////////////////////////////////////////////////////////
703 // Windows specific stuff goes here...
706 // QWindowsMimeMetafile can only be compiled on Windows.
708 static FORMATETC cfFromMime(QString const & mimetype)
711 if (mimetype == emfMimeType()) {
712 formatetc.cfFormat = CF_ENHMETAFILE;
713 formatetc.tymed = TYMED_ENHMF;
714 } else if (mimetype == wmfMimeType()) {
715 formatetc.cfFormat = CF_METAFILEPICT;
716 formatetc.tymed = TYMED_MFPICT;
719 formatetc.dwAspect = DVASPECT_CONTENT;
720 formatetc.lindex = -1;
725 class QWindowsMimeMetafile : public QWindowsMime {
727 QWindowsMimeMetafile() {}
729 bool canConvertFromMime(FORMATETC const & formatetc,
730 QMimeData const * mimedata) const
735 bool canConvertToMime(QString const & mimetype,
736 IDataObject * pDataObj) const
738 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
740 FORMATETC formatetc = cfFromMime(mimetype);
741 return pDataObj->QueryGetData(&formatetc) == S_OK;
744 bool convertFromMime(FORMATETC const & formatetc,
745 const QMimeData * mimedata, STGMEDIUM * pmedium) const
750 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
751 QVariant::Type preferredType) const
754 if (!canConvertToMime(mimetype, pDataObj))
757 FORMATETC formatetc = cfFromMime(mimetype);
759 if (pDataObj->GetData(&formatetc, &s) != S_OK)
763 if (s.tymed == TYMED_ENHMF) {
764 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
765 data.resize(dataSize);
766 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
767 (LPBYTE)data.data());
768 } else if (s.tymed == TYMED_MFPICT) {
769 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
770 data.resize(dataSize);
771 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
772 (LPBYTE)data.data());
775 ReleaseStgMedium(&s);
781 QVector<FORMATETC> formatsForMime(QString const & mimetype,
782 QMimeData const * mimedata) const
784 QVector<FORMATETC> formats;
785 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
786 formats += cfFromMime(mimetype);
790 QString mimeForFormat(FORMATETC const & formatetc) const
792 switch (formatetc.cfFormat) {
794 return emfMimeType();
795 case CF_METAFILEPICT:
796 return wmfMimeType();
805 /// Allows to check whether ESC was pressed during a long operation
806 class KeyChecker : public QObject {
811 KeyChecker() : pressed_(false), started_(false) {}
814 QCoreApplication::instance()->installEventFilter(this);
819 QCoreApplication::instance()->removeEventFilter(this);
823 QCoreApplication::processEvents();
826 bool started() const {
829 bool eventFilter(QObject *obj, QEvent *event) {
830 LYXERR(Debug::ACTION, "Event Type: " << event->type());
831 switch (event->type()) {
835 return QObject::eventFilter(obj, event);
837 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
838 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
846 ////////////////////////////////////////////////////////////////////////
847 // GuiApplication::Private definition and implementation.
848 ////////////////////////////////////////////////////////////////////////
850 struct GuiApplication::Private
852 Private(): language_model_(0), meta_fake_bit(NoModifier),
856 /// WMF Mime handler for Windows clipboard.
857 wmf_mime_ = new QWindowsMimeMetafile;
859 initKeySequences(&theTopLevelKeymap());
862 void initKeySequences(KeyMap * kb)
864 keyseq = KeySequence(kb, kb);
865 cancel_meta_seq = KeySequence(kb, kb);
869 QSortFilterProxyModel * language_model_;
871 GuiClipboard clipboard_;
873 GuiSelection selection_;
875 FontLoader font_loader_;
877 ColorCache color_cache_;
879 QTranslator qt_trans_;
881 QHash<int, SocketNotifier *> socket_notifiers_;
885 /// The global instance
888 /// this timer is used for any regular events one wants to
889 /// perform. at present it is used to check if forked processes
891 QTimer general_timer_;
893 /// delayed FuncRequests
894 std::queue<FuncRequest> func_request_queue_;
899 KeySequence cancel_meta_seq;
901 KeyModifier meta_fake_bit;
903 /// Multiple views container.
905 * Warning: This must not be a smart pointer as the destruction of the
906 * object is handled by Qt when the view is closed
907 * \sa Qt::WA_DeleteOnClose attribute.
909 QHash<int, GuiView *> views_;
911 /// Only used on mac.
912 GlobalMenuBar * global_menubar_;
915 /// Linkback mime handler for MacOSX.
916 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
920 /// WMF Mime handler for Windows clipboard.
921 QWindowsMimeMetafile * wmf_mime_;
924 /// Allows to check whether ESC was pressed during a long operation
925 KeyChecker key_checker_;
929 GuiApplication * guiApp;
931 GuiApplication::~GuiApplication()
934 closeAllLinkBackLinks();
940 GuiApplication::GuiApplication(int & argc, char ** argv)
941 : QApplication(argc, argv), current_view_(0),
942 d(new GuiApplication::Private)
944 QString app_name = "LyX";
945 QCoreApplication::setOrganizationName(app_name);
946 QCoreApplication::setOrganizationDomain("lyx.org");
947 QCoreApplication::setApplicationName(lyx_package);
949 // Install translator for GUI elements.
950 installTranslator(&d->qt_trans_);
952 // FIXME: quitOnLastWindowClosed is true by default. We should have a
953 // lyxrc setting for this in order to let the application stay resident.
954 // But then we need some kind of dock icon, at least on Windows.
956 if (lyxrc.quit_on_last_window_closed)
957 setQuitOnLastWindowClosed(false);
960 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
961 // seems to be the default case for applications like LyX.
962 setQuitOnLastWindowClosed(false);
963 // This allows to translate the strings that appear in the LyX menu.
964 /// A translator suitable for the entries in the LyX menu.
965 /// Only needed with Qt/Mac.
966 installTranslator(new MenuTranslator(this));
972 // doubleClickInterval() is 400 ms on X11 which is just too long.
973 // On Windows and Mac OS X, the operating system's value is used.
974 // On Microsoft Windows, calling this function sets the double
975 // click interval for all applications. So we don't!
976 QApplication::setDoubleClickInterval(300);
979 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
981 // needs to be done before reading lyxrc
983 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
987 // Set the cache to 5120 kilobytes which corresponds to screen size of
988 // 1280 by 1024 pixels with a color depth of 32 bits.
989 QPixmapCache::setCacheLimit(5120);
991 // Initialize RC Fonts
992 if (lyxrc.roman_font_name.empty())
993 lyxrc.roman_font_name = fromqstr(romanFontName());
995 if (lyxrc.sans_font_name.empty())
996 lyxrc.sans_font_name = fromqstr(sansFontName());
998 if (lyxrc.typewriter_font_name.empty())
999 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1001 d->general_timer_.setInterval(500);
1002 connect(&d->general_timer_, SIGNAL(timeout()),
1003 this, SLOT(handleRegularEvents()));
1004 d->general_timer_.start();
1006 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1007 // This is clearly not enough in a time where we use threads for
1008 // document preview and/or export. 20 should be OK.
1009 QThreadPool::globalInstance()->setMaxThreadCount(20);
1013 GuiApplication * theGuiApp()
1015 return dynamic_cast<GuiApplication *>(theApp());
1019 void GuiApplication::clearSession()
1026 docstring Application::iconName(FuncRequest const & f, bool unknown)
1028 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1032 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1036 BufferView * bv = 0;
1037 BufferView * doc_bv = 0;
1039 if (cmd.action() == LFUN_NOACTION) {
1040 status.message(from_utf8(N_("Nothing to do")));
1041 status.setEnabled(false);
1044 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1045 status.setUnknown(true);
1046 status.message(from_utf8(N_("Unknown action")));
1047 status.setEnabled(false);
1050 // Does the GuiApplication know something?
1051 else if (getStatus(cmd, status)) { }
1053 // If we do not have a GuiView, then other functions are disabled
1054 else if (!current_view_)
1055 status.setEnabled(false);
1057 // Does the GuiView know something?
1058 else if (current_view_->getStatus(cmd, status)) { }
1060 // In LyX/Mac, when a dialog is open, the menus of the
1061 // application can still be accessed without giving focus to
1062 // the main window. In this case, we want to disable the menu
1063 // entries that are buffer or view-related.
1064 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1066 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1067 status.setEnabled(false);
1070 // If we do not have a BufferView, then other functions are disabled
1071 else if (!(bv = current_view_->currentBufferView()))
1072 status.setEnabled(false);
1074 // Does the current BufferView know something?
1075 else if (bv->getStatus(cmd, status)) { }
1077 // Does the current Buffer know something?
1078 else if (bv->buffer().getStatus(cmd, status)) { }
1080 // If we do not have a document BufferView, different from the
1081 // current BufferView, then other functions are disabled
1082 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1083 status.setEnabled(false);
1085 // Does the document Buffer know something?
1086 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1089 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1090 status.message(from_utf8(N_("Command not handled")));
1091 status.setEnabled(false);
1094 // the default error message if we disable the command
1095 if (!status.enabled() && status.message().empty())
1096 status.message(from_utf8(N_("Command disabled")));
1102 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1104 // I would really like to avoid having this switch and rather try to
1105 // encode this in the function itself.
1106 // -- And I'd rather let an inset decide which LFUNs it is willing
1107 // to handle (Andre')
1109 switch (cmd.action()) {
1111 // This could be used for the no-GUI version. The GUI version is handled in
1112 // GuiView::getStatus(). See above.
1114 case LFUN_BUFFER_WRITE:
1115 case LFUN_BUFFER_WRITE_AS: {
1116 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1117 enable = b && (b->isUnnamed() || !b->isClean());
1122 case LFUN_BOOKMARK_GOTO: {
1123 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1124 enable = theSession().bookmarks().isValid(num);
1128 case LFUN_BOOKMARK_CLEAR:
1129 enable = theSession().bookmarks().hasValid();
1132 // this one is difficult to get right. As a half-baked
1133 // solution, we consider only the first action of the sequence
1134 case LFUN_COMMAND_SEQUENCE: {
1135 // argument contains ';'-terminated commands
1136 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1137 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1138 func.setOrigin(cmd.origin());
1139 flag = getStatus(func);
1143 // we want to check if at least one of these is enabled
1144 case LFUN_COMMAND_ALTERNATIVES: {
1145 // argument contains ';'-terminated commands
1146 string arg = to_utf8(cmd.argument());
1147 while (!arg.empty()) {
1149 arg = split(arg, first, ';');
1150 FuncRequest func(lyxaction.lookupFunc(first));
1151 func.setOrigin(cmd.origin());
1152 flag = getStatus(func);
1153 // if this one is enabled, the whole thing is
1162 string name = to_utf8(cmd.argument());
1163 if (theTopLevelCmdDef().lock(name, func)) {
1164 func.setOrigin(cmd.origin());
1165 flag = getStatus(func);
1166 theTopLevelCmdDef().release(name);
1168 // catch recursion or unknown command
1169 // definition. all operations until the
1170 // recursion or unknown command definition
1171 // occurs are performed, so set the state to
1178 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1180 case LFUN_PREFERENCES_SAVE:
1181 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1182 case LFUN_DEBUG_LEVEL_SET:
1183 // these are handled in our dispatch()
1186 case LFUN_WINDOW_CLOSE:
1187 enable = d->views_.size() > 0;
1190 case LFUN_BUFFER_NEW:
1191 case LFUN_BUFFER_NEW_TEMPLATE:
1192 case LFUN_FILE_OPEN:
1193 case LFUN_HELP_OPEN:
1194 case LFUN_SCREEN_FONT_UPDATE:
1195 case LFUN_SET_COLOR:
1196 case LFUN_WINDOW_NEW:
1198 case LFUN_LYXRC_APPLY:
1199 case LFUN_COMMAND_PREFIX:
1201 case LFUN_META_PREFIX:
1202 case LFUN_RECONFIGURE:
1203 case LFUN_SERVER_GET_FILENAME:
1204 case LFUN_SERVER_NOTIFY:
1208 case LFUN_BUFFER_FORALL: {
1209 if (theBufferList().empty()) {
1210 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1211 flag.setEnabled(false);
1215 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1216 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1217 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1218 flag.setEnabled(false);
1229 flag.setEnabled(false);
1233 /// make a post-dispatch status message
1234 static docstring makeDispatchMessage(docstring const & msg,
1235 FuncRequest const & cmd)
1237 const bool verbose = (cmd.origin() == FuncRequest::MENU
1238 || cmd.origin() == FuncRequest::TOOLBAR
1239 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1241 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1242 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1246 docstring dispatch_msg = msg;
1247 if (!dispatch_msg.empty())
1248 dispatch_msg += ' ';
1250 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1252 bool argsadded = false;
1254 if (!cmd.argument().empty()) {
1255 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1256 comname += ' ' + cmd.argument();
1260 docstring const shortcuts = theTopLevelKeymap().
1261 printBindings(cmd, KeySequence::ForGui);
1263 if (!shortcuts.empty())
1264 comname += ": " + shortcuts;
1265 else if (!argsadded && !cmd.argument().empty())
1266 comname += ' ' + cmd.argument();
1268 if (!comname.empty()) {
1269 comname = rtrim(comname);
1270 dispatch_msg += '(' + rtrim(comname) + ')';
1272 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1273 return dispatch_msg;
1277 void GuiApplication::dispatch(FuncRequest const & cmd)
1279 Buffer * buffer = 0;
1280 if (current_view_ && current_view_->currentBufferView()) {
1281 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1282 buffer = ¤t_view_->currentBufferView()->buffer();
1284 buffer->undo().beginUndoGroup();
1288 // redraw the screen at the end (first of the two drawing steps).
1289 // This is done unless explicitly requested otherwise
1290 dr.screenUpdate(Update::FitCursor);
1292 updateCurrentView(cmd, dr);
1294 // the buffer may have been closed by one action
1295 if (theBufferList().isLoaded(buffer))
1296 buffer->undo().endUndoGroup();
1300 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1305 BufferView * bv = current_view_->currentBufferView();
1307 if (dr.needBufferUpdate()) {
1308 bv->cursor().clearBufferUpdate();
1309 bv->buffer().updateBuffer();
1311 // BufferView::update() updates the ViewMetricsInfo and
1312 // also initializes the position cache for all insets in
1313 // (at least partially) visible top-level paragraphs.
1314 // We will redraw the screen only if needed.
1315 bv->processUpdateFlags(dr.screenUpdate());
1317 // Do we have a selection?
1318 theSelection().haveSelection(bv->cursor().selection());
1321 current_view_->restartCursor();
1323 if (dr.needMessageUpdate()) {
1324 // Some messages may already be translated, so we cannot use _()
1325 current_view_->message(makeDispatchMessage(
1326 translateIfPossible(dr.message()), cmd));
1331 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1332 bool switchToBuffer)
1334 if (!theSession().bookmarks().isValid(idx))
1336 BookmarksSection::Bookmark const & bm =
1337 theSession().bookmarks().bookmark(idx);
1338 LASSERT(!bm.filename.empty(), return);
1339 string const file = bm.filename.absFileName();
1340 // if the file is not opened, open it.
1341 if (!theBufferList().exists(bm.filename)) {
1343 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1347 // open may fail, so we need to test it again
1348 if (!theBufferList().exists(bm.filename))
1351 // bm can be changed when saving
1352 BookmarksSection::Bookmark tmp = bm;
1354 // Special case idx == 0 used for back-from-back jump navigation
1356 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1358 // if the current buffer is not that one, switch to it.
1359 BufferView * doc_bv = current_view_ ?
1360 current_view_->documentBufferView() : 0;
1361 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1362 if (switchToBuffer) {
1363 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1366 doc_bv = current_view_->documentBufferView();
1371 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1372 if (!doc_bv->moveToPosition(
1373 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1380 // Cursor jump succeeded!
1381 Cursor const & cur = doc_bv->cursor();
1382 pit_type new_pit = cur.pit();
1383 pos_type new_pos = cur.pos();
1384 int new_id = cur.paragraph().id();
1386 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1387 // see http://www.lyx.org/trac/ticket/3092
1388 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1389 || bm.top_id != new_id) {
1390 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1391 new_pit, new_pos, new_id);
1395 // This function runs "configure" and then rereads lyx.defaults to
1396 // reconfigure the automatic settings.
1397 void GuiApplication::reconfigure(string const & option)
1399 // emit message signal.
1401 current_view_->message(_("Running configure..."));
1403 // Run configure in user lyx directory
1404 PathChanger p(package().user_support());
1405 string configure_command = package().configure_command();
1406 configure_command += option;
1408 int const ret = one.startscript(Systemcall::Wait, configure_command);
1410 // emit message signal.
1412 current_view_->message(_("Reloading configuration..."));
1413 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1414 // Re-read packages.lst
1415 LaTeXPackages::getAvailable();
1418 Alert::information(_("System reconfiguration failed"),
1419 _("The system reconfiguration has failed.\n"
1420 "Default textclass is used but LyX may\n"
1421 "not be able to work properly.\n"
1422 "Please reconfigure again if needed."));
1424 Alert::information(_("System reconfigured"),
1425 _("The system has been reconfigured.\n"
1426 "You need to restart LyX to make use of any\n"
1427 "updated document class specifications."));
1430 void GuiApplication::validateCurrentView()
1432 if (!d->views_.empty() && !current_view_) {
1433 // currently at least one view exists but no view has the focus.
1434 // choose the last view to make it current.
1435 // a view without any open document is preferred.
1436 GuiView * candidate = 0;
1437 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1438 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1439 for (; it != end; ++it) {
1441 if (!candidate->documentBufferView())
1444 setCurrentView(candidate);
1448 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1450 string const argument = to_utf8(cmd.argument());
1451 FuncCode const action = cmd.action();
1453 LYXERR(Debug::ACTION, "cmd: " << cmd);
1455 // we have not done anything wrong yet.
1458 FuncStatus const flag = getStatus(cmd);
1459 if (!flag.enabled()) {
1460 // We cannot use this function here
1461 LYXERR(Debug::ACTION, "action "
1462 << lyxaction.getActionName(action)
1463 << " [" << action << "] is disabled at this location");
1464 dr.setMessage(flag.message());
1466 dr.dispatched(false);
1467 dr.screenUpdate(Update::None);
1468 dr.clearBufferUpdate();
1472 if (cmd.origin() == FuncRequest::LYXSERVER) {
1473 if (current_view_ && current_view_->currentBufferView())
1474 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1475 // we will also need to redraw the screen at the end
1476 dr.screenUpdate(Update::FitCursor);
1479 // Assumes that the action will be dispatched.
1480 dr.dispatched(true);
1482 switch (cmd.action()) {
1484 case LFUN_WINDOW_NEW:
1485 createView(toqstr(cmd.argument()));
1488 case LFUN_WINDOW_CLOSE:
1489 // update bookmark pit of the current buffer before window close
1490 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1491 gotoBookmark(i+1, false, false);
1492 // clear the last opened list, because
1493 // maybe this will end the session
1494 theSession().lastOpened().clear();
1495 // check for valid current_view_
1496 validateCurrentView();
1498 current_view_->closeScheduled();
1502 // quitting is triggered by the gui code
1503 // (leaving the event loop).
1505 current_view_->message(from_utf8(N_("Exiting.")));
1506 if (closeAllViews())
1510 case LFUN_SCREEN_FONT_UPDATE: {
1511 // handle the screen font changes.
1512 d->font_loader_.update();
1513 // Backup current_view_
1514 GuiView * view = current_view_;
1515 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1516 // to skip the refresh.
1518 theBufferList().changed(false);
1519 // Restore current_view_
1520 current_view_ = view;
1524 case LFUN_BUFFER_NEW:
1525 validateCurrentView();
1526 if (d->views_.empty()
1527 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1528 createView(QString(), false); // keep hidden
1529 current_view_->newDocument(to_utf8(cmd.argument()), false);
1530 current_view_->show();
1531 setActiveWindow(current_view_);
1533 current_view_->newDocument(to_utf8(cmd.argument()), false);
1537 case LFUN_BUFFER_NEW_TEMPLATE:
1538 validateCurrentView();
1539 if (d->views_.empty()
1540 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1542 current_view_->newDocument(to_utf8(cmd.argument()), true);
1543 if (!current_view_->documentBufferView())
1544 current_view_->close();
1546 current_view_->newDocument(to_utf8(cmd.argument()), true);
1550 case LFUN_FILE_OPEN: {
1551 validateCurrentView();
1552 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1553 string const fname = to_utf8(cmd.argument());
1554 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1555 && current_view_->documentBufferView() != 0)) {
1556 // We want the ui session to be saved per document and not per
1557 // window number. The filename crc is a good enough identifier.
1558 boost::crc_32_type crc;
1559 crc = for_each(fname.begin(), fname.end(), crc);
1560 createView(crc.checksum());
1561 current_view_->openDocument(fname);
1562 if (current_view_ && !current_view_->documentBufferView())
1563 current_view_->close();
1565 current_view_->openDocument(fname);
1569 case LFUN_HELP_OPEN: {
1570 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1571 if (current_view_ == 0)
1573 string const arg = to_utf8(cmd.argument());
1575 current_view_->message(_("Missing argument"));
1578 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1580 fname = i18nLibFileSearch("examples", arg, "lyx");
1582 if (fname.empty()) {
1583 lyxerr << "LyX: unable to find documentation file `"
1584 << arg << "'. Bad installation?" << endl;
1587 current_view_->message(bformat(_("Opening help file %1$s..."),
1588 makeDisplayPath(fname.absFileName())));
1589 Buffer * buf = current_view_->loadDocument(fname, false);
1591 #ifndef DEVEL_VERSION
1593 buf->setReadonly(true);
1600 case LFUN_SET_COLOR: {
1602 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1603 if (lyx_name.empty() || x11_name.empty()) {
1605 current_view_->message(
1606 _("Syntax: set-color <lyx_name> <x11_name>"));
1611 // FIXME: The graphics cache no longer has a changeDisplay method.
1612 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1613 bool const graphicsbg_changed =
1614 lyx_name == graphicsbg && x11_name != graphicsbg;
1615 if (graphicsbg_changed)
1616 graphics::GCache::get().changeDisplay(true);
1619 if (!lcolor.setColor(lyx_name, x11_name)) {
1621 current_view_->message(
1622 bformat(_("Set-color \"%1$s\" failed "
1623 "- color is undefined or "
1624 "may not be redefined"),
1625 from_utf8(lyx_name)));
1628 // Make sure we don't keep old colors in cache.
1629 d->color_cache_.clear();
1633 case LFUN_LYXRC_APPLY: {
1634 // reset active key sequences, since the bindings
1635 // are updated (bug 6064)
1637 LyXRC const lyxrc_orig = lyxrc;
1639 istringstream ss(to_utf8(cmd.argument()));
1640 bool const success = lyxrc.read(ss);
1643 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1644 << "Unable to read lyxrc data"
1649 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1655 case LFUN_COMMAND_PREFIX:
1656 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1661 d->meta_fake_bit = NoModifier;
1662 GuiView * gv = currentView();
1663 if (gv && gv->currentBufferView())
1664 // cancel any selection
1665 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1666 dr.setMessage(from_ascii(N_("Cancel")));
1669 case LFUN_META_PREFIX:
1670 d->meta_fake_bit = AltModifier;
1671 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1674 // --- Menus -----------------------------------------------
1675 case LFUN_RECONFIGURE:
1676 // argument is any additional parameter to the configure.py command
1677 reconfigure(to_utf8(cmd.argument()));
1680 // --- lyxserver commands ----------------------------
1681 case LFUN_SERVER_GET_FILENAME: {
1682 if (current_view_ && current_view_->documentBufferView()) {
1683 docstring const fname = from_utf8(
1684 current_view_->documentBufferView()->buffer().absFileName());
1685 dr.setMessage(fname);
1686 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1688 dr.setMessage(docstring());
1689 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1694 case LFUN_SERVER_NOTIFY: {
1695 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1696 dr.setMessage(dispatch_buffer);
1697 theServer().notifyClient(to_utf8(dispatch_buffer));
1701 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1702 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1708 string rest = split(argument, countstr, ' ');
1709 istringstream is(countstr);
1712 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1713 for (int i = 0; i < count; ++i)
1714 dispatch(lyxaction.lookupFunc(rest));
1718 case LFUN_COMMAND_SEQUENCE: {
1719 // argument contains ';'-terminated commands
1720 string arg = argument;
1721 // FIXME: this LFUN should also work without any view.
1722 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1723 ? &(current_view_->documentBufferView()->buffer()) : 0;
1725 buffer->undo().beginUndoGroup();
1726 while (!arg.empty()) {
1728 arg = split(arg, first, ';');
1729 FuncRequest func(lyxaction.lookupFunc(first));
1730 func.setOrigin(cmd.origin());
1733 // the buffer may have been closed by one action
1734 if (theBufferList().isLoaded(buffer))
1735 buffer->undo().endUndoGroup();
1739 case LFUN_BUFFER_FORALL: {
1740 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1742 map<Buffer *, GuiView *> views_lVisible;
1743 map<GuiView *, Buffer *> activeBuffers;
1745 QList<GuiView *> allViews = d->views_.values();
1747 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1748 // and on which buffer is active in each view.
1749 Buffer * const last = theBufferList().last();
1750 foreach (GuiView * view, allViews) {
1751 // all of the buffers might be locally hidden. That is, there is no active buffer.
1752 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1753 activeBuffers[view] = 0;
1755 activeBuffers[view] = &view->currentBufferView()->buffer();
1757 // find out if each is locally visible or locally hidden.
1758 // we don't use a for loop as the buffer list cycles.
1759 Buffer * b = theBufferList().first();
1761 bool const locallyVisible = view && view->workArea(*b);
1762 if (locallyVisible) {
1763 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1764 // only need to overwrite/add if we don't already know a buffer is globally
1765 // visible or we do know but we would prefer to dispatch LFUN from the
1766 // current view because of cursor position issues.
1767 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1768 views_lVisible[b] = view;
1772 b = theBufferList().next(b);
1776 GuiView * const homeView = currentView();
1777 Buffer * b = theBufferList().first();
1778 Buffer * nextBuf = 0;
1779 int numProcessed = 0;
1782 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1784 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1786 // first change to a view where b is locally visible, preferably current_view_.
1787 GuiView * const vLv = views_lVisible[b];
1789 lyx::dispatch(funcToRun);
1797 // put things back to how they were (if possible).
1798 foreach (GuiView * view, allViews) {
1799 Buffer * originalBuf = activeBuffers[view];
1800 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1801 if (theBufferList().isLoaded(originalBuf))
1802 view->setBuffer(originalBuf);
1804 homeView->setFocus();
1806 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1810 case LFUN_COMMAND_ALTERNATIVES: {
1811 // argument contains ';'-terminated commands
1812 string arg = argument;
1813 while (!arg.empty()) {
1815 arg = split(arg, first, ';');
1816 FuncRequest func(lyxaction.lookupFunc(first));
1817 func.setOrigin(cmd.origin());
1818 FuncStatus const stat = getStatus(func);
1819 if (stat.enabled()) {
1829 if (theTopLevelCmdDef().lock(argument, func)) {
1830 func.setOrigin(cmd.origin());
1832 theTopLevelCmdDef().release(argument);
1834 if (func.action() == LFUN_UNKNOWN_ACTION) {
1835 // unknown command definition
1836 lyxerr << "Warning: unknown command definition `"
1840 // recursion detected
1841 lyxerr << "Warning: Recursion in the command definition `"
1842 << argument << "' detected"
1849 case LFUN_PREFERENCES_SAVE:
1850 lyxrc.write(support::makeAbsPath("preferences",
1851 package().user_support().absFileName()), false);
1854 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1855 string const fname = addName(addPath(package().user_support().absFileName(),
1856 "templates/"), "defaults.lyx");
1857 Buffer defaults(fname);
1859 istringstream ss(argument);
1862 int const unknown_tokens = defaults.readHeader(lex);
1864 if (unknown_tokens != 0) {
1865 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1866 << unknown_tokens << " unknown token"
1867 << (unknown_tokens == 1 ? "" : "s")
1871 if (defaults.writeFile(FileName(defaults.absFileName())))
1872 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1873 makeDisplayPath(fname)));
1876 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1881 case LFUN_BOOKMARK_GOTO:
1882 // go to bookmark, open unopened file and switch to buffer if necessary
1883 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1884 dr.screenUpdate(Update::Force | Update::FitCursor);
1887 case LFUN_BOOKMARK_CLEAR:
1888 theSession().bookmarks().clear();
1891 case LFUN_DEBUG_LEVEL_SET:
1892 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1896 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1899 current_view_->dispatch(cmd, dr);
1903 if (cmd.origin() == FuncRequest::LYXSERVER)
1904 updateCurrentView(cmd, dr);
1908 docstring GuiApplication::viewStatusMessage()
1910 // When meta-fake key is pressed, show the key sequence so far + "M-".
1911 if (d->meta_fake_bit != NoModifier)
1912 return d->keyseq.print(KeySequence::ForGui) + "M-";
1914 // Else, when a non-complete key sequence is pressed,
1915 // show the available options.
1916 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1917 return d->keyseq.printOptions(true);
1923 void GuiApplication::handleKeyFunc(FuncCode action)
1927 if (d->keyseq.length())
1929 GuiView * gv = currentView();
1930 LASSERT(gv && gv->currentBufferView(), return);
1931 BufferView * bv = gv->currentBufferView();
1932 bv->getIntl().getTransManager().deadkey(
1933 c, get_accent(action).accent, bv->cursor().innerText(),
1935 // Need to clear, in case the minibuffer calls these
1938 // copied verbatim from do_accent_char
1939 bv->cursor().resetAnchor();
1943 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1945 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1947 // Do nothing if we have nothing (JMarc)
1948 if (!keysym.isOK()) {
1949 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1951 current_view_->restartCursor();
1955 if (keysym.isModifier()) {
1957 current_view_->restartCursor();
1961 char_type encoded_last_key = keysym.getUCSEncoded();
1963 // Do a one-deep top-level lookup for
1964 // cancel and meta-fake keys. RVDK_PATCH_5
1965 d->cancel_meta_seq.reset();
1967 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1968 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1970 // When not cancel or meta-fake, do the normal lookup.
1971 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1972 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1973 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1974 // remove Caps Lock and Mod2 as a modifiers
1975 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1976 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1979 // Dont remove this unless you know what you are doing.
1980 d->meta_fake_bit = NoModifier;
1982 // Can this happen now ?
1983 if (func.action() == LFUN_NOACTION)
1984 func = FuncRequest(LFUN_COMMAND_PREFIX);
1986 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1987 << d->keyseq.print(KeySequence::Portable) << ']');
1989 // already here we know if it any point in going further
1990 // why not return already here if action == -1 and
1991 // num_bytes == 0? (Lgb)
1993 if (d->keyseq.length() > 1 && current_view_)
1994 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1997 // Maybe user can only reach the key via holding down shift.
1998 // Let's see. But only if shift is the only modifier
1999 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2000 LYXERR(Debug::KEY, "Trying without shift");
2001 func = d->keyseq.addkey(keysym, NoModifier);
2002 LYXERR(Debug::KEY, "Action now " << func.action());
2005 if (func.action() == LFUN_UNKNOWN_ACTION) {
2006 // Hmm, we didn't match any of the keysequences. See
2007 // if it's normal insertable text not already covered
2009 if (keysym.isText() && d->keyseq.length() == 1) {
2010 LYXERR(Debug::KEY, "isText() is true, inserting.");
2011 func = FuncRequest(LFUN_SELF_INSERT,
2012 FuncRequest::KEYBOARD);
2014 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2015 if (current_view_) {
2016 current_view_->message(_("Unknown function."));
2017 current_view_->restartCursor();
2023 if (func.action() == LFUN_SELF_INSERT) {
2024 if (encoded_last_key != 0) {
2025 docstring const arg(1, encoded_last_key);
2026 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2027 FuncRequest::KEYBOARD));
2028 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2031 processFuncRequest(func);
2035 void GuiApplication::processFuncRequest(FuncRequest const & func)
2037 lyx::dispatch(func);
2041 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2043 addToFuncRequestQueue(func);
2044 processFuncRequestQueueAsync();
2048 void GuiApplication::processFuncRequestQueue()
2050 while (!d->func_request_queue_.empty()) {
2051 processFuncRequest(d->func_request_queue_.front());
2052 d->func_request_queue_.pop();
2057 void GuiApplication::processFuncRequestQueueAsync()
2059 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2063 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2065 d->func_request_queue_.push(func);
2069 void GuiApplication::resetGui()
2071 // Set the language defined by the user.
2075 if (!readUIFile(toqstr(lyxrc.ui_file)))
2076 // Gives some error box here.
2079 if (d->global_menubar_)
2080 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2082 QHash<int, GuiView *>::iterator it;
2083 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2086 gv->setLayoutDirection(layoutDirection());
2090 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2094 void GuiApplication::createView(int view_id)
2096 createView(QString(), true, view_id);
2100 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2103 // release the keyboard which might have been grabed by the global
2104 // menubar on Mac to catch shortcuts even without any GuiView.
2105 if (d->global_menubar_)
2106 d->global_menubar_->releaseKeyboard();
2110 while (d->views_.find(id) != d->views_.end())
2113 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2114 GuiView * view = new GuiView(id);
2116 d->views_[id] = view;
2120 setActiveWindow(view);
2123 if (!geometry_arg.isEmpty()) {
2127 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2128 re.indexIn(geometry_arg);
2129 w = re.cap(1).toInt();
2130 h = re.cap(2).toInt();
2131 x = re.cap(3).toInt();
2132 y = re.cap(4).toInt();
2133 view->setGeometry(x, y, w, h);
2140 Clipboard & GuiApplication::clipboard()
2142 return d->clipboard_;
2146 Selection & GuiApplication::selection()
2148 return d->selection_;
2152 FontLoader & GuiApplication::fontLoader()
2154 return d->font_loader_;
2158 Toolbars const & GuiApplication::toolbars() const
2160 return d->toolbars_;
2164 Toolbars & GuiApplication::toolbars()
2166 return d->toolbars_;
2170 Menus const & GuiApplication::menus() const
2176 Menus & GuiApplication::menus()
2182 QList<int> GuiApplication::viewIds() const
2184 return d->views_.keys();
2188 ColorCache & GuiApplication::colorCache()
2190 return d->color_cache_;
2194 int GuiApplication::exec()
2196 // asynchronously handle batch commands. This event will be in
2197 // the event queue in front of other asynchronous events. Hence,
2198 // we can assume in the latter that the gui is setup already.
2199 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2201 return QApplication::exec();
2205 void GuiApplication::exit(int status)
2207 QApplication::exit(status);
2211 void GuiApplication::setGuiLanguage()
2213 QString const default_language = toqstr(getGuiMessages().language());
2214 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2215 QLocale const default_locale(default_language);
2216 QLocale::setDefault(default_locale);
2218 // install translation file for Qt built-in dialogs
2219 QString const language_name = QString("qt_") + default_locale.name();
2221 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2222 // Short-named translator can be loaded from a long name, but not the
2223 // opposite. Therefore, long name should be used without truncation.
2224 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2225 if (!d->qt_trans_.load(language_name,
2226 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2227 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2230 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2234 switch (default_locale.language()) {
2235 case QLocale::Arabic :
2236 case QLocale::Hebrew :
2237 case QLocale::Persian :
2238 case QLocale::Urdu :
2239 setLayoutDirection(Qt::RightToLeft);
2242 setLayoutDirection(Qt::LeftToRight);
2247 void GuiApplication::execBatchCommands()
2252 if (!readUIFile(toqstr(lyxrc.ui_file)))
2253 // Gives some error box here.
2257 #if QT_VERSION > 0x040600
2258 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2260 // Create the global default menubar which is shown for the dialogs
2261 // and if no GuiView is visible.
2262 // This must be done after the session was recovered to know the "last files".
2263 d->global_menubar_ = new GlobalMenuBar;
2264 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2267 lyx::execBatchCommands();
2271 QAbstractItemModel * GuiApplication::languageModel()
2273 if (d->language_model_)
2274 return d->language_model_;
2276 QStandardItemModel * lang_model = new QStandardItemModel(this);
2277 lang_model->insertColumns(0, 3);
2279 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2280 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2281 Languages::const_iterator it = lyx::languages.begin();
2282 Languages::const_iterator end = lyx::languages.end();
2283 for (; it != end; ++it) {
2284 current_row = lang_model->rowCount();
2285 lang_model->insertRows(current_row, 1);
2286 QModelIndex pl_item = lang_model->index(current_row, 0);
2287 QModelIndex sp_item = lang_model->index(current_row, 1);
2288 QModelIndex th_item = lang_model->index(current_row, 2);
2289 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2290 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2291 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2292 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2293 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2294 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2295 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2296 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2297 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2298 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2300 d->language_model_ = new QSortFilterProxyModel(this);
2301 d->language_model_->setSourceModel(lang_model);
2302 d->language_model_->setSortLocaleAware(true);
2303 return d->language_model_;
2307 void GuiApplication::restoreGuiSession()
2309 if (!lyxrc.load_session)
2312 Session & session = theSession();
2313 LastOpenedSection::LastOpened const & lastopened =
2314 session.lastOpened().getfiles();
2316 validateCurrentView();
2318 FileName active_file;
2319 // do not add to the lastfile list since these files are restored from
2320 // last session, and should be already there (regular files), or should
2321 // not be added at all (help files).
2322 for (size_t i = 0; i < lastopened.size(); ++i) {
2323 FileName const & file_name = lastopened[i].file_name;
2324 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2325 && current_view_->documentBufferView() != 0)) {
2326 boost::crc_32_type crc;
2327 string const & fname = file_name.absFileName();
2328 crc = for_each(fname.begin(), fname.end(), crc);
2329 createView(crc.checksum());
2331 current_view_->loadDocument(file_name, false);
2333 if (lastopened[i].active)
2334 active_file = file_name;
2337 // Restore last active buffer
2338 Buffer * buffer = theBufferList().getBuffer(active_file);
2339 if (buffer && current_view_)
2340 current_view_->setBuffer(buffer);
2342 // clear this list to save a few bytes of RAM
2343 session.lastOpened().clear();
2347 QString const GuiApplication::romanFontName()
2350 font.setKerning(false);
2351 font.setStyleHint(QFont::Serif);
2352 font.setFamily("serif");
2354 return QFontInfo(font).family();
2358 QString const GuiApplication::sansFontName()
2361 font.setKerning(false);
2362 font.setStyleHint(QFont::SansSerif);
2363 font.setFamily("sans");
2365 return QFontInfo(font).family();
2369 QString const GuiApplication::typewriterFontName()
2372 font.setKerning(false);
2373 font.setStyleHint(QFont::TypeWriter);
2374 font.setFamily("monospace");
2376 return QFontInfo(font).family();
2380 void GuiApplication::handleRegularEvents()
2382 ForkedCallsController::handleCompletedProcesses();
2386 bool GuiApplication::event(QEvent * e)
2389 case QEvent::FileOpen: {
2390 // Open a file; this happens only on Mac OS X for now.
2392 // We do this asynchronously because on startup the batch
2393 // commands are not executed here yet and the gui is not ready
2395 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2396 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2397 processFuncRequestAsync(fr);
2402 return QApplication::event(e);
2407 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2410 return QApplication::notify(receiver, event);
2412 catch (ExceptionMessage const & e) {
2414 case ErrorException:
2416 setQuitOnLastWindowClosed(false);
2418 Alert::error(e.title_, e.details_);
2420 // Properly crash in debug mode in order to get a useful backtrace.
2423 // In release mode, try to exit gracefully.
2426 case BufferException: {
2427 if (!current_view_ || !current_view_->documentBufferView())
2429 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2430 docstring details = e.details_ + '\n';
2431 details += buf->emergencyWrite();
2432 theBufferList().release(buf);
2433 details += "\n" + _("The current document was closed.");
2434 Alert::error(e.title_, details);
2437 case WarningException:
2438 Alert::warning(e.title_, e.details_);
2442 catch (exception const & e) {
2443 docstring s = _("LyX has caught an exception, it will now "
2444 "attempt to save all unsaved documents and exit."
2446 s += from_ascii(e.what());
2447 Alert::error(_("Software exception Detected"), s);
2451 docstring s = _("LyX has caught some really weird exception, it will "
2452 "now attempt to save all unsaved documents and exit.");
2453 Alert::error(_("Software exception Detected"), s);
2461 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2463 QColor const & qcol = d->color_cache_.get(col);
2464 if (!qcol.isValid()) {
2470 rgbcol.r = qcol.red();
2471 rgbcol.g = qcol.green();
2472 rgbcol.b = qcol.blue();
2477 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2479 QColor const qcol(lcolor.getX11Name(col).c_str());
2480 if (!qcol.isValid()) {
2486 rgbcol.r = qcol.red();
2487 rgbcol.g = qcol.green();
2488 rgbcol.b = qcol.blue();
2493 string const GuiApplication::hexName(ColorCode col)
2495 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2499 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2501 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2502 d->socket_notifiers_[fd] = sn;
2503 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2507 void GuiApplication::socketDataReceived(int fd)
2509 d->socket_notifiers_[fd]->func_();
2513 void GuiApplication::unregisterSocketCallback(int fd)
2515 d->socket_notifiers_.take(fd)->setEnabled(false);
2519 void GuiApplication::commitData(QSessionManager & sm)
2521 /// The implementation is required to avoid an application exit
2522 /// when session state save is triggered by session manager.
2523 /// The default implementation sends a close event to all
2524 /// visible top level widgets when session managment allows
2526 /// We are changing that to close all wiew one by one.
2527 /// FIXME: verify if the default implementation is enough now.
2528 #ifdef QT_NO_SESSIONMANAGER
2530 #warning Qt is compiled without session manager
2532 #pragma message("warning: Qt is compiled without session manager")
2536 if (sm.allowsInteraction() && !closeAllViews())
2542 void GuiApplication::unregisterView(GuiView * gv)
2544 LAPPERR(d->views_[gv->id()] == gv);
2545 d->views_.remove(gv->id());
2546 if (current_view_ == gv)
2551 bool GuiApplication::closeAllViews()
2553 if (d->views_.empty())
2556 // When a view/window was closed before without quitting LyX, there
2557 // are already entries in the lastOpened list.
2558 theSession().lastOpened().clear();
2560 QList<GuiView *> const views = d->views_.values();
2561 foreach (GuiView * view, views) {
2562 if (!view->closeScheduled())
2571 GuiView & GuiApplication::view(int id) const
2573 LAPPERR(d->views_.contains(id));
2574 return *d->views_.value(id);
2578 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2580 QList<GuiView *> const views = d->views_.values();
2581 foreach (GuiView * view, views)
2582 view->hideDialog(name, inset);
2586 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2588 Buffer const * buffer_ = 0;
2589 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2590 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2591 if (Buffer const * ptr = (*it)->updateInset(inset))
2598 bool GuiApplication::searchMenu(FuncRequest const & func,
2599 docstring_list & names) const
2601 return d->menus_.searchMenu(func, names);
2605 // Ensure that a file is read only once (prevents include loops)
2606 static QStringList uifiles;
2607 // store which ui files define Toolbars
2608 static QStringList toolbar_uifiles;
2611 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2622 LexerKeyword uitags[] = {
2623 { "format", ui_format },
2624 { "include", ui_include },
2625 { "menuset", ui_menuset },
2626 { "toolbars", ui_toolbars },
2627 { "toolbarset", ui_toolbarset }
2631 lex.setFile(ui_path);
2633 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2637 if (lyxerr.debugging(Debug::PARSER))
2638 lex.printTable(lyxerr);
2641 // format before introduction of format tag
2642 unsigned int format = 0;
2643 while (lex.isOK()) {
2644 int const status = lex.lex();
2646 // we have to do this check here, outside the switch,
2647 // because otherwise we would start reading include files,
2648 // e.g., if the first tag we hit was an include tag.
2649 if (status == ui_format)
2651 format = lex.getInteger();
2655 // this will trigger unless the first tag we hit is a format
2656 // tag, with the right format.
2657 if (format != LFUN_FORMAT)
2658 return FormatMismatch;
2661 case Lexer::LEX_FEOF:
2666 QString const file = toqstr(lex.getString());
2667 bool const success = readUIFile(file, true);
2669 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2676 d->menus_.read(lex);
2680 d->toolbars_.readToolbars(lex);
2684 d->toolbars_.readToolbarSettings(lex);
2685 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2689 if (!rtrim(lex.getString()).empty())
2690 lex.printError("LyX::ReadUIFile: "
2691 "Unknown menu tag: `$$Token'");
2693 LYXERR0("Error with status: " << status);
2699 return (error ? ReadError : ReadOK);
2703 bool GuiApplication::readUIFile(QString const & name, bool include)
2705 LYXERR(Debug::INIT, "About to read " << name << "...");
2709 ui_path = libFileSearch("ui", name, "inc");
2710 if (ui_path.empty())
2711 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2713 ui_path = libFileSearch("ui", name, "ui");
2716 if (ui_path.empty()) {
2717 static const QString defaultUIFile = "default";
2718 LYXERR(Debug::INIT, "Could not find " << name);
2720 Alert::warning(_("Could not find UI definition file"),
2721 bformat(_("Error while reading the included file\n%1$s\n"
2722 "Please check your installation."), qstring_to_ucs4(name)));
2725 if (name == defaultUIFile) {
2726 LYXERR(Debug::INIT, "Could not find default UI file!!");
2727 Alert::warning(_("Could not find default UI file"),
2728 _("LyX could not find the default UI file!\n"
2729 "Please check your installation."));
2732 Alert::warning(_("Could not find UI definition file"),
2733 bformat(_("Error while reading the configuration file\n%1$s\n"
2734 "Falling back to default.\n"
2735 "Please look under Tools>Preferences>User Interface and\n"
2736 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2737 return readUIFile(defaultUIFile, false);
2740 QString const uifile = toqstr(ui_path.absFileName());
2741 if (uifiles.contains(uifile)) {
2743 // We are reading again the top uifile so reset the safeguard:
2746 d->toolbars_.reset();
2748 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2749 << "Is this an include loop?");
2753 uifiles.push_back(uifile);
2755 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2757 ReturnValues retval = readUIFile(ui_path);
2759 if (retval == FormatMismatch) {
2760 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2761 FileName const tempfile = FileName::tempName("convert_ui");
2762 bool const success = prefs2prefs(ui_path, tempfile, true);
2764 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2765 " to format " << LFUN_FORMAT << ".");
2767 retval = readUIFile(tempfile);
2768 tempfile.removeFile();
2772 if (retval != ReadOK) {
2773 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2781 settings.beginGroup("ui_files");
2782 bool touched = false;
2783 for (int i = 0; i != uifiles.size(); ++i) {
2784 QFileInfo fi(uifiles[i]);
2785 QDateTime const date_value = fi.lastModified();
2786 QString const name_key = QString::number(i);
2787 // if an ui file which defines Toolbars has changed,
2788 // we have to reset the settings
2789 if (toolbar_uifiles.contains(uifiles[i])
2790 && (!settings.contains(name_key)
2791 || settings.value(name_key).toString() != uifiles[i]
2792 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2794 settings.setValue(name_key, uifiles[i]);
2795 settings.setValue(name_key + "/date", date_value);
2798 settings.endGroup();
2800 settings.remove("views");
2806 void GuiApplication::onLastWindowClosed()
2808 if (d->global_menubar_)
2809 d->global_menubar_->grabKeyboard();
2813 void GuiApplication::startLongOperation() {
2814 d->key_checker_.start();
2818 bool GuiApplication::longOperationCancelled() {
2819 return d->key_checker_.pressed();
2823 void GuiApplication::stopLongOperation() {
2824 d->key_checker_.stop();
2828 bool GuiApplication::longOperationStarted() {
2829 return d->key_checker_.started();
2833 ////////////////////////////////////////////////////////////////////////
2835 // X11 specific stuff goes here...
2838 bool GuiApplication::x11EventFilter(XEvent * xev)
2843 switch (xev->type) {
2844 case SelectionRequest: {
2845 if (xev->xselectionrequest.selection != XA_PRIMARY)
2847 LYXERR(Debug::SELECTION, "X requested selection.");
2848 BufferView * bv = current_view_->currentBufferView();
2850 docstring const sel = bv->requestSelection();
2852 d->selection_.put(sel);
2856 case SelectionClear: {
2857 if (xev->xselectionclear.selection != XA_PRIMARY)
2859 LYXERR(Debug::SELECTION, "Lost selection.");
2860 BufferView * bv = current_view_->currentBufferView();
2862 bv->clearSelection();
2870 } // namespace frontend
2873 void hideDialogs(std::string const & name, Inset * inset)
2876 frontend::guiApp->hideDialogs(name, inset);
2880 ////////////////////////////////////////////////////////////////////
2884 ////////////////////////////////////////////////////////////////////
2886 frontend::FontLoader & theFontLoader()
2888 LAPPERR(frontend::guiApp);
2889 return frontend::guiApp->fontLoader();
2893 frontend::FontMetrics const & theFontMetrics(Font const & f)
2895 return theFontMetrics(f.fontInfo());
2899 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2901 LAPPERR(frontend::guiApp);
2902 return frontend::guiApp->fontLoader().metrics(f);
2906 ////////////////////////////////////////////////////////////////////
2910 ////////////////////////////////////////////////////////////////////
2912 frontend::Clipboard & theClipboard()
2914 LAPPERR(frontend::guiApp);
2915 return frontend::guiApp->clipboard();
2919 frontend::Selection & theSelection()
2921 LAPPERR(frontend::guiApp);
2922 return frontend::guiApp->selection();
2928 #include "moc_GuiApplication.cpp"