2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ColorCache.h"
19 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "GuiWorkArea.h"
45 #include "LaTeXPackages.h"
48 #include "LyXAction.h"
50 #include "Paragraph.h"
53 #include "SpellChecker.h"
54 #include "Thesaurus.h"
57 #include "support/convert.h"
58 #include "support/debug.h"
59 #include "support/ExceptionMessage.h"
60 #include "support/FileName.h"
61 #include "support/filetools.h"
62 #include "support/foreach.h"
63 #include "support/ForkedCalls.h"
64 #include "support/gettext.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/lyxalgo.h" // sorted
68 #include "support/Messages.h"
69 #include "support/os.h"
70 #include "support/Package.h"
71 #include "support/PathChanger.h"
72 #include "support/Systemcall.h"
75 #include "support/AppleScript.h"
76 #include "support/linkback/LinkBackProxy.h"
87 #include <QFileOpenEvent>
91 #include <QImageReader>
94 #include <QLibraryInfo>
100 #include <QPixmapCache>
102 #include <QSessionManager>
104 #include <QShowEvent>
105 #include <QSocketNotifier>
106 #include <QSortFilterProxyModel>
107 #include <QStandardItemModel>
108 #include <QTextCodec>
110 #include <QTranslator>
111 #include <QThreadPool>
115 #include <X11/Xatom.h>
116 #include <X11/Xlib.h>
122 #include <QWindowsMime>
130 #include <QMacPasteboardMime>
133 #include "support/bind.h"
134 #include <boost/crc.hpp>
141 using namespace lyx::support;
144 static void initializeResources()
146 static bool initialized = false;
148 Q_INIT_RESOURCE(Resources);
156 frontend::Application * createApplication(int & argc, char * argv[])
159 // prune -geometry argument(s) by shifting
160 // the following ones 2 places down.
161 for (int i = 0 ; i < argc ; ++i) {
162 if (strcmp(argv[i], "-geometry") == 0) {
163 int const remove = (i+1) < argc ? 2 : 1;
165 for (int j = i; j < argc; ++j)
166 argv[j] = argv[j + remove];
171 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
172 // I'd rather do that in the constructor, but I do not think that
173 // the palette is accessible there.
174 guiApp->colorCache().setPalette(guiApp->palette());
182 if (lyxrc.gui_language == "auto") {
183 theLocale = QLocale::system();
185 Language const * l = languages.getLanguage(lyxrc.gui_language);
186 string const code = l ? l->code() : string();
187 theLocale = QLocale(toqstr(code));
189 Messages::guiLanguage(fromqstr(theLocale.name()));
190 QLocale::setDefault(theLocale);
197 /// Return the list of loadable formats.
198 vector<string> loadableImageFormats()
202 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
204 LYXERR(Debug::GRAPHICS,
205 "\nThe image loader can load the following directly:\n");
207 if (qt_formats.empty())
208 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
210 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
212 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
214 string ext = ascii_lowercase((const char *) *it);
225 ////////////////////////////////////////////////////////////////////////
227 // Icon loading support code
229 ////////////////////////////////////////////////////////////////////////
239 bool operator<(PngMap const & lhs, PngMap const & rhs)
241 return lhs.key < rhs.key;
247 CompareKey(QString const & name) : name_(name) {}
248 bool operator()(PngMap const & other) const { return other.key == name_; }
254 // this must be sorted alphabetically
255 // Upper case comes before lower case
256 // Please don't change the formatting, this list is parsed by
257 // development/tools/generate_symbols_images.py.
258 PngMap sorted_png_map[] = {
259 { "Arrownot", "arrownot2"},
260 { "Arrowvert", "arrowvert2"},
261 { "Bowtie", "bowtie2" },
263 { "Bumpeq", "bumpeq2" },
264 { "CIRCLE", "circle3" },
266 { "CheckedBox", "checkedbox2" },
267 { "Circle", "circle2" },
268 { "Colonapprox", "colonapprox2" },
269 { "Coloneq", "coloneq2" },
270 { "Coloneqq", "coloneqq2" },
271 { "Colonsim", "colonsim2" },
273 { "DOWNarrow", "downarrow3" },
274 { "Delta", "delta2" },
275 { "Diamond", "diamond2" },
276 { "Doteq", "doteq2" },
277 { "Downarrow", "downarrow2" },
278 { "Eqcolon", "eqcolon2" },
279 { "Eqqcolon", "eqqcolon2" },
280 { "Gamma", "gamma2" },
282 { "LEFTCIRCLE", "leftcircle3" },
283 { "LEFTarrow", "leftarrow3" },
284 { "LEFTcircle", "leftcircle4" },
286 { "Lambda", "lambda2" },
288 { "Leftarrow", "leftarrow2" },
289 { "Leftcircle", "leftcircle2" },
290 { "Leftrightarrow", "leftrightarrow2" },
291 { "Longarrownot", "longarrownot2"},
292 { "Longleftarrow", "longleftarrow2" },
293 { "Longleftrightarrow", "longleftrightarrow2" },
294 { "Longmapsfrom", "longmapsfrom2"},
295 { "Longmapsto", "longmapsto2"},
296 { "Longrightarrow", "longrightarrow2" },
297 { "Mapsfrom", "mapsfrom2"},
298 { "Mapsfromchar", "mapsfromchar2"},
299 { "Mapsto", "mapsto2"},
300 { "Mapstochar", "mapstochar2"},
301 { "Omega", "omega2" },
306 { "RIGHTCIRCLE", "rightcircle3" },
307 { "RIGHTarrow", "rightarrow3" },
308 { "RIGHTcircle", "rightcircle4" },
310 { "Rightarrow", "rightarrow2" },
311 { "Rightcircle", "rightcircle2" },
312 { "Sigma", "sigma2" },
313 { "Square", "square2" },
314 { "Subset", "subset2" },
315 { "Supset", "supset2" },
316 { "Theta", "theta2" },
317 { "Thorn", "thorn2" },
318 { "UParrow", "uparrow3" },
319 { "Uparrow", "uparrow2" },
320 { "Updownarrow", "updownarrow2" },
321 { "Upsilon", "upsilon2" },
322 { "Vdash", "vdash3" },
327 { "nLeftarrow", "nleftarrow2" },
328 { "nLeftrightarrow", "nleftrightarrow2" },
329 { "nRightarrow", "nrightarrow2" },
330 { "nVDash", "nvdash3" },
331 { "nVdash", "nvdash4" },
332 { "nvDash", "nvdash2" },
333 { "textrm \\AA", "textrm_AA"},
334 { "textrm \\O", "textrm_O"},
335 { "vDash", "vdash2" },
336 { "varDelta", "vardelta2" },
337 { "varGamma", "vargamma2" },
338 { "varLambda", "varlambda2" },
339 { "varOmega", "varomega2" },
340 { "varPhi", "varphi2" },
341 { "varPi", "varpi2" },
342 { "varPsi", "varpsi2" },
343 { "varSigma", "varsigma2" },
344 { "varTheta", "vartheta2" },
345 { "varUpsilon", "varupsilon2" },
346 { "varXi", "varxi2" }
350 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
352 // This list specifies which system's theme icon is related to which lyx
353 // command. It was based on:
354 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
355 // this must be sorted alphabetically
356 // Upper case comes before lower case
357 PngMap sorted_theme_icon_map[] = {
358 { "bookmark-goto 0", "go-jump" },
359 { "buffer-new", "document-new" },
360 { "buffer-print", "document-print" },
361 { "buffer-write", "document-save" },
362 { "buffer-write-as", "document-save-as" },
363 { "buffer-zoom-in", "zoom-in" },
364 { "buffer-zoom-out", "zoom-out" },
365 { "copy", "edit-copy" },
366 { "cut", "edit-cut" },
367 { "depth-decrement", "format-indent-less" },
368 { "depth-increment", "format-indent-more" },
369 { "dialog-show print", "document-print" },
370 { "dialog-show spellchecker", "tools-check-spelling" },
371 { "dialog-show-new-inset graphics", "insert-image" },
372 { "dialog-toggle findreplaceadv", "edit-find-replace" },
373 { "file-open", "document-open" },
374 { "font-bold", "format-text-bold" },
375 { "font-ital", "format-text-italic" },
376 { "font-strikeout", "format-text-strikethrough" },
377 { "font-underline", "format-text-underline" },
378 { "lyx-quit", "application-exit" },
379 { "paste", "edit-paste" },
380 { "redo", "edit-redo" },
381 { "undo", "edit-undo" },
382 { "window-close", "window-close" },
383 { "window-new", "window-new" }
386 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
389 QString findPng(QString const & name)
391 PngMap const * const begin = sorted_png_map;
392 PngMap const * const end = begin + nr_sorted_png_map;
393 LATTEST(sorted(begin, end));
395 PngMap const * const it = find_if(begin, end, CompareKey(name));
399 png_name = it->value;
402 png_name.replace('_', "underscore");
403 png_name.replace(' ', '_');
405 // This way we can have "math-delim { }" on the toolbar.
406 png_name.replace('(', "lparen");
407 png_name.replace(')', "rparen");
408 png_name.replace('[', "lbracket");
409 png_name.replace(']', "rbracket");
410 png_name.replace('{', "lbrace");
411 png_name.replace('}', "rbrace");
412 png_name.replace('|', "bars");
413 png_name.replace(',', "thinspace");
414 png_name.replace(':', "mediumspace");
415 png_name.replace(';', "thickspace");
416 png_name.replace('!', "negthinspace");
419 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
420 << "Looking for math PNG called \"" << png_name << '"');
427 QString themeIconName(QString const & action)
429 PngMap const * const begin = sorted_theme_icon_map;
430 PngMap const * const end = begin + nr_sorted_theme_icon_map;
431 LASSERT(sorted(begin, end), /**/);
433 PngMap const * const it = find_if(begin, end, CompareKey(action));
441 QString iconName(FuncRequest const & f, bool unknown)
443 initializeResources();
447 switch (f.action()) {
448 case LFUN_MATH_INSERT:
449 if (!f.argument().empty()) {
451 name1 = findPng(toqstr(f.argument()).mid(1));
454 case LFUN_MATH_DELIM:
455 case LFUN_MATH_BIGDELIM:
457 name1 = findPng(toqstr(f.argument()));
461 name1 = toqstr(f.argument());
463 case LFUN_COMMAND_ALTERNATIVES: {
464 // use the first of the alternative commands
466 docstring dummy = split(f.argument(), firstcom, ';');
467 name1 = toqstr(firstcom);
468 // FIXME: we should rename the icons to tabular-xxx instead of
469 // "tabular-feature-xxx"
470 name1.replace("inset-modify tabular", "tabular-feature");
471 name1.replace(' ', '_');
474 case LFUN_INSET_MODIFY: {
475 // FIXME: we should rename the icons to tabular-xxx instead of
476 // "tabular-feature-xxx" and generalize this naming to all
477 // insets, not to tabular using ones.
479 string const command = split(to_utf8(f.argument()), inset_name, ' ');
480 if (insetCode(inset_name) == TABULAR_CODE) {
481 name1 = "tabular-feature "+ toqstr(command);
482 name1.replace(' ', '_');
487 name2 = toqstr(lyxaction.getActionName(f.action()));
490 if (!f.argument().empty()) {
491 name1 = name2 + ' ' + toqstr(f.argument());
492 name1.replace(' ', '_');
493 name1.replace('\\', "backslash");
497 QStringList imagedirs;
498 imagedirs << "images/" << "images/ipa/";
499 for (int i = 0; i < imagedirs.size(); ++i) {
500 QString imagedir = imagedirs.at(i) + path;
501 FileName fname = imageLibFileSearch(imagedir, name1, "png");
503 return toqstr(fname.absFileName());
505 fname = imageLibFileSearch(imagedir, name2, "png");
507 return toqstr(fname.absFileName());
510 path = ":/images/" + path;
513 LYXERR0("Directory " << path << " not found in resource!");
517 if (res.exists(name1))
521 if (res.exists(name2))
524 LYXERR(Debug::GUI, "Cannot find icon with filename "
525 << "\"" << name1 << "\""
527 << "\"" << name2 << "\""
529 << lyxaction.getActionName(f.action())
530 << '(' << to_utf8(f.argument()) << ")\"");
533 QString imagedir = "images/";
534 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
536 return toqstr(fname.absFileName());
537 return QString(":/images/unknown.png");
543 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
546 QString imagedir = path;
547 FileName fname = imageLibFileSearch(imagedir, name, ext);
548 QString path1 = toqstr(fname.absFileName());
549 QString path2 = ":/" + path + name + "." + ext;
551 if (pixmap.load(path1)) {
554 else if (pixmap.load(path2)) {
558 LYXERR0("Cannot load pixmap \""
559 << path << name << '.' << ext
560 << "\", please verify resource system!");
565 QIcon getIcon(FuncRequest const & f, bool unknown)
567 #if (QT_VERSION >= 0x040600)
568 if (lyxrc.use_system_theme_icons) {
569 QString action = toqstr(lyxaction.getActionName(f.action()));
570 if (!f.argument().empty())
571 action += " " + toqstr(f.argument());
572 QString const theme_icon = themeIconName(action);
573 if (QIcon::hasThemeIcon(theme_icon))
574 return QIcon::fromTheme(theme_icon);
578 QString icon = iconName(f, unknown);
582 //LYXERR(Debug::GUI, "Found icon: " << icon);
584 if (!pm.load(icon)) {
585 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
593 ////////////////////////////////////////////////////////////////////////
595 // LyX server support code.
597 ////////////////////////////////////////////////////////////////////////
599 class SocketNotifier : public QSocketNotifier
602 /// connect a connection notification from the LyXServerSocket
603 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
604 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
608 /// The callback function
609 Application::SocketCallback func_;
613 ////////////////////////////////////////////////////////////////////////
615 // Mac specific stuff goes here...
617 ////////////////////////////////////////////////////////////////////////
619 class MenuTranslator : public QTranslator
622 MenuTranslator(QObject * parent)
623 : QTranslator(parent)
626 QString translate(const char * /*context*/,
627 const char * sourceText,
628 const char * /*comment*/ = 0) const
630 string const s = sourceText;
631 if (s == N_("About %1") || s == N_("Preferences")
632 || s == N_("Reconfigure") || s == N_("Quit %1"))
639 class GlobalMenuBar : public QMenuBar
643 GlobalMenuBar() : QMenuBar(0) {}
646 bool event(QEvent * e)
648 if (e->type() == QEvent::ShortcutOverride) {
649 // && activeWindow() == 0) {
650 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
652 setKeySymbol(&sym, ke);
653 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
662 // QMacPasteboardMimeGraphics can only be compiled on Mac.
664 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
667 QMacPasteboardMimeGraphics()
668 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
671 QString convertorName() { return "Graphics"; }
673 QString flavorFor(QString const & mime)
675 LYXERR(Debug::ACTION, "flavorFor " << mime);
676 if (mime == pdfMimeType())
677 return QLatin1String("com.adobe.pdf");
681 QString mimeFor(QString flav)
683 LYXERR(Debug::ACTION, "mimeFor " << flav);
684 if (flav == QLatin1String("com.adobe.pdf"))
685 return pdfMimeType();
689 bool canConvert(QString const & mime, QString flav)
691 return mimeFor(flav) == mime;
694 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
698 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
702 QList<QByteArray> convertFromMime(QString const & /*mime*/,
703 QVariant data, QString /*flav*/)
705 QList<QByteArray> ret;
706 ret.append(data.toByteArray());
712 ///////////////////////////////////////////////////////////////
714 // You can find more platform specific stuff at the end of this file...
716 ///////////////////////////////////////////////////////////////
718 ////////////////////////////////////////////////////////////////////////
719 // Windows specific stuff goes here...
722 // QWindowsMimeMetafile can only be compiled on Windows.
724 static FORMATETC cfFromMime(QString const & mimetype)
727 if (mimetype == emfMimeType()) {
728 formatetc.cfFormat = CF_ENHMETAFILE;
729 formatetc.tymed = TYMED_ENHMF;
730 } else if (mimetype == wmfMimeType()) {
731 formatetc.cfFormat = CF_METAFILEPICT;
732 formatetc.tymed = TYMED_MFPICT;
735 formatetc.dwAspect = DVASPECT_CONTENT;
736 formatetc.lindex = -1;
741 class QWindowsMimeMetafile : public QWindowsMime {
743 QWindowsMimeMetafile() {}
745 bool canConvertFromMime(FORMATETC const & formatetc,
746 QMimeData const * mimedata) const
751 bool canConvertToMime(QString const & mimetype,
752 IDataObject * pDataObj) const
754 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
756 FORMATETC formatetc = cfFromMime(mimetype);
757 return pDataObj->QueryGetData(&formatetc) == S_OK;
760 bool convertFromMime(FORMATETC const & formatetc,
761 const QMimeData * mimedata, STGMEDIUM * pmedium) const
766 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
767 QVariant::Type preferredType) const
770 if (!canConvertToMime(mimetype, pDataObj))
773 FORMATETC formatetc = cfFromMime(mimetype);
775 if (pDataObj->GetData(&formatetc, &s) != S_OK)
779 if (s.tymed == TYMED_ENHMF) {
780 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
781 data.resize(dataSize);
782 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
783 (LPBYTE)data.data());
784 } else if (s.tymed == TYMED_MFPICT) {
785 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
786 data.resize(dataSize);
787 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
788 (LPBYTE)data.data());
791 ReleaseStgMedium(&s);
797 QVector<FORMATETC> formatsForMime(QString const & mimetype,
798 QMimeData const * mimedata) const
800 QVector<FORMATETC> formats;
801 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
802 formats += cfFromMime(mimetype);
806 QString mimeForFormat(FORMATETC const & formatetc) const
808 switch (formatetc.cfFormat) {
810 return emfMimeType();
811 case CF_METAFILEPICT:
812 return wmfMimeType();
821 /// Allows to check whether ESC was pressed during a long operation
822 class KeyChecker : public QObject {
827 KeyChecker() : pressed_(false), started_(false) {}
830 QCoreApplication::instance()->installEventFilter(this);
835 QCoreApplication::instance()->removeEventFilter(this);
839 QCoreApplication::processEvents();
842 bool started() const {
845 bool eventFilter(QObject *obj, QEvent *event) {
846 LYXERR(Debug::ACTION, "Event Type: " << event->type());
847 switch (event->type()) {
851 return QObject::eventFilter(obj, event);
853 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
854 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
862 ////////////////////////////////////////////////////////////////////////
863 // GuiApplication::Private definition and implementation.
864 ////////////////////////////////////////////////////////////////////////
866 struct GuiApplication::Private
868 Private(): language_model_(0), meta_fake_bit(NoModifier),
872 /// WMF Mime handler for Windows clipboard.
873 wmf_mime_ = new QWindowsMimeMetafile;
875 initKeySequences(&theTopLevelKeymap());
878 void initKeySequences(KeyMap * kb)
880 keyseq = KeySequence(kb, kb);
881 cancel_meta_seq = KeySequence(kb, kb);
885 QSortFilterProxyModel * language_model_;
887 GuiClipboard clipboard_;
889 GuiSelection selection_;
891 FontLoader font_loader_;
893 ColorCache color_cache_;
895 QTranslator qt_trans_;
897 QHash<int, SocketNotifier *> socket_notifiers_;
901 /// The global instance
904 /// this timer is used for any regular events one wants to
905 /// perform. at present it is used to check if forked processes
907 QTimer general_timer_;
909 /// delayed FuncRequests
910 std::queue<FuncRequest> func_request_queue_;
915 KeySequence cancel_meta_seq;
917 KeyModifier meta_fake_bit;
919 /// Multiple views container.
921 * Warning: This must not be a smart pointer as the destruction of the
922 * object is handled by Qt when the view is closed
923 * \sa Qt::WA_DeleteOnClose attribute.
925 QHash<int, GuiView *> views_;
927 /// Only used on mac.
928 GlobalMenuBar * global_menubar_;
931 /// Linkback mime handler for MacOSX.
932 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
936 /// WMF Mime handler for Windows clipboard.
937 QWindowsMimeMetafile * wmf_mime_;
940 /// Allows to check whether ESC was pressed during a long operation
941 KeyChecker key_checker_;
945 GuiApplication * guiApp;
947 GuiApplication::~GuiApplication()
950 closeAllLinkBackLinks();
956 GuiApplication::GuiApplication(int & argc, char ** argv)
957 : QApplication(argc, argv), current_view_(0),
958 d(new GuiApplication::Private)
960 QString app_name = "LyX";
961 QCoreApplication::setOrganizationName(app_name);
962 QCoreApplication::setOrganizationDomain("lyx.org");
963 QCoreApplication::setApplicationName(lyx_package);
965 qsrand(QDateTime::currentDateTime().toTime_t());
967 // Install translator for GUI elements.
968 installTranslator(&d->qt_trans_);
970 // FIXME: quitOnLastWindowClosed is true by default. We should have a
971 // lyxrc setting for this in order to let the application stay resident.
972 // But then we need some kind of dock icon, at least on Windows.
974 if (lyxrc.quit_on_last_window_closed)
975 setQuitOnLastWindowClosed(false);
978 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
979 // seems to be the default case for applications like LyX.
980 setQuitOnLastWindowClosed(false);
981 // This allows to translate the strings that appear in the LyX menu.
982 /// A translator suitable for the entries in the LyX menu.
983 /// Only needed with Qt/Mac.
984 installTranslator(new MenuTranslator(this));
990 // doubleClickInterval() is 400 ms on X11 which is just too long.
991 // On Windows and Mac OS X, the operating system's value is used.
992 // On Microsoft Windows, calling this function sets the double
993 // click interval for all applications. So we don't!
994 QApplication::setDoubleClickInterval(300);
997 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
999 // needs to be done before reading lyxrc
1001 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1005 // Set the cache to 5120 kilobytes which corresponds to screen size of
1006 // 1280 by 1024 pixels with a color depth of 32 bits.
1007 QPixmapCache::setCacheLimit(5120);
1009 // Initialize RC Fonts
1010 if (lyxrc.roman_font_name.empty())
1011 lyxrc.roman_font_name = fromqstr(romanFontName());
1013 if (lyxrc.sans_font_name.empty())
1014 lyxrc.sans_font_name = fromqstr(sansFontName());
1016 if (lyxrc.typewriter_font_name.empty())
1017 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1019 d->general_timer_.setInterval(500);
1020 connect(&d->general_timer_, SIGNAL(timeout()),
1021 this, SLOT(handleRegularEvents()));
1022 d->general_timer_.start();
1024 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1025 // This is clearly not enough in a time where we use threads for
1026 // document preview and/or export. 20 should be OK.
1027 QThreadPool::globalInstance()->setMaxThreadCount(20);
1031 GuiApplication * theGuiApp()
1033 return dynamic_cast<GuiApplication *>(theApp());
1037 void GuiApplication::clearSession()
1044 docstring Application::iconName(FuncRequest const & f, bool unknown)
1046 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1050 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1054 BufferView * bv = 0;
1055 BufferView * doc_bv = 0;
1057 if (cmd.action() == LFUN_NOACTION) {
1058 status.message(from_utf8(N_("Nothing to do")));
1059 status.setEnabled(false);
1062 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1063 status.setUnknown(true);
1064 status.message(from_utf8(N_("Unknown action")));
1065 status.setEnabled(false);
1068 // Does the GuiApplication know something?
1069 else if (getStatus(cmd, status)) { }
1071 // If we do not have a GuiView, then other functions are disabled
1072 else if (!current_view_)
1073 status.setEnabled(false);
1075 // Does the GuiView know something?
1076 else if (current_view_->getStatus(cmd, status)) { }
1078 // In LyX/Mac, when a dialog is open, the menus of the
1079 // application can still be accessed without giving focus to
1080 // the main window. In this case, we want to disable the menu
1081 // entries that are buffer or view-related.
1082 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1084 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1085 status.setEnabled(false);
1088 // If we do not have a BufferView, then other functions are disabled
1089 else if (!(bv = current_view_->currentBufferView()))
1090 status.setEnabled(false);
1092 // Does the current BufferView know something?
1093 else if (bv->getStatus(cmd, status)) { }
1095 // Does the current Buffer know something?
1096 else if (bv->buffer().getStatus(cmd, status)) { }
1098 // If we do not have a document BufferView, different from the
1099 // current BufferView, then other functions are disabled
1100 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1101 status.setEnabled(false);
1103 // Does the document Buffer know something?
1104 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1107 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1108 status.message(from_utf8(N_("Command not handled")));
1109 status.setEnabled(false);
1112 // the default error message if we disable the command
1113 if (!status.enabled() && status.message().empty())
1114 status.message(from_utf8(N_("Command disabled")));
1120 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1122 // I would really like to avoid having this switch and rather try to
1123 // encode this in the function itself.
1124 // -- And I'd rather let an inset decide which LFUNs it is willing
1125 // to handle (Andre')
1127 switch (cmd.action()) {
1129 // This could be used for the no-GUI version. The GUI version is handled in
1130 // GuiView::getStatus(). See above.
1132 case LFUN_BUFFER_WRITE:
1133 case LFUN_BUFFER_WRITE_AS: {
1134 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1135 enable = b && (b->isUnnamed() || !b->isClean());
1140 case LFUN_BOOKMARK_GOTO: {
1141 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1142 enable = theSession().bookmarks().isValid(num);
1146 case LFUN_BOOKMARK_CLEAR:
1147 enable = theSession().bookmarks().hasValid();
1150 // this one is difficult to get right. As a half-baked
1151 // solution, we consider only the first action of the sequence
1152 case LFUN_COMMAND_SEQUENCE: {
1153 // argument contains ';'-terminated commands
1154 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1155 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1156 func.setOrigin(cmd.origin());
1157 flag = getStatus(func);
1161 // we want to check if at least one of these is enabled
1162 case LFUN_COMMAND_ALTERNATIVES: {
1163 // argument contains ';'-terminated commands
1164 string arg = to_utf8(cmd.argument());
1165 while (!arg.empty()) {
1167 arg = split(arg, first, ';');
1168 FuncRequest func(lyxaction.lookupFunc(first));
1169 func.setOrigin(cmd.origin());
1170 flag = getStatus(func);
1171 // if this one is enabled, the whole thing is
1180 string name = to_utf8(cmd.argument());
1181 if (theTopLevelCmdDef().lock(name, func)) {
1182 func.setOrigin(cmd.origin());
1183 flag = getStatus(func);
1184 theTopLevelCmdDef().release(name);
1186 // catch recursion or unknown command
1187 // definition. all operations until the
1188 // recursion or unknown command definition
1189 // occurs are performed, so set the state to
1196 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1198 case LFUN_PREFERENCES_SAVE:
1199 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1200 case LFUN_DEBUG_LEVEL_SET:
1201 // these are handled in our dispatch()
1204 case LFUN_WINDOW_CLOSE:
1205 enable = d->views_.size() > 0;
1208 case LFUN_BUFFER_NEW:
1209 case LFUN_BUFFER_NEW_TEMPLATE:
1210 case LFUN_FILE_OPEN:
1211 case LFUN_HELP_OPEN:
1212 case LFUN_SCREEN_FONT_UPDATE:
1213 case LFUN_SET_COLOR:
1214 case LFUN_WINDOW_NEW:
1216 case LFUN_LYXRC_APPLY:
1217 case LFUN_COMMAND_PREFIX:
1219 case LFUN_META_PREFIX:
1220 case LFUN_RECONFIGURE:
1221 case LFUN_SERVER_GET_FILENAME:
1222 case LFUN_SERVER_NOTIFY:
1226 case LFUN_BUFFER_FORALL: {
1227 if (theBufferList().empty()) {
1228 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1229 flag.setEnabled(false);
1233 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1234 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1235 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1236 flag.setEnabled(false);
1247 flag.setEnabled(false);
1251 /// make a post-dispatch status message
1252 static docstring makeDispatchMessage(docstring const & msg,
1253 FuncRequest const & cmd)
1255 const bool verbose = (cmd.origin() == FuncRequest::MENU
1256 || cmd.origin() == FuncRequest::TOOLBAR
1257 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1259 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1260 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1264 docstring dispatch_msg = msg;
1265 if (!dispatch_msg.empty())
1266 dispatch_msg += ' ';
1268 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1270 bool argsadded = false;
1272 if (!cmd.argument().empty()) {
1273 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1274 comname += ' ' + cmd.argument();
1278 docstring const shortcuts = theTopLevelKeymap().
1279 printBindings(cmd, KeySequence::ForGui);
1281 if (!shortcuts.empty())
1282 comname += ": " + shortcuts;
1283 else if (!argsadded && !cmd.argument().empty())
1284 comname += ' ' + cmd.argument();
1286 if (!comname.empty()) {
1287 comname = rtrim(comname);
1288 dispatch_msg += '(' + rtrim(comname) + ')';
1290 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1291 return dispatch_msg;
1295 void GuiApplication::dispatch(FuncRequest const & cmd)
1297 Buffer * buffer = 0;
1298 if (current_view_ && current_view_->currentBufferView()) {
1299 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1300 buffer = ¤t_view_->currentBufferView()->buffer();
1302 buffer->undo().beginUndoGroup();
1306 // redraw the screen at the end (first of the two drawing steps).
1307 // This is done unless explicitly requested otherwise
1308 dr.screenUpdate(Update::FitCursor);
1310 updateCurrentView(cmd, dr);
1312 // the buffer may have been closed by one action
1313 if (theBufferList().isLoaded(buffer))
1314 buffer->undo().endUndoGroup();
1318 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1323 BufferView * bv = current_view_->currentBufferView();
1325 if (dr.needBufferUpdate()) {
1326 bv->cursor().clearBufferUpdate();
1327 bv->buffer().updateBuffer();
1329 // BufferView::update() updates the ViewMetricsInfo and
1330 // also initializes the position cache for all insets in
1331 // (at least partially) visible top-level paragraphs.
1332 // We will redraw the screen only if needed.
1333 bv->processUpdateFlags(dr.screenUpdate());
1335 // Do we have a selection?
1336 theSelection().haveSelection(bv->cursor().selection());
1339 current_view_->restartCursor();
1341 if (dr.needMessageUpdate()) {
1342 // Some messages may already be translated, so we cannot use _()
1343 current_view_->message(makeDispatchMessage(
1344 translateIfPossible(dr.message()), cmd));
1349 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1350 bool switchToBuffer)
1352 if (!theSession().bookmarks().isValid(idx))
1354 BookmarksSection::Bookmark const & bm =
1355 theSession().bookmarks().bookmark(idx);
1356 LASSERT(!bm.filename.empty(), return);
1357 string const file = bm.filename.absFileName();
1358 // if the file is not opened, open it.
1359 if (!theBufferList().exists(bm.filename)) {
1361 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1365 // open may fail, so we need to test it again
1366 if (!theBufferList().exists(bm.filename))
1369 // bm can be changed when saving
1370 BookmarksSection::Bookmark tmp = bm;
1372 // Special case idx == 0 used for back-from-back jump navigation
1374 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1376 // if the current buffer is not that one, switch to it.
1377 BufferView * doc_bv = current_view_ ?
1378 current_view_->documentBufferView() : 0;
1379 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1380 if (switchToBuffer) {
1381 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1384 doc_bv = current_view_->documentBufferView();
1389 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1390 if (!doc_bv->moveToPosition(
1391 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1398 // Cursor jump succeeded!
1399 Cursor const & cur = doc_bv->cursor();
1400 pit_type new_pit = cur.pit();
1401 pos_type new_pos = cur.pos();
1402 int new_id = cur.paragraph().id();
1404 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1405 // see http://www.lyx.org/trac/ticket/3092
1406 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1407 || bm.top_id != new_id) {
1408 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1409 new_pit, new_pos, new_id);
1413 // This function runs "configure" and then rereads lyx.defaults to
1414 // reconfigure the automatic settings.
1415 void GuiApplication::reconfigure(string const & option)
1417 // emit message signal.
1419 current_view_->message(_("Running configure..."));
1421 // Run configure in user lyx directory
1422 PathChanger p(package().user_support());
1423 string configure_command = package().configure_command();
1424 configure_command += option;
1426 int const ret = one.startscript(Systemcall::Wait, configure_command);
1428 // emit message signal.
1430 current_view_->message(_("Reloading configuration..."));
1431 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1432 // Re-read packages.lst
1433 LaTeXPackages::getAvailable();
1436 Alert::information(_("System reconfiguration failed"),
1437 _("The system reconfiguration has failed.\n"
1438 "Default textclass is used but LyX may\n"
1439 "not be able to work properly.\n"
1440 "Please reconfigure again if needed."));
1442 Alert::information(_("System reconfigured"),
1443 _("The system has been reconfigured.\n"
1444 "You need to restart LyX to make use of any\n"
1445 "updated document class specifications."));
1448 void GuiApplication::validateCurrentView()
1450 if (!d->views_.empty() && !current_view_) {
1451 // currently at least one view exists but no view has the focus.
1452 // choose the last view to make it current.
1453 // a view without any open document is preferred.
1454 GuiView * candidate = 0;
1455 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1456 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1457 for (; it != end; ++it) {
1459 if (!candidate->documentBufferView())
1462 setCurrentView(candidate);
1466 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1468 string const argument = to_utf8(cmd.argument());
1469 FuncCode const action = cmd.action();
1471 LYXERR(Debug::ACTION, "cmd: " << cmd);
1473 // we have not done anything wrong yet.
1476 FuncStatus const flag = getStatus(cmd);
1477 if (!flag.enabled()) {
1478 // We cannot use this function here
1479 LYXERR(Debug::ACTION, "action "
1480 << lyxaction.getActionName(action)
1481 << " [" << action << "] is disabled at this location");
1482 dr.setMessage(flag.message());
1484 dr.dispatched(false);
1485 dr.screenUpdate(Update::None);
1486 dr.clearBufferUpdate();
1490 if (cmd.origin() == FuncRequest::LYXSERVER) {
1491 if (current_view_ && current_view_->currentBufferView())
1492 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1493 // we will also need to redraw the screen at the end
1494 dr.screenUpdate(Update::FitCursor);
1497 // Assumes that the action will be dispatched.
1498 dr.dispatched(true);
1500 switch (cmd.action()) {
1502 case LFUN_WINDOW_NEW:
1503 createView(toqstr(cmd.argument()));
1506 case LFUN_WINDOW_CLOSE:
1507 // update bookmark pit of the current buffer before window close
1508 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1509 gotoBookmark(i+1, false, false);
1510 // clear the last opened list, because
1511 // maybe this will end the session
1512 theSession().lastOpened().clear();
1513 // check for valid current_view_
1514 validateCurrentView();
1516 current_view_->closeScheduled();
1520 // quitting is triggered by the gui code
1521 // (leaving the event loop).
1523 current_view_->message(from_utf8(N_("Exiting.")));
1524 if (closeAllViews())
1528 case LFUN_SCREEN_FONT_UPDATE: {
1529 // handle the screen font changes.
1530 d->font_loader_.update();
1531 // Backup current_view_
1532 GuiView * view = current_view_;
1533 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1534 // to skip the refresh.
1536 theBufferList().changed(false);
1537 // Restore current_view_
1538 current_view_ = view;
1542 case LFUN_BUFFER_NEW:
1543 validateCurrentView();
1544 if (d->views_.empty()
1545 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1546 createView(QString(), false); // keep hidden
1547 current_view_->newDocument(to_utf8(cmd.argument()), false);
1548 current_view_->show();
1549 setActiveWindow(current_view_);
1551 current_view_->newDocument(to_utf8(cmd.argument()), false);
1555 case LFUN_BUFFER_NEW_TEMPLATE:
1556 validateCurrentView();
1557 if (d->views_.empty()
1558 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1560 current_view_->newDocument(to_utf8(cmd.argument()), true);
1561 if (!current_view_->documentBufferView())
1562 current_view_->close();
1564 current_view_->newDocument(to_utf8(cmd.argument()), true);
1568 case LFUN_FILE_OPEN: {
1569 validateCurrentView();
1570 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1571 string const fname = to_utf8(cmd.argument());
1572 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1573 && current_view_->documentBufferView() != 0)) {
1574 // We want the ui session to be saved per document and not per
1575 // window number. The filename crc is a good enough identifier.
1576 boost::crc_32_type crc;
1577 crc = for_each(fname.begin(), fname.end(), crc);
1578 createView(crc.checksum());
1579 current_view_->openDocument(fname);
1580 if (current_view_ && !current_view_->documentBufferView())
1581 current_view_->close();
1583 current_view_->openDocument(fname);
1587 case LFUN_HELP_OPEN: {
1588 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1589 if (current_view_ == 0)
1591 string const arg = to_utf8(cmd.argument());
1593 current_view_->message(_("Missing argument"));
1596 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1598 fname = i18nLibFileSearch("examples", arg, "lyx");
1600 if (fname.empty()) {
1601 lyxerr << "LyX: unable to find documentation file `"
1602 << arg << "'. Bad installation?" << endl;
1605 current_view_->message(bformat(_("Opening help file %1$s..."),
1606 makeDisplayPath(fname.absFileName())));
1607 Buffer * buf = current_view_->loadDocument(fname, false);
1609 #ifndef DEVEL_VERSION
1611 buf->setReadonly(true);
1618 case LFUN_SET_COLOR: {
1620 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1621 if (lyx_name.empty() || x11_name.empty()) {
1623 current_view_->message(
1624 _("Syntax: set-color <lyx_name> <x11_name>"));
1629 // FIXME: The graphics cache no longer has a changeDisplay method.
1630 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1631 bool const graphicsbg_changed =
1632 lyx_name == graphicsbg && x11_name != graphicsbg;
1633 if (graphicsbg_changed)
1634 graphics::GCache::get().changeDisplay(true);
1637 if (!lcolor.setColor(lyx_name, x11_name)) {
1639 current_view_->message(
1640 bformat(_("Set-color \"%1$s\" failed "
1641 "- color is undefined or "
1642 "may not be redefined"),
1643 from_utf8(lyx_name)));
1646 // Make sure we don't keep old colors in cache.
1647 d->color_cache_.clear();
1651 case LFUN_LYXRC_APPLY: {
1652 // reset active key sequences, since the bindings
1653 // are updated (bug 6064)
1655 LyXRC const lyxrc_orig = lyxrc;
1657 istringstream ss(to_utf8(cmd.argument()));
1658 bool const success = lyxrc.read(ss);
1661 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1662 << "Unable to read lyxrc data"
1667 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1673 case LFUN_COMMAND_PREFIX:
1674 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1679 d->meta_fake_bit = NoModifier;
1680 GuiView * gv = currentView();
1681 if (gv && gv->currentBufferView())
1682 // cancel any selection
1683 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1684 dr.setMessage(from_ascii(N_("Cancel")));
1687 case LFUN_META_PREFIX:
1688 d->meta_fake_bit = AltModifier;
1689 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1692 // --- Menus -----------------------------------------------
1693 case LFUN_RECONFIGURE:
1694 // argument is any additional parameter to the configure.py command
1695 reconfigure(to_utf8(cmd.argument()));
1698 // --- lyxserver commands ----------------------------
1699 case LFUN_SERVER_GET_FILENAME: {
1700 if (current_view_ && current_view_->documentBufferView()) {
1701 docstring const fname = from_utf8(
1702 current_view_->documentBufferView()->buffer().absFileName());
1703 dr.setMessage(fname);
1704 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1706 dr.setMessage(docstring());
1707 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1712 case LFUN_SERVER_NOTIFY: {
1713 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1714 dr.setMessage(dispatch_buffer);
1715 theServer().notifyClient(to_utf8(dispatch_buffer));
1719 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1720 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1726 string rest = split(argument, countstr, ' ');
1727 istringstream is(countstr);
1730 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1731 for (int i = 0; i < count; ++i)
1732 dispatch(lyxaction.lookupFunc(rest));
1736 case LFUN_COMMAND_SEQUENCE: {
1737 // argument contains ';'-terminated commands
1738 string arg = argument;
1739 // FIXME: this LFUN should also work without any view.
1740 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1741 ? &(current_view_->documentBufferView()->buffer()) : 0;
1743 buffer->undo().beginUndoGroup();
1744 while (!arg.empty()) {
1746 arg = split(arg, first, ';');
1747 FuncRequest func(lyxaction.lookupFunc(first));
1748 func.setOrigin(cmd.origin());
1751 // the buffer may have been closed by one action
1752 if (theBufferList().isLoaded(buffer))
1753 buffer->undo().endUndoGroup();
1757 case LFUN_BUFFER_FORALL: {
1758 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1760 map<Buffer *, GuiView *> views_lVisible;
1761 map<GuiView *, Buffer *> activeBuffers;
1763 QList<GuiView *> allViews = d->views_.values();
1765 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1766 // and on which buffer is active in each view.
1767 Buffer * const last = theBufferList().last();
1768 foreach (GuiView * view, allViews) {
1769 // all of the buffers might be locally hidden. That is, there is no active buffer.
1770 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1771 activeBuffers[view] = 0;
1773 activeBuffers[view] = &view->currentBufferView()->buffer();
1775 // find out if each is locally visible or locally hidden.
1776 // we don't use a for loop as the buffer list cycles.
1777 Buffer * b = theBufferList().first();
1779 bool const locallyVisible = view && view->workArea(*b);
1780 if (locallyVisible) {
1781 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1782 // only need to overwrite/add if we don't already know a buffer is globally
1783 // visible or we do know but we would prefer to dispatch LFUN from the
1784 // current view because of cursor position issues.
1785 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1786 views_lVisible[b] = view;
1790 b = theBufferList().next(b);
1794 GuiView * const homeView = currentView();
1795 Buffer * b = theBufferList().first();
1796 Buffer * nextBuf = 0;
1797 int numProcessed = 0;
1800 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1802 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1804 // first change to a view where b is locally visible, preferably current_view_.
1805 GuiView * const vLv = views_lVisible[b];
1807 lyx::dispatch(funcToRun);
1815 // put things back to how they were (if possible).
1816 foreach (GuiView * view, allViews) {
1817 Buffer * originalBuf = activeBuffers[view];
1818 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1819 if (theBufferList().isLoaded(originalBuf))
1820 view->setBuffer(originalBuf);
1822 homeView->setFocus();
1824 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1828 case LFUN_COMMAND_ALTERNATIVES: {
1829 // argument contains ';'-terminated commands
1830 string arg = argument;
1831 while (!arg.empty()) {
1833 arg = split(arg, first, ';');
1834 FuncRequest func(lyxaction.lookupFunc(first));
1835 func.setOrigin(cmd.origin());
1836 FuncStatus const stat = getStatus(func);
1837 if (stat.enabled()) {
1847 if (theTopLevelCmdDef().lock(argument, func)) {
1848 func.setOrigin(cmd.origin());
1850 theTopLevelCmdDef().release(argument);
1852 if (func.action() == LFUN_UNKNOWN_ACTION) {
1853 // unknown command definition
1854 lyxerr << "Warning: unknown command definition `"
1858 // recursion detected
1859 lyxerr << "Warning: Recursion in the command definition `"
1860 << argument << "' detected"
1867 case LFUN_PREFERENCES_SAVE:
1868 lyxrc.write(support::makeAbsPath("preferences",
1869 package().user_support().absFileName()), false);
1872 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1873 string const fname = addName(addPath(package().user_support().absFileName(),
1874 "templates/"), "defaults.lyx");
1875 Buffer defaults(fname);
1877 istringstream ss(argument);
1880 int const unknown_tokens = defaults.readHeader(lex);
1882 if (unknown_tokens != 0) {
1883 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1884 << unknown_tokens << " unknown token"
1885 << (unknown_tokens == 1 ? "" : "s")
1889 if (defaults.writeFile(FileName(defaults.absFileName())))
1890 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1891 makeDisplayPath(fname)));
1894 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1899 case LFUN_BOOKMARK_GOTO:
1900 // go to bookmark, open unopened file and switch to buffer if necessary
1901 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1902 dr.screenUpdate(Update::Force | Update::FitCursor);
1905 case LFUN_BOOKMARK_CLEAR:
1906 theSession().bookmarks().clear();
1909 case LFUN_DEBUG_LEVEL_SET:
1910 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1914 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1917 current_view_->dispatch(cmd, dr);
1921 if (cmd.origin() == FuncRequest::LYXSERVER)
1922 updateCurrentView(cmd, dr);
1926 docstring GuiApplication::viewStatusMessage()
1928 // When meta-fake key is pressed, show the key sequence so far + "M-".
1929 if (d->meta_fake_bit != NoModifier)
1930 return d->keyseq.print(KeySequence::ForGui) + "M-";
1932 // Else, when a non-complete key sequence is pressed,
1933 // show the available options.
1934 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1935 return d->keyseq.printOptions(true);
1941 void GuiApplication::handleKeyFunc(FuncCode action)
1945 if (d->keyseq.length())
1947 GuiView * gv = currentView();
1948 LASSERT(gv && gv->currentBufferView(), return);
1949 BufferView * bv = gv->currentBufferView();
1950 bv->getIntl().getTransManager().deadkey(
1951 c, get_accent(action).accent, bv->cursor().innerText(),
1953 // Need to clear, in case the minibuffer calls these
1956 // copied verbatim from do_accent_char
1957 bv->cursor().resetAnchor();
1961 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1963 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1965 // Do nothing if we have nothing (JMarc)
1966 if (!keysym.isOK()) {
1967 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1969 current_view_->restartCursor();
1973 if (keysym.isModifier()) {
1975 current_view_->restartCursor();
1979 char_type encoded_last_key = keysym.getUCSEncoded();
1981 // Do a one-deep top-level lookup for
1982 // cancel and meta-fake keys. RVDK_PATCH_5
1983 d->cancel_meta_seq.reset();
1985 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1986 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1988 // When not cancel or meta-fake, do the normal lookup.
1989 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1990 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1991 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1992 // remove Caps Lock and Mod2 as a modifiers
1993 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1994 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1997 // Dont remove this unless you know what you are doing.
1998 d->meta_fake_bit = NoModifier;
2000 // Can this happen now ?
2001 if (func.action() == LFUN_NOACTION)
2002 func = FuncRequest(LFUN_COMMAND_PREFIX);
2004 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2005 << d->keyseq.print(KeySequence::Portable) << ']');
2007 // already here we know if it any point in going further
2008 // why not return already here if action == -1 and
2009 // num_bytes == 0? (Lgb)
2011 if (d->keyseq.length() > 1 && current_view_)
2012 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2015 // Maybe user can only reach the key via holding down shift.
2016 // Let's see. But only if shift is the only modifier
2017 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2018 LYXERR(Debug::KEY, "Trying without shift");
2019 func = d->keyseq.addkey(keysym, NoModifier);
2020 LYXERR(Debug::KEY, "Action now " << func.action());
2023 if (func.action() == LFUN_UNKNOWN_ACTION) {
2024 // Hmm, we didn't match any of the keysequences. See
2025 // if it's normal insertable text not already covered
2027 if (keysym.isText() && d->keyseq.length() == 1) {
2028 LYXERR(Debug::KEY, "isText() is true, inserting.");
2029 func = FuncRequest(LFUN_SELF_INSERT,
2030 FuncRequest::KEYBOARD);
2032 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2033 if (current_view_) {
2034 current_view_->message(_("Unknown function."));
2035 current_view_->restartCursor();
2041 if (func.action() == LFUN_SELF_INSERT) {
2042 if (encoded_last_key != 0) {
2043 docstring const arg(1, encoded_last_key);
2044 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2045 FuncRequest::KEYBOARD));
2046 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2049 processFuncRequest(func);
2053 void GuiApplication::processFuncRequest(FuncRequest const & func)
2055 lyx::dispatch(func);
2059 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2061 addToFuncRequestQueue(func);
2062 processFuncRequestQueueAsync();
2066 void GuiApplication::processFuncRequestQueue()
2068 while (!d->func_request_queue_.empty()) {
2069 processFuncRequest(d->func_request_queue_.front());
2070 d->func_request_queue_.pop();
2075 void GuiApplication::processFuncRequestQueueAsync()
2077 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2081 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2083 d->func_request_queue_.push(func);
2087 void GuiApplication::resetGui()
2089 // Set the language defined by the user.
2093 if (!readUIFile(toqstr(lyxrc.ui_file)))
2094 // Gives some error box here.
2097 if (d->global_menubar_)
2098 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2100 QHash<int, GuiView *>::iterator it;
2101 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2104 gv->setLayoutDirection(layoutDirection());
2108 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2112 void GuiApplication::createView(int view_id)
2114 createView(QString(), true, view_id);
2118 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2121 // release the keyboard which might have been grabed by the global
2122 // menubar on Mac to catch shortcuts even without any GuiView.
2123 if (d->global_menubar_)
2124 d->global_menubar_->releaseKeyboard();
2128 while (d->views_.find(id) != d->views_.end())
2131 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2132 GuiView * view = new GuiView(id);
2134 d->views_[id] = view;
2138 setActiveWindow(view);
2141 if (!geometry_arg.isEmpty()) {
2145 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2146 re.indexIn(geometry_arg);
2147 w = re.cap(1).toInt();
2148 h = re.cap(2).toInt();
2149 x = re.cap(3).toInt();
2150 y = re.cap(4).toInt();
2151 view->setGeometry(x, y, w, h);
2158 Clipboard & GuiApplication::clipboard()
2160 return d->clipboard_;
2164 Selection & GuiApplication::selection()
2166 return d->selection_;
2170 FontLoader & GuiApplication::fontLoader()
2172 return d->font_loader_;
2176 Toolbars const & GuiApplication::toolbars() const
2178 return d->toolbars_;
2182 Toolbars & GuiApplication::toolbars()
2184 return d->toolbars_;
2188 Menus const & GuiApplication::menus() const
2194 Menus & GuiApplication::menus()
2200 QList<int> GuiApplication::viewIds() const
2202 return d->views_.keys();
2206 ColorCache & GuiApplication::colorCache()
2208 return d->color_cache_;
2212 int GuiApplication::exec()
2214 // asynchronously handle batch commands. This event will be in
2215 // the event queue in front of other asynchronous events. Hence,
2216 // we can assume in the latter that the gui is setup already.
2217 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2219 return QApplication::exec();
2223 void GuiApplication::exit(int status)
2225 QApplication::exit(status);
2229 void GuiApplication::setGuiLanguage()
2233 // install translation file for Qt built-in dialogs
2234 QString const language_name = QString("qt_") + theLocale.name();
2235 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2236 // Short-named translator can be loaded from a long name, but not the
2237 // opposite. Therefore, long name should be used without truncation.
2238 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2239 if (!d->qt_trans_.load(language_name,
2240 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2241 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2244 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2248 switch (theLocale.language()) {
2249 case QLocale::Arabic :
2250 case QLocale::Hebrew :
2251 case QLocale::Persian :
2252 case QLocale::Urdu :
2253 setLayoutDirection(Qt::RightToLeft);
2256 setLayoutDirection(Qt::LeftToRight);
2261 void GuiApplication::execBatchCommands()
2266 if (!readUIFile(toqstr(lyxrc.ui_file)))
2267 // Gives some error box here.
2271 #if QT_VERSION > 0x040600
2272 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2274 // Create the global default menubar which is shown for the dialogs
2275 // and if no GuiView is visible.
2276 // This must be done after the session was recovered to know the "last files".
2277 d->global_menubar_ = new GlobalMenuBar;
2278 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2281 lyx::execBatchCommands();
2285 QAbstractItemModel * GuiApplication::languageModel()
2287 if (d->language_model_)
2288 return d->language_model_;
2290 QStandardItemModel * lang_model = new QStandardItemModel(this);
2291 lang_model->insertColumns(0, 3);
2293 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2294 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2295 Languages::const_iterator it = lyx::languages.begin();
2296 Languages::const_iterator end = lyx::languages.end();
2297 for (; it != end; ++it) {
2298 current_row = lang_model->rowCount();
2299 lang_model->insertRows(current_row, 1);
2300 QModelIndex pl_item = lang_model->index(current_row, 0);
2301 QModelIndex sp_item = lang_model->index(current_row, 1);
2302 QModelIndex th_item = lang_model->index(current_row, 2);
2303 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2304 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2305 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2306 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2307 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2308 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2309 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2310 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2311 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2312 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2314 d->language_model_ = new QSortFilterProxyModel(this);
2315 d->language_model_->setSourceModel(lang_model);
2316 d->language_model_->setSortLocaleAware(true);
2317 return d->language_model_;
2321 void GuiApplication::restoreGuiSession()
2323 if (!lyxrc.load_session)
2326 Session & session = theSession();
2327 LastOpenedSection::LastOpened const & lastopened =
2328 session.lastOpened().getfiles();
2330 validateCurrentView();
2332 FileName active_file;
2333 // do not add to the lastfile list since these files are restored from
2334 // last session, and should be already there (regular files), or should
2335 // not be added at all (help files).
2336 for (size_t i = 0; i < lastopened.size(); ++i) {
2337 FileName const & file_name = lastopened[i].file_name;
2338 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2339 && current_view_->documentBufferView() != 0)) {
2340 boost::crc_32_type crc;
2341 string const & fname = file_name.absFileName();
2342 crc = for_each(fname.begin(), fname.end(), crc);
2343 createView(crc.checksum());
2345 current_view_->loadDocument(file_name, false);
2347 if (lastopened[i].active)
2348 active_file = file_name;
2351 // Restore last active buffer
2352 Buffer * buffer = theBufferList().getBuffer(active_file);
2353 if (buffer && current_view_)
2354 current_view_->setBuffer(buffer);
2356 // clear this list to save a few bytes of RAM
2357 session.lastOpened().clear();
2361 QString const GuiApplication::romanFontName()
2364 font.setKerning(false);
2365 font.setStyleHint(QFont::Serif);
2366 font.setFamily("serif");
2368 return QFontInfo(font).family();
2372 QString const GuiApplication::sansFontName()
2375 font.setKerning(false);
2376 font.setStyleHint(QFont::SansSerif);
2377 font.setFamily("sans");
2379 return QFontInfo(font).family();
2383 QString const GuiApplication::typewriterFontName()
2386 font.setKerning(false);
2387 font.setStyleHint(QFont::TypeWriter);
2388 font.setFamily("monospace");
2390 return QFontInfo(font).family();
2394 void GuiApplication::handleRegularEvents()
2396 ForkedCallsController::handleCompletedProcesses();
2400 bool GuiApplication::event(QEvent * e)
2403 case QEvent::FileOpen: {
2404 // Open a file; this happens only on Mac OS X for now.
2406 // We do this asynchronously because on startup the batch
2407 // commands are not executed here yet and the gui is not ready
2409 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2410 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2411 processFuncRequestAsync(fr);
2416 return QApplication::event(e);
2421 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2424 return QApplication::notify(receiver, event);
2426 catch (ExceptionMessage const & e) {
2428 case ErrorException:
2430 setQuitOnLastWindowClosed(false);
2432 Alert::error(e.title_, e.details_);
2434 // Properly crash in debug mode in order to get a useful backtrace.
2437 // In release mode, try to exit gracefully.
2440 case BufferException: {
2441 if (!current_view_ || !current_view_->documentBufferView())
2443 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2444 docstring details = e.details_ + '\n';
2445 details += buf->emergencyWrite();
2446 theBufferList().release(buf);
2447 details += "\n" + _("The current document was closed.");
2448 Alert::error(e.title_, details);
2451 case WarningException:
2452 Alert::warning(e.title_, e.details_);
2456 catch (exception const & e) {
2457 docstring s = _("LyX has caught an exception, it will now "
2458 "attempt to save all unsaved documents and exit."
2460 s += from_ascii(e.what());
2461 Alert::error(_("Software exception Detected"), s);
2465 docstring s = _("LyX has caught some really weird exception, it will "
2466 "now attempt to save all unsaved documents and exit.");
2467 Alert::error(_("Software exception Detected"), s);
2475 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2477 QColor const & qcol = d->color_cache_.get(col);
2478 if (!qcol.isValid()) {
2484 rgbcol.r = qcol.red();
2485 rgbcol.g = qcol.green();
2486 rgbcol.b = qcol.blue();
2491 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2493 QColor const qcol(lcolor.getX11Name(col).c_str());
2494 if (!qcol.isValid()) {
2500 rgbcol.r = qcol.red();
2501 rgbcol.g = qcol.green();
2502 rgbcol.b = qcol.blue();
2507 string const GuiApplication::hexName(ColorCode col)
2509 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2513 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2515 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2516 d->socket_notifiers_[fd] = sn;
2517 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2521 void GuiApplication::socketDataReceived(int fd)
2523 d->socket_notifiers_[fd]->func_();
2527 void GuiApplication::unregisterSocketCallback(int fd)
2529 d->socket_notifiers_.take(fd)->setEnabled(false);
2533 void GuiApplication::commitData(QSessionManager & sm)
2535 /// The implementation is required to avoid an application exit
2536 /// when session state save is triggered by session manager.
2537 /// The default implementation sends a close event to all
2538 /// visible top level widgets when session managment allows
2540 /// We are changing that to close all wiew one by one.
2541 /// FIXME: verify if the default implementation is enough now.
2542 #ifdef QT_NO_SESSIONMANAGER
2544 #warning Qt is compiled without session manager
2546 #pragma message("warning: Qt is compiled without session manager")
2550 if (sm.allowsInteraction() && !closeAllViews())
2556 void GuiApplication::unregisterView(GuiView * gv)
2558 LAPPERR(d->views_[gv->id()] == gv);
2559 d->views_.remove(gv->id());
2560 if (current_view_ == gv)
2565 bool GuiApplication::closeAllViews()
2567 if (d->views_.empty())
2570 // When a view/window was closed before without quitting LyX, there
2571 // are already entries in the lastOpened list.
2572 theSession().lastOpened().clear();
2574 QList<GuiView *> const views = d->views_.values();
2575 foreach (GuiView * view, views) {
2576 if (!view->closeScheduled())
2585 GuiView & GuiApplication::view(int id) const
2587 LAPPERR(d->views_.contains(id));
2588 return *d->views_.value(id);
2592 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2594 QList<GuiView *> const views = d->views_.values();
2595 foreach (GuiView * view, views)
2596 view->hideDialog(name, inset);
2600 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2602 Buffer const * buffer_ = 0;
2603 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2604 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2605 if (Buffer const * ptr = (*it)->updateInset(inset))
2612 bool GuiApplication::searchMenu(FuncRequest const & func,
2613 docstring_list & names) const
2615 return d->menus_.searchMenu(func, names);
2619 // Ensure that a file is read only once (prevents include loops)
2620 static QStringList uifiles;
2621 // store which ui files define Toolbars
2622 static QStringList toolbar_uifiles;
2625 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2636 LexerKeyword uitags[] = {
2637 { "format", ui_format },
2638 { "include", ui_include },
2639 { "menuset", ui_menuset },
2640 { "toolbars", ui_toolbars },
2641 { "toolbarset", ui_toolbarset }
2645 lex.setFile(ui_path);
2647 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2651 if (lyxerr.debugging(Debug::PARSER))
2652 lex.printTable(lyxerr);
2655 // format before introduction of format tag
2656 unsigned int format = 0;
2657 while (lex.isOK()) {
2658 int const status = lex.lex();
2660 // we have to do this check here, outside the switch,
2661 // because otherwise we would start reading include files,
2662 // e.g., if the first tag we hit was an include tag.
2663 if (status == ui_format)
2665 format = lex.getInteger();
2669 // this will trigger unless the first tag we hit is a format
2670 // tag, with the right format.
2671 if (format != LFUN_FORMAT)
2672 return FormatMismatch;
2675 case Lexer::LEX_FEOF:
2680 QString const file = toqstr(lex.getString());
2681 bool const success = readUIFile(file, true);
2683 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2690 d->menus_.read(lex);
2694 d->toolbars_.readToolbars(lex);
2698 d->toolbars_.readToolbarSettings(lex);
2699 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2703 if (!rtrim(lex.getString()).empty())
2704 lex.printError("LyX::ReadUIFile: "
2705 "Unknown menu tag: `$$Token'");
2707 LYXERR0("Error with status: " << status);
2713 return (error ? ReadError : ReadOK);
2717 bool GuiApplication::readUIFile(QString const & name, bool include)
2719 LYXERR(Debug::INIT, "About to read " << name << "...");
2723 ui_path = libFileSearch("ui", name, "inc");
2724 if (ui_path.empty())
2725 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2727 ui_path = libFileSearch("ui", name, "ui");
2730 if (ui_path.empty()) {
2731 static const QString defaultUIFile = "default";
2732 LYXERR(Debug::INIT, "Could not find " << name);
2734 Alert::warning(_("Could not find UI definition file"),
2735 bformat(_("Error while reading the included file\n%1$s\n"
2736 "Please check your installation."), qstring_to_ucs4(name)));
2739 if (name == defaultUIFile) {
2740 LYXERR(Debug::INIT, "Could not find default UI file!!");
2741 Alert::warning(_("Could not find default UI file"),
2742 _("LyX could not find the default UI file!\n"
2743 "Please check your installation."));
2746 Alert::warning(_("Could not find UI definition file"),
2747 bformat(_("Error while reading the configuration file\n%1$s\n"
2748 "Falling back to default.\n"
2749 "Please look under Tools>Preferences>User Interface and\n"
2750 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2751 return readUIFile(defaultUIFile, false);
2754 QString const uifile = toqstr(ui_path.absFileName());
2755 if (uifiles.contains(uifile)) {
2757 // We are reading again the top uifile so reset the safeguard:
2760 d->toolbars_.reset();
2762 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2763 << "Is this an include loop?");
2767 uifiles.push_back(uifile);
2769 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2771 ReturnValues retval = readUIFile(ui_path);
2773 if (retval == FormatMismatch) {
2774 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2775 FileName const tempfile = FileName::tempName("convert_ui");
2776 bool const success = prefs2prefs(ui_path, tempfile, true);
2778 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2779 " to format " << LFUN_FORMAT << ".");
2781 retval = readUIFile(tempfile);
2782 tempfile.removeFile();
2786 if (retval != ReadOK) {
2787 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2795 settings.beginGroup("ui_files");
2796 bool touched = false;
2797 for (int i = 0; i != uifiles.size(); ++i) {
2798 QFileInfo fi(uifiles[i]);
2799 QDateTime const date_value = fi.lastModified();
2800 QString const name_key = QString::number(i);
2801 // if an ui file which defines Toolbars has changed,
2802 // we have to reset the settings
2803 if (toolbar_uifiles.contains(uifiles[i])
2804 && (!settings.contains(name_key)
2805 || settings.value(name_key).toString() != uifiles[i]
2806 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2808 settings.setValue(name_key, uifiles[i]);
2809 settings.setValue(name_key + "/date", date_value);
2812 settings.endGroup();
2814 settings.remove("views");
2820 void GuiApplication::onLastWindowClosed()
2822 if (d->global_menubar_)
2823 d->global_menubar_->grabKeyboard();
2827 void GuiApplication::startLongOperation() {
2828 d->key_checker_.start();
2832 bool GuiApplication::longOperationCancelled() {
2833 return d->key_checker_.pressed();
2837 void GuiApplication::stopLongOperation() {
2838 d->key_checker_.stop();
2842 bool GuiApplication::longOperationStarted() {
2843 return d->key_checker_.started();
2847 ////////////////////////////////////////////////////////////////////////
2849 // X11 specific stuff goes here...
2852 bool GuiApplication::x11EventFilter(XEvent * xev)
2857 switch (xev->type) {
2858 case SelectionRequest: {
2859 if (xev->xselectionrequest.selection != XA_PRIMARY)
2861 LYXERR(Debug::SELECTION, "X requested selection.");
2862 BufferView * bv = current_view_->currentBufferView();
2864 docstring const sel = bv->requestSelection();
2866 d->selection_.put(sel);
2870 case SelectionClear: {
2871 if (xev->xselectionclear.selection != XA_PRIMARY)
2873 LYXERR(Debug::SELECTION, "Lost selection.");
2874 BufferView * bv = current_view_->currentBufferView();
2876 bv->clearSelection();
2884 } // namespace frontend
2887 void hideDialogs(std::string const & name, Inset * inset)
2890 frontend::guiApp->hideDialogs(name, inset);
2894 ////////////////////////////////////////////////////////////////////
2898 ////////////////////////////////////////////////////////////////////
2900 frontend::FontLoader & theFontLoader()
2902 LAPPERR(frontend::guiApp);
2903 return frontend::guiApp->fontLoader();
2907 frontend::FontMetrics const & theFontMetrics(Font const & f)
2909 return theFontMetrics(f.fontInfo());
2913 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2915 LAPPERR(frontend::guiApp);
2916 return frontend::guiApp->fontLoader().metrics(f);
2920 ////////////////////////////////////////////////////////////////////
2924 ////////////////////////////////////////////////////////////////////
2926 frontend::Clipboard & theClipboard()
2928 LAPPERR(frontend::guiApp);
2929 return frontend::guiApp->clipboard();
2933 frontend::Selection & theSelection()
2935 LAPPERR(frontend::guiApp);
2936 return frontend::guiApp->selection();
2942 #include "moc_GuiApplication.cpp"