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 "BufferParams.h"
36 #include "BufferView.h"
39 #include "CutAndPaste.h"
40 #include "ErrorList.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
44 #include "GuiWorkArea.h"
48 #include "LaTeXPackages.h"
51 #include "LyXAction.h"
53 #include "Paragraph.h"
56 #include "SpellChecker.h"
57 #include "Thesaurus.h"
60 #include "insets/InsetText.h"
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/ExceptionMessage.h"
65 #include "support/FileName.h"
66 #include "support/filetools.h"
67 #include "support/foreach.h"
68 #include "support/ForkedCalls.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/lstrings.h"
72 #include "support/lyxalgo.h" // sorted
73 #include "support/Messages.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/PathChanger.h"
77 #include "support/Systemcall.h"
78 #include "support/TempFile.h"
81 #include "support/AppleScript.h"
82 #include "support/linkback/LinkBackProxy.h"
93 #include <QFileOpenEvent>
97 #include <QImageReader>
100 #include <QLibraryInfo>
106 #include <QPixmapCache>
108 #include <QSessionManager>
110 #include <QShowEvent>
111 #include <QSocketNotifier>
112 #include <QSortFilterProxyModel>
113 #include <QStandardItemModel>
114 #include <QTextCodec>
116 #include <QTranslator>
117 #include <QThreadPool>
121 #include <X11/Xatom.h>
122 #include <X11/Xlib.h>
128 #include <QWindowsMime>
136 #include <QMacPasteboardMime>
139 #include "support/bind.h"
140 #include <boost/crc.hpp>
147 using namespace lyx::support;
150 static void initializeResources()
152 static bool initialized = false;
154 Q_INIT_RESOURCE(Resources);
162 frontend::Application * createApplication(int & argc, char * argv[])
165 // prune -geometry argument(s) by shifting
166 // the following ones 2 places down.
167 for (int i = 0 ; i < argc ; ++i) {
168 if (strcmp(argv[i], "-geometry") == 0) {
169 int const remove = (i+1) < argc ? 2 : 1;
171 for (int j = i; j < argc; ++j)
172 argv[j] = argv[j + remove];
177 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
178 // I'd rather do that in the constructor, but I do not think that
179 // the palette is accessible there.
180 guiApp->colorCache().setPalette(guiApp->palette());
188 if (lyxrc.gui_language == "auto") {
189 theLocale = QLocale::system();
191 Language const * l = languages.getLanguage(lyxrc.gui_language);
192 string const code = l ? l->code() : string();
193 theLocale = QLocale(toqstr(code));
195 string const code = fromqstr(theLocale.name());
196 // Qt tries to outsmart us and transforms en_US to C.
197 Messages::guiLanguage((code == "C") ? "en_US" : code);
198 QLocale::setDefault(theLocale);
199 setlocale(LC_NUMERIC, "C");
206 /// Return the list of loadable formats.
207 vector<string> loadableImageFormats()
211 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
213 LYXERR(Debug::GRAPHICS,
214 "\nThe image loader can load the following directly:\n");
216 if (qt_formats.empty())
217 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
219 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
221 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
223 string ext = ascii_lowercase((const char *) *it);
234 ////////////////////////////////////////////////////////////////////////
236 // Icon loading support code
238 ////////////////////////////////////////////////////////////////////////
248 bool operator<(PngMap const & lhs, PngMap const & rhs)
250 return lhs.key < rhs.key;
256 CompareKey(QString const & name) : name_(name) {}
257 bool operator()(PngMap const & other) const { return other.key == name_; }
263 // this must be sorted alphabetically
264 // Upper case comes before lower case
265 // Please don't change the formatting, this list is parsed by
266 // development/tools/generate_symbols_images.py.
267 PngMap sorted_png_map[] = {
268 { "Arrownot", "arrownot2"},
269 { "Arrowvert", "arrowvert2"},
270 { "Bowtie", "bowtie2" },
272 { "Bumpeq", "bumpeq2" },
273 { "CIRCLE", "circle3" },
275 { "CheckedBox", "checkedbox2" },
276 { "Circle", "circle2" },
277 { "Colonapprox", "colonapprox2" },
278 { "Coloneq", "coloneq2" },
279 { "Coloneqq", "coloneqq2" },
280 { "Colonsim", "colonsim2" },
282 { "DOWNarrow", "downarrow3" },
283 { "Delta", "delta2" },
284 { "Diamond", "diamond2" },
285 { "Doteq", "doteq2" },
286 { "Downarrow", "downarrow2" },
287 { "Eqcolon", "eqcolon2" },
288 { "Eqqcolon", "eqqcolon2" },
289 { "Gamma", "gamma2" },
291 { "LEFTCIRCLE", "leftcircle3" },
292 { "LEFTarrow", "leftarrow3" },
293 { "LEFTcircle", "leftcircle4" },
295 { "Lambda", "lambda2" },
297 { "Leftarrow", "leftarrow2" },
298 { "Leftcircle", "leftcircle2" },
299 { "Leftrightarrow", "leftrightarrow2" },
300 { "Longarrownot", "longarrownot2"},
301 { "Longleftarrow", "longleftarrow2" },
302 { "Longleftrightarrow", "longleftrightarrow2" },
303 { "Longmapsfrom", "longmapsfrom2"},
304 { "Longmapsto", "longmapsto2"},
305 { "Longrightarrow", "longrightarrow2" },
306 { "Mapsfrom", "mapsfrom2"},
307 { "Mapsfromchar", "mapsfromchar2"},
308 { "Mapsto", "mapsto2"},
309 { "Mapstochar", "mapstochar2"},
310 { "Omega", "omega2" },
315 { "RIGHTCIRCLE", "rightcircle3" },
316 { "RIGHTarrow", "rightarrow3" },
317 { "RIGHTcircle", "rightcircle4" },
319 { "Rightarrow", "rightarrow2" },
320 { "Rightcircle", "rightcircle2" },
321 { "Sigma", "sigma2" },
322 { "Square", "square2" },
323 { "Subset", "subset2" },
324 { "Supset", "supset2" },
325 { "Theta", "theta2" },
326 { "Thorn", "thorn2" },
327 { "UParrow", "uparrow3" },
328 { "Uparrow", "uparrow2" },
329 { "Updownarrow", "updownarrow2" },
330 { "Upsilon", "upsilon2" },
331 { "Vdash", "vdash3" },
336 { "nLeftarrow", "nleftarrow2" },
337 { "nLeftrightarrow", "nleftrightarrow2" },
338 { "nRightarrow", "nrightarrow2" },
339 { "nVDash", "nvdash3" },
340 { "nVdash", "nvdash4" },
341 { "nvDash", "nvdash2" },
342 { "textrm \\AA", "textrm_AA"},
343 { "textrm \\O", "textrm_O"},
344 { "vDash", "vdash2" },
345 { "varDelta", "vardelta2" },
346 { "varGamma", "vargamma2" },
347 { "varLambda", "varlambda2" },
348 { "varOmega", "varomega2" },
349 { "varPhi", "varphi2" },
350 { "varPi", "varpi2" },
351 { "varPsi", "varpsi2" },
352 { "varSigma", "varsigma2" },
353 { "varTheta", "vartheta2" },
354 { "varUpsilon", "varupsilon2" },
355 { "varXi", "varxi2" }
359 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
361 // This list specifies which system's theme icon is related to which lyx
362 // command. It was based on:
363 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
364 // this must be sorted alphabetically
365 // Upper case comes before lower case
366 PngMap sorted_theme_icon_map[] = {
367 { "bookmark-goto 0", "go-jump" },
368 { "buffer-new", "document-new" },
369 { "buffer-print", "document-print" },
370 { "buffer-write", "document-save" },
371 { "buffer-write-as", "document-save-as" },
372 { "buffer-zoom-in", "zoom-in" },
373 { "buffer-zoom-out", "zoom-out" },
374 { "copy", "edit-copy" },
375 { "cut", "edit-cut" },
376 { "depth-decrement", "format-indent-less" },
377 { "depth-increment", "format-indent-more" },
378 { "dialog-show print", "document-print" },
379 { "dialog-show spellchecker", "tools-check-spelling" },
380 { "dialog-show-new-inset graphics", "insert-image" },
381 { "dialog-toggle findreplaceadv", "edit-find-replace" },
382 { "file-open", "document-open" },
383 { "font-bold", "format-text-bold" },
384 { "font-ital", "format-text-italic" },
385 { "font-strikeout", "format-text-strikethrough" },
386 { "font-underline", "format-text-underline" },
387 { "lyx-quit", "application-exit" },
388 { "paste", "edit-paste" },
389 { "redo", "edit-redo" },
390 { "undo", "edit-undo" },
391 { "window-close", "window-close" },
392 { "window-new", "window-new" }
395 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
398 QString findPng(QString const & name)
400 PngMap const * const begin = sorted_png_map;
401 PngMap const * const end = begin + nr_sorted_png_map;
402 LATTEST(sorted(begin, end));
404 PngMap const * const it = find_if(begin, end, CompareKey(name));
408 png_name = it->value;
411 png_name.replace('_', "underscore");
412 png_name.replace(' ', '_');
414 // This way we can have "math-delim { }" on the toolbar.
415 png_name.replace('(', "lparen");
416 png_name.replace(')', "rparen");
417 png_name.replace('[', "lbracket");
418 png_name.replace(']', "rbracket");
419 png_name.replace('{', "lbrace");
420 png_name.replace('}', "rbrace");
421 png_name.replace('|', "bars");
422 png_name.replace(',', "thinspace");
423 png_name.replace(':', "mediumspace");
424 png_name.replace(';', "thickspace");
425 png_name.replace('!', "negthinspace");
428 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
429 << "Looking for math PNG called \"" << png_name << '"');
436 QString themeIconName(QString const & action)
438 PngMap const * const begin = sorted_theme_icon_map;
439 PngMap const * const end = begin + nr_sorted_theme_icon_map;
440 LASSERT(sorted(begin, end), /**/);
442 PngMap const * const it = find_if(begin, end, CompareKey(action));
450 QString iconName(FuncRequest const & f, bool unknown)
452 initializeResources();
456 switch (f.action()) {
457 case LFUN_MATH_INSERT:
458 if (!f.argument().empty()) {
460 name1 = findPng(toqstr(f.argument()).mid(1));
463 case LFUN_MATH_DELIM:
464 case LFUN_MATH_BIGDELIM:
466 name1 = findPng(toqstr(f.argument()));
470 name1 = toqstr(f.argument());
472 case LFUN_COMMAND_ALTERNATIVES: {
473 // use the first of the alternative commands
475 docstring dummy = split(f.argument(), firstcom, ';');
476 name1 = toqstr(firstcom);
477 // FIXME: we should rename the icons to tabular-xxx instead of
478 // "tabular-feature-xxx"
479 name1.replace("inset-modify tabular", "tabular-feature");
480 name1.replace(' ', '_');
483 case LFUN_INSET_MODIFY: {
484 // FIXME: we should rename the icons to tabular-xxx instead of
485 // "tabular-feature-xxx" and generalize this naming to all
486 // insets, not to tabular using ones.
488 string const command = split(to_utf8(f.argument()), inset_name, ' ');
489 if (insetCode(inset_name) == TABULAR_CODE) {
490 name1 = "tabular-feature "+ toqstr(command);
491 name1.replace(' ', '_');
496 name2 = toqstr(lyxaction.getActionName(f.action()));
499 if (!f.argument().empty()) {
500 name1 = name2 + ' ' + toqstr(f.argument());
501 name1.replace(' ', '_');
502 name1.replace('\\', "backslash");
506 QStringList imagedirs;
507 imagedirs << "images/" << "images/ipa/";
508 for (int i = 0; i < imagedirs.size(); ++i) {
509 QString imagedir = imagedirs.at(i) + path;
510 FileName fname = imageLibFileSearch(imagedir, name1, "png");
512 return toqstr(fname.absFileName());
514 fname = imageLibFileSearch(imagedir, name2, "png");
516 return toqstr(fname.absFileName());
519 path = ":/images/" + path;
522 LYXERR0("Directory " << path << " not found in resource!");
526 if (res.exists(name1))
530 if (res.exists(name2))
533 LYXERR(Debug::GUI, "Cannot find icon with filename "
534 << "\"" << name1 << "\""
536 << "\"" << name2 << "\""
538 << lyxaction.getActionName(f.action())
539 << '(' << to_utf8(f.argument()) << ")\"");
542 QString imagedir = "images/";
543 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
545 return toqstr(fname.absFileName());
546 return QString(":/images/unknown.png");
552 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
555 QString imagedir = path;
556 FileName fname = imageLibFileSearch(imagedir, name, ext);
557 QString path1 = toqstr(fname.absFileName());
558 QString path2 = ":/" + path + name + "." + ext;
560 if (pixmap.load(path1)) {
563 else if (pixmap.load(path2)) {
567 LYXERR0("Cannot load pixmap \""
568 << path << name << '.' << ext
569 << "\", please verify resource system!");
574 QIcon getIcon(FuncRequest const & f, bool unknown)
576 #if (QT_VERSION >= 0x040600)
577 if (lyxrc.use_system_theme_icons) {
578 QString action = toqstr(lyxaction.getActionName(f.action()));
579 if (!f.argument().empty())
580 action += " " + toqstr(f.argument());
581 QString const theme_icon = themeIconName(action);
582 if (QIcon::hasThemeIcon(theme_icon))
583 return QIcon::fromTheme(theme_icon);
587 QString icon = iconName(f, unknown);
591 //LYXERR(Debug::GUI, "Found icon: " << icon);
593 if (!pm.load(icon)) {
594 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
602 ////////////////////////////////////////////////////////////////////////
604 // LyX server support code.
606 ////////////////////////////////////////////////////////////////////////
608 class SocketNotifier : public QSocketNotifier
611 /// connect a connection notification from the LyXServerSocket
612 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
613 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
617 /// The callback function
618 Application::SocketCallback func_;
622 ////////////////////////////////////////////////////////////////////////
624 // Mac specific stuff goes here...
626 ////////////////////////////////////////////////////////////////////////
628 class MenuTranslator : public QTranslator
631 MenuTranslator(QObject * parent)
632 : QTranslator(parent)
635 #if QT_VERSION >= 0x050000
636 virtual QString translate(const char * /* context */,
637 const char *sourceText,
638 const char * /* disambiguation */ = 0, int /* n */ = -1) const
640 QString translate(const char * /*context*/,
641 const char * sourceText,
642 const char * /*comment*/ = 0) const
645 string const s = sourceText;
646 if (s == N_("About %1") || s == N_("Preferences")
647 || s == N_("Reconfigure") || s == N_("Quit %1"))
655 // QMacPasteboardMimeGraphics can only be compiled on Mac.
657 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
660 QMacPasteboardMimeGraphics()
661 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
664 QString convertorName() { return "Graphics"; }
666 QString flavorFor(QString const & mime)
668 LYXERR(Debug::ACTION, "flavorFor " << mime);
669 if (mime == pdfMimeType())
670 return QLatin1String("com.adobe.pdf");
674 QString mimeFor(QString flav)
676 LYXERR(Debug::ACTION, "mimeFor " << flav);
677 if (flav == QLatin1String("com.adobe.pdf"))
678 return pdfMimeType();
682 bool canConvert(QString const & mime, QString flav)
684 return mimeFor(flav) == mime;
687 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
691 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
695 QList<QByteArray> convertFromMime(QString const & /*mime*/,
696 QVariant data, QString /*flav*/)
698 QList<QByteArray> ret;
699 ret.append(data.toByteArray());
705 ///////////////////////////////////////////////////////////////
707 // You can find more platform specific stuff at the end of this file...
709 ///////////////////////////////////////////////////////////////
711 ////////////////////////////////////////////////////////////////////////
712 // Windows specific stuff goes here...
715 // QWindowsMimeMetafile can only be compiled on Windows.
717 static FORMATETC cfFromMime(QString const & mimetype)
720 if (mimetype == emfMimeType()) {
721 formatetc.cfFormat = CF_ENHMETAFILE;
722 formatetc.tymed = TYMED_ENHMF;
723 } else if (mimetype == wmfMimeType()) {
724 formatetc.cfFormat = CF_METAFILEPICT;
725 formatetc.tymed = TYMED_MFPICT;
728 formatetc.dwAspect = DVASPECT_CONTENT;
729 formatetc.lindex = -1;
734 class QWindowsMimeMetafile : public QWindowsMime {
736 QWindowsMimeMetafile() {}
738 bool canConvertFromMime(FORMATETC const & formatetc,
739 QMimeData const * mimedata) const
744 bool canConvertToMime(QString const & mimetype,
745 IDataObject * pDataObj) const
747 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
749 FORMATETC formatetc = cfFromMime(mimetype);
750 return pDataObj->QueryGetData(&formatetc) == S_OK;
753 bool convertFromMime(FORMATETC const & formatetc,
754 const QMimeData * mimedata, STGMEDIUM * pmedium) const
759 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
760 QVariant::Type preferredType) const
763 if (!canConvertToMime(mimetype, pDataObj))
766 FORMATETC formatetc = cfFromMime(mimetype);
768 if (pDataObj->GetData(&formatetc, &s) != S_OK)
772 if (s.tymed == TYMED_ENHMF) {
773 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
774 data.resize(dataSize);
775 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
776 (LPBYTE)data.data());
777 } else if (s.tymed == TYMED_MFPICT) {
778 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
779 data.resize(dataSize);
780 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
781 (LPBYTE)data.data());
784 ReleaseStgMedium(&s);
790 QVector<FORMATETC> formatsForMime(QString const & mimetype,
791 QMimeData const * mimedata) const
793 QVector<FORMATETC> formats;
794 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
795 formats += cfFromMime(mimetype);
799 QString mimeForFormat(FORMATETC const & formatetc) const
801 switch (formatetc.cfFormat) {
803 return emfMimeType();
804 case CF_METAFILEPICT:
805 return wmfMimeType();
814 /// Allows to check whether ESC was pressed during a long operation
815 class KeyChecker : public QObject {
820 KeyChecker() : pressed_(false), started_(false) {}
823 QCoreApplication::instance()->installEventFilter(this);
828 QCoreApplication::instance()->removeEventFilter(this);
832 QCoreApplication::processEvents();
835 bool started() const {
838 bool eventFilter(QObject *obj, QEvent *event) {
839 LYXERR(Debug::ACTION, "Event Type: " << event->type());
840 switch (event->type()) {
844 case QEvent::UpdateRequest:
845 case QEvent::CursorChange:
846 case QEvent::ActionChanged:
847 case QEvent::EnabledChange:
848 case QEvent::SockAct:
851 case QEvent::ToolTipChange:
852 case QEvent::LayoutRequest:
853 case QEvent::MetaCall:
854 return QObject::eventFilter(obj, event);
856 // FIXME Blocking all these events is a bad idea.
857 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
858 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
866 ////////////////////////////////////////////////////////////////////////
867 // GuiApplication::Private definition and implementation.
868 ////////////////////////////////////////////////////////////////////////
870 struct GuiApplication::Private
872 Private(): language_model_(0), meta_fake_bit(NoModifier),
876 /// WMF Mime handler for Windows clipboard.
877 wmf_mime_ = new QWindowsMimeMetafile;
879 initKeySequences(&theTopLevelKeymap());
882 void initKeySequences(KeyMap * kb)
884 keyseq = KeySequence(kb, kb);
885 cancel_meta_seq = KeySequence(kb, kb);
889 QSortFilterProxyModel * language_model_;
891 GuiClipboard clipboard_;
893 GuiSelection selection_;
895 FontLoader font_loader_;
897 ColorCache color_cache_;
899 QTranslator qt_trans_;
901 QHash<int, SocketNotifier *> socket_notifiers_;
905 /// The global instance
908 /// this timer is used for any regular events one wants to
909 /// perform. at present it is used to check if forked processes
911 QTimer general_timer_;
913 /// delayed FuncRequests
914 std::queue<FuncRequest> func_request_queue_;
919 KeySequence cancel_meta_seq;
921 KeyModifier meta_fake_bit;
923 /// Multiple views container.
925 * Warning: This must not be a smart pointer as the destruction of the
926 * object is handled by Qt when the view is closed
927 * \sa Qt::WA_DeleteOnClose attribute.
929 QHash<int, GuiView *> views_;
931 /// Only used on mac.
932 QMenuBar * global_menubar_;
935 /// Linkback mime handler for MacOSX.
936 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
940 /// WMF Mime handler for Windows clipboard.
941 QWindowsMimeMetafile * wmf_mime_;
944 /// Allows to check whether ESC was pressed during a long operation
945 KeyChecker key_checker_;
949 GuiApplication * guiApp;
951 GuiApplication::~GuiApplication()
954 closeAllLinkBackLinks();
960 GuiApplication::GuiApplication(int & argc, char ** argv)
961 : QApplication(argc, argv), current_view_(0),
962 d(new GuiApplication::Private)
964 QString app_name = "LyX";
965 QCoreApplication::setOrganizationName(app_name);
966 QCoreApplication::setOrganizationDomain("lyx.org");
967 QCoreApplication::setApplicationName(lyx_package);
969 qsrand(QDateTime::currentDateTime().toTime_t());
971 // Install translator for GUI elements.
972 installTranslator(&d->qt_trans_);
974 // FIXME: quitOnLastWindowClosed is true by default. We should have a
975 // lyxrc setting for this in order to let the application stay resident.
976 // But then we need some kind of dock icon, at least on Windows.
978 if (lyxrc.quit_on_last_window_closed)
979 setQuitOnLastWindowClosed(false);
982 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
983 // seems to be the default case for applications like LyX.
984 setQuitOnLastWindowClosed(false);
985 // This allows to translate the strings that appear in the LyX menu.
986 /// A translator suitable for the entries in the LyX menu.
987 /// Only needed with Qt/Mac.
988 installTranslator(new MenuTranslator(this));
994 // doubleClickInterval() is 400 ms on X11 which is just too long.
995 // On Windows and Mac OS X, the operating system's value is used.
996 // On Microsoft Windows, calling this function sets the double
997 // click interval for all applications. So we don't!
998 QApplication::setDoubleClickInterval(300);
1001 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1003 // needs to be done before reading lyxrc
1005 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1009 // Set the cache to 5120 kilobytes which corresponds to screen size of
1010 // 1280 by 1024 pixels with a color depth of 32 bits.
1011 QPixmapCache::setCacheLimit(5120);
1013 // Initialize RC Fonts
1014 if (lyxrc.roman_font_name.empty())
1015 lyxrc.roman_font_name = fromqstr(romanFontName());
1017 if (lyxrc.sans_font_name.empty())
1018 lyxrc.sans_font_name = fromqstr(sansFontName());
1020 if (lyxrc.typewriter_font_name.empty())
1021 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1023 d->general_timer_.setInterval(500);
1024 connect(&d->general_timer_, SIGNAL(timeout()),
1025 this, SLOT(handleRegularEvents()));
1026 d->general_timer_.start();
1028 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1029 // This is clearly not enough in a time where we use threads for
1030 // document preview and/or export. 20 should be OK.
1031 QThreadPool::globalInstance()->setMaxThreadCount(20);
1035 GuiApplication * theGuiApp()
1037 return dynamic_cast<GuiApplication *>(theApp());
1041 void GuiApplication::clearSession()
1048 docstring Application::iconName(FuncRequest const & f, bool unknown)
1050 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1054 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1058 BufferView * bv = 0;
1059 BufferView * doc_bv = 0;
1061 if (cmd.action() == LFUN_NOACTION) {
1062 status.message(from_utf8(N_("Nothing to do")));
1063 status.setEnabled(false);
1066 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1067 status.setUnknown(true);
1068 status.message(from_utf8(N_("Unknown action")));
1069 status.setEnabled(false);
1072 // Does the GuiApplication know something?
1073 else if (getStatus(cmd, status)) { }
1075 // If we do not have a GuiView, then other functions are disabled
1076 else if (!current_view_)
1077 status.setEnabled(false);
1079 // Does the GuiView know something?
1080 else if (current_view_->getStatus(cmd, status)) { }
1082 // In LyX/Mac, when a dialog is open, the menus of the
1083 // application can still be accessed without giving focus to
1084 // the main window. In this case, we want to disable the menu
1085 // entries that are buffer or view-related.
1086 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1088 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1089 status.setEnabled(false);
1092 // If we do not have a BufferView, then other functions are disabled
1093 else if (!(bv = current_view_->currentBufferView()))
1094 status.setEnabled(false);
1096 // Does the current BufferView know something?
1097 else if (bv->getStatus(cmd, status)) { }
1099 // Does the current Buffer know something?
1100 else if (bv->buffer().getStatus(cmd, status)) { }
1102 // If we do not have a document BufferView, different from the
1103 // current BufferView, then other functions are disabled
1104 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1105 status.setEnabled(false);
1107 // Does the document Buffer know something?
1108 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1111 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1112 status.message(from_utf8(N_("Command not handled")));
1113 status.setEnabled(false);
1116 // the default error message if we disable the command
1117 if (!status.enabled() && status.message().empty())
1118 status.message(from_utf8(N_("Command disabled")));
1124 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1126 // I would really like to avoid having this switch and rather try to
1127 // encode this in the function itself.
1128 // -- And I'd rather let an inset decide which LFUNs it is willing
1129 // to handle (Andre')
1131 switch (cmd.action()) {
1133 // This could be used for the no-GUI version. The GUI version is handled in
1134 // GuiView::getStatus(). See above.
1136 case LFUN_BUFFER_WRITE:
1137 case LFUN_BUFFER_WRITE_AS: {
1138 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1139 enable = b && (b->isUnnamed() || !b->isClean());
1144 case LFUN_BOOKMARK_GOTO: {
1145 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1146 enable = theSession().bookmarks().isValid(num);
1150 case LFUN_BOOKMARK_CLEAR:
1151 enable = theSession().bookmarks().hasValid();
1154 // this one is difficult to get right. As a half-baked
1155 // solution, we consider only the first action of the sequence
1156 case LFUN_COMMAND_SEQUENCE: {
1157 // argument contains ';'-terminated commands
1158 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1159 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1160 func.setOrigin(cmd.origin());
1161 flag = getStatus(func);
1165 // we want to check if at least one of these is enabled
1166 case LFUN_COMMAND_ALTERNATIVES: {
1167 // argument contains ';'-terminated commands
1168 string arg = to_utf8(cmd.argument());
1169 while (!arg.empty()) {
1171 arg = split(arg, first, ';');
1172 FuncRequest func(lyxaction.lookupFunc(first));
1173 func.setOrigin(cmd.origin());
1174 flag = getStatus(func);
1175 // if this one is enabled, the whole thing is
1184 string name = to_utf8(cmd.argument());
1185 if (theTopLevelCmdDef().lock(name, func)) {
1186 func.setOrigin(cmd.origin());
1187 flag = getStatus(func);
1188 theTopLevelCmdDef().release(name);
1190 // catch recursion or unknown command
1191 // definition. all operations until the
1192 // recursion or unknown command definition
1193 // occurs are performed, so set the state to
1200 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1202 case LFUN_PREFERENCES_SAVE:
1203 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1204 case LFUN_DEBUG_LEVEL_SET:
1205 // these are handled in our dispatch()
1208 case LFUN_WINDOW_CLOSE:
1209 enable = d->views_.size() > 0;
1212 case LFUN_BUFFER_NEW:
1213 case LFUN_BUFFER_NEW_TEMPLATE:
1214 case LFUN_FILE_OPEN:
1215 case LFUN_HELP_OPEN:
1216 case LFUN_SCREEN_FONT_UPDATE:
1217 case LFUN_SET_COLOR:
1218 case LFUN_WINDOW_NEW:
1220 case LFUN_LYXRC_APPLY:
1221 case LFUN_COMMAND_PREFIX:
1223 case LFUN_META_PREFIX:
1224 case LFUN_RECONFIGURE:
1225 case LFUN_SERVER_GET_FILENAME:
1226 case LFUN_SERVER_NOTIFY:
1230 case LFUN_BUFFER_FORALL: {
1231 if (theBufferList().empty()) {
1232 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1233 flag.setEnabled(false);
1237 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1238 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1239 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1240 flag.setEnabled(false);
1245 case LFUN_DIALOG_SHOW: {
1246 string const name = cmd.getArg(0);
1247 return name == "aboutlyx"
1249 || name == "texinfo"
1250 || name == "progress"
1251 || name == "compare";
1259 flag.setEnabled(false);
1263 /// make a post-dispatch status message
1264 static docstring makeDispatchMessage(docstring const & msg,
1265 FuncRequest const & cmd)
1267 const bool verbose = (cmd.origin() == FuncRequest::MENU
1268 || cmd.origin() == FuncRequest::TOOLBAR
1269 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1271 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1272 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1276 docstring dispatch_msg = msg;
1277 if (!dispatch_msg.empty())
1278 dispatch_msg += ' ';
1280 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1282 bool argsadded = false;
1284 if (!cmd.argument().empty()) {
1285 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1286 comname += ' ' + cmd.argument();
1290 docstring const shortcuts = theTopLevelKeymap().
1291 printBindings(cmd, KeySequence::ForGui);
1293 if (!shortcuts.empty())
1294 comname += ": " + shortcuts;
1295 else if (!argsadded && !cmd.argument().empty())
1296 comname += ' ' + cmd.argument();
1298 if (!comname.empty()) {
1299 comname = rtrim(comname);
1300 dispatch_msg += '(' + rtrim(comname) + ')';
1302 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1303 return dispatch_msg;
1307 void GuiApplication::dispatch(FuncRequest const & cmd)
1309 Buffer * buffer = 0;
1310 if (current_view_ && current_view_->currentBufferView()) {
1311 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1312 buffer = ¤t_view_->currentBufferView()->buffer();
1314 buffer->undo().beginUndoGroup();
1318 // redraw the screen at the end (first of the two drawing steps).
1319 // This is done unless explicitly requested otherwise
1320 dr.screenUpdate(Update::FitCursor);
1322 updateCurrentView(cmd, dr);
1324 // the buffer may have been closed by one action
1325 if (theBufferList().isLoaded(buffer))
1326 buffer->undo().endUndoGroup();
1330 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1335 BufferView * bv = current_view_->currentBufferView();
1337 if (dr.needBufferUpdate()) {
1338 bv->cursor().clearBufferUpdate();
1339 bv->buffer().updateBuffer();
1341 // BufferView::update() updates the ViewMetricsInfo and
1342 // also initializes the position cache for all insets in
1343 // (at least partially) visible top-level paragraphs.
1344 // We will redraw the screen only if needed.
1345 bv->processUpdateFlags(dr.screenUpdate());
1347 // Do we have a selection?
1348 theSelection().haveSelection(bv->cursor().selection());
1351 current_view_->restartCursor();
1353 if (dr.needMessageUpdate()) {
1354 // Some messages may already be translated, so we cannot use _()
1355 current_view_->message(makeDispatchMessage(
1356 translateIfPossible(dr.message()), cmd));
1361 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1362 bool switchToBuffer)
1364 if (!theSession().bookmarks().isValid(idx))
1366 BookmarksSection::Bookmark const & bm =
1367 theSession().bookmarks().bookmark(idx);
1368 LASSERT(!bm.filename.empty(), return);
1369 string const file = bm.filename.absFileName();
1370 // if the file is not opened, open it.
1371 if (!theBufferList().exists(bm.filename)) {
1373 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1377 // open may fail, so we need to test it again
1378 if (!theBufferList().exists(bm.filename))
1381 // bm can be changed when saving
1382 BookmarksSection::Bookmark tmp = bm;
1384 // Special case idx == 0 used for back-from-back jump navigation
1386 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1388 // if the current buffer is not that one, switch to it.
1389 BufferView * doc_bv = current_view_ ?
1390 current_view_->documentBufferView() : 0;
1391 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1392 if (switchToBuffer) {
1393 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1396 doc_bv = current_view_->documentBufferView();
1401 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1402 if (!doc_bv->moveToPosition(
1403 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1410 // Cursor jump succeeded!
1411 Cursor const & cur = doc_bv->cursor();
1412 pit_type new_pit = cur.pit();
1413 pos_type new_pos = cur.pos();
1414 int new_id = cur.paragraph().id();
1416 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1417 // see http://www.lyx.org/trac/ticket/3092
1418 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1419 || bm.top_id != new_id) {
1420 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1421 new_pit, new_pos, new_id);
1425 // This function runs "configure" and then rereads lyx.defaults to
1426 // reconfigure the automatic settings.
1427 void GuiApplication::reconfigure(string const & option)
1429 // emit message signal.
1431 current_view_->message(_("Running configure..."));
1433 // Run configure in user lyx directory
1434 PathChanger p(package().user_support());
1435 string configure_command = package().configure_command();
1436 configure_command += option;
1438 int const ret = one.startscript(Systemcall::Wait, configure_command);
1440 // emit message signal.
1442 current_view_->message(_("Reloading configuration..."));
1443 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1444 // Re-read packages.lst
1445 LaTeXPackages::getAvailable();
1448 Alert::information(_("System reconfiguration failed"),
1449 _("The system reconfiguration has failed.\n"
1450 "Default textclass is used but LyX may\n"
1451 "not be able to work properly.\n"
1452 "Please reconfigure again if needed."));
1454 Alert::information(_("System reconfigured"),
1455 _("The system has been reconfigured.\n"
1456 "You need to restart LyX to make use of any\n"
1457 "updated document class specifications."));
1460 void GuiApplication::validateCurrentView()
1462 if (!d->views_.empty() && !current_view_) {
1463 // currently at least one view exists but no view has the focus.
1464 // choose the last view to make it current.
1465 // a view without any open document is preferred.
1466 GuiView * candidate = 0;
1467 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1468 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1469 for (; it != end; ++it) {
1471 if (!candidate->documentBufferView())
1474 setCurrentView(candidate);
1478 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1480 string const argument = to_utf8(cmd.argument());
1481 FuncCode const action = cmd.action();
1483 LYXERR(Debug::ACTION, "cmd: " << cmd);
1485 // we have not done anything wrong yet.
1488 FuncStatus const flag = getStatus(cmd);
1489 if (!flag.enabled()) {
1490 // We cannot use this function here
1491 LYXERR(Debug::ACTION, "action "
1492 << lyxaction.getActionName(action)
1493 << " [" << action << "] is disabled at this location");
1494 dr.setMessage(flag.message());
1496 dr.dispatched(false);
1497 dr.screenUpdate(Update::None);
1498 dr.clearBufferUpdate();
1502 if (cmd.origin() == FuncRequest::LYXSERVER) {
1503 if (current_view_ && current_view_->currentBufferView())
1504 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1505 // we will also need to redraw the screen at the end
1506 dr.screenUpdate(Update::FitCursor);
1509 // Assumes that the action will be dispatched.
1510 dr.dispatched(true);
1512 switch (cmd.action()) {
1514 case LFUN_WINDOW_NEW:
1515 createView(toqstr(cmd.argument()));
1518 case LFUN_WINDOW_CLOSE:
1519 // update bookmark pit of the current buffer before window close
1520 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1521 gotoBookmark(i+1, false, false);
1522 // clear the last opened list, because
1523 // maybe this will end the session
1524 theSession().lastOpened().clear();
1525 // check for valid current_view_
1526 validateCurrentView();
1528 current_view_->closeScheduled();
1532 // quitting is triggered by the gui code
1533 // (leaving the event loop).
1535 current_view_->message(from_utf8(N_("Exiting.")));
1536 if (closeAllViews())
1540 case LFUN_SCREEN_FONT_UPDATE: {
1541 // handle the screen font changes.
1542 d->font_loader_.update();
1543 // Backup current_view_
1544 GuiView * view = current_view_;
1545 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1546 // to skip the refresh.
1548 theBufferList().changed(false);
1549 // Restore current_view_
1550 current_view_ = view;
1554 case LFUN_BUFFER_NEW:
1555 validateCurrentView();
1556 if (d->views_.empty()
1557 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1558 createView(QString(), false); // keep hidden
1559 current_view_->newDocument(to_utf8(cmd.argument()), false);
1560 current_view_->show();
1561 setActiveWindow(current_view_);
1563 current_view_->newDocument(to_utf8(cmd.argument()), false);
1567 case LFUN_BUFFER_NEW_TEMPLATE:
1568 validateCurrentView();
1569 if (d->views_.empty()
1570 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1572 current_view_->newDocument(to_utf8(cmd.argument()), true);
1573 if (!current_view_->documentBufferView())
1574 current_view_->close();
1576 current_view_->newDocument(to_utf8(cmd.argument()), true);
1580 case LFUN_FILE_OPEN: {
1581 validateCurrentView();
1582 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1583 string const fname = to_utf8(cmd.argument());
1584 bool const is_open = FileName::isAbsolute(fname)
1585 && theBufferList().getBuffer(FileName(fname));
1586 if (d->views_.empty()
1587 || (!lyxrc.open_buffers_in_tabs
1588 && current_view_->documentBufferView() != 0
1590 // We want the ui session to be saved per document and not per
1591 // window number. The filename crc is a good enough identifier.
1592 boost::crc_32_type crc;
1593 crc = for_each(fname.begin(), fname.end(), crc);
1594 createView(crc.checksum());
1595 current_view_->openDocument(fname);
1596 if (current_view_ && !current_view_->documentBufferView())
1597 current_view_->close();
1599 current_view_->openDocument(fname);
1603 case LFUN_HELP_OPEN: {
1604 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1605 if (current_view_ == 0)
1607 string const arg = to_utf8(cmd.argument());
1609 current_view_->message(_("Missing argument"));
1612 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1614 fname = i18nLibFileSearch("examples", arg, "lyx");
1616 if (fname.empty()) {
1617 lyxerr << "LyX: unable to find documentation file `"
1618 << arg << "'. Bad installation?" << endl;
1621 current_view_->message(bformat(_("Opening help file %1$s..."),
1622 makeDisplayPath(fname.absFileName())));
1623 Buffer * buf = current_view_->loadDocument(fname, false);
1625 #ifndef DEVEL_VERSION
1627 buf->setReadonly(true);
1634 case LFUN_SET_COLOR: {
1636 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1637 if (lyx_name.empty() || x11_name.empty()) {
1639 current_view_->message(
1640 _("Syntax: set-color <lyx_name> <x11_name>"));
1645 // FIXME: The graphics cache no longer has a changeDisplay method.
1646 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1647 bool const graphicsbg_changed =
1648 lyx_name == graphicsbg && x11_name != graphicsbg;
1649 if (graphicsbg_changed)
1650 graphics::GCache::get().changeDisplay(true);
1653 if (!lcolor.setColor(lyx_name, x11_name)) {
1655 current_view_->message(
1656 bformat(_("Set-color \"%1$s\" failed "
1657 "- color is undefined or "
1658 "may not be redefined"),
1659 from_utf8(lyx_name)));
1662 // Make sure we don't keep old colors in cache.
1663 d->color_cache_.clear();
1667 case LFUN_LYXRC_APPLY: {
1668 // reset active key sequences, since the bindings
1669 // are updated (bug 6064)
1671 LyXRC const lyxrc_orig = lyxrc;
1673 istringstream ss(to_utf8(cmd.argument()));
1674 bool const success = lyxrc.read(ss);
1677 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1678 << "Unable to read lyxrc data"
1683 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1685 // If the request comes from the minibuffer, then we can't reset
1686 // the GUI, since that would destory the minibuffer itself and
1687 // cause a crash, since we are currently in one of the methods of
1688 // GuiCommandBuffer. See bug #8540.
1689 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1692 // FIXME Unfortunately, that leaves a bug here, since we cannot
1693 // reset the GUI in this case. If the changes to lyxrc affected the
1694 // UI, then, nothing would happen. This seems fairly unlikely, but
1695 // it definitely is a bug.
1700 case LFUN_COMMAND_PREFIX:
1701 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1706 d->meta_fake_bit = NoModifier;
1707 GuiView * gv = currentView();
1708 if (gv && gv->currentBufferView())
1709 // cancel any selection
1710 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1711 dr.setMessage(from_ascii(N_("Cancel")));
1714 case LFUN_META_PREFIX:
1715 d->meta_fake_bit = AltModifier;
1716 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1719 // --- Menus -----------------------------------------------
1720 case LFUN_RECONFIGURE:
1721 // argument is any additional parameter to the configure.py command
1722 reconfigure(to_utf8(cmd.argument()));
1725 // --- lyxserver commands ----------------------------
1726 case LFUN_SERVER_GET_FILENAME: {
1727 if (current_view_ && current_view_->documentBufferView()) {
1728 docstring const fname = from_utf8(
1729 current_view_->documentBufferView()->buffer().absFileName());
1730 dr.setMessage(fname);
1731 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1733 dr.setMessage(docstring());
1734 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1739 case LFUN_SERVER_NOTIFY: {
1740 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1741 dr.setMessage(dispatch_buffer);
1742 theServer().notifyClient(to_utf8(dispatch_buffer));
1746 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1747 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1753 string rest = split(argument, countstr, ' ');
1754 istringstream is(countstr);
1757 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1758 for (int i = 0; i < count; ++i)
1759 dispatch(lyxaction.lookupFunc(rest));
1763 case LFUN_COMMAND_SEQUENCE: {
1764 // argument contains ';'-terminated commands
1765 string arg = argument;
1766 // FIXME: this LFUN should also work without any view.
1767 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1768 ? &(current_view_->documentBufferView()->buffer()) : 0;
1770 buffer->undo().beginUndoGroup();
1771 while (!arg.empty()) {
1773 arg = split(arg, first, ';');
1774 FuncRequest func(lyxaction.lookupFunc(first));
1775 func.setOrigin(cmd.origin());
1778 // the buffer may have been closed by one action
1779 if (theBufferList().isLoaded(buffer))
1780 buffer->undo().endUndoGroup();
1784 case LFUN_BUFFER_FORALL: {
1785 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1787 map<Buffer *, GuiView *> views_lVisible;
1788 map<GuiView *, Buffer *> activeBuffers;
1790 QList<GuiView *> allViews = d->views_.values();
1792 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1793 // and on which buffer is active in each view.
1794 Buffer * const last = theBufferList().last();
1795 foreach (GuiView * view, allViews) {
1796 // all of the buffers might be locally hidden. That is, there is no active buffer.
1797 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1798 activeBuffers[view] = 0;
1800 activeBuffers[view] = &view->currentBufferView()->buffer();
1802 // find out if each is locally visible or locally hidden.
1803 // we don't use a for loop as the buffer list cycles.
1804 Buffer * b = theBufferList().first();
1806 bool const locallyVisible = view && view->workArea(*b);
1807 if (locallyVisible) {
1808 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1809 // only need to overwrite/add if we don't already know a buffer is globally
1810 // visible or we do know but we would prefer to dispatch LFUN from the
1811 // current view because of cursor position issues.
1812 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1813 views_lVisible[b] = view;
1817 b = theBufferList().next(b);
1821 GuiView * const homeView = currentView();
1822 Buffer * b = theBufferList().first();
1823 Buffer * nextBuf = 0;
1824 int numProcessed = 0;
1827 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1829 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1831 // first change to a view where b is locally visible, preferably current_view_.
1832 GuiView * const vLv = views_lVisible[b];
1834 lyx::dispatch(funcToRun);
1842 // put things back to how they were (if possible).
1843 foreach (GuiView * view, allViews) {
1844 Buffer * originalBuf = activeBuffers[view];
1845 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1846 if (theBufferList().isLoaded(originalBuf))
1847 view->setBuffer(originalBuf);
1849 homeView->setFocus();
1851 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1855 case LFUN_COMMAND_ALTERNATIVES: {
1856 // argument contains ';'-terminated commands
1857 string arg = argument;
1858 while (!arg.empty()) {
1860 arg = split(arg, first, ';');
1861 FuncRequest func(lyxaction.lookupFunc(first));
1862 func.setOrigin(cmd.origin());
1863 FuncStatus const stat = getStatus(func);
1864 if (stat.enabled()) {
1874 if (theTopLevelCmdDef().lock(argument, func)) {
1875 func.setOrigin(cmd.origin());
1877 theTopLevelCmdDef().release(argument);
1879 if (func.action() == LFUN_UNKNOWN_ACTION) {
1880 // unknown command definition
1881 lyxerr << "Warning: unknown command definition `"
1885 // recursion detected
1886 lyxerr << "Warning: Recursion in the command definition `"
1887 << argument << "' detected"
1894 case LFUN_PREFERENCES_SAVE:
1895 lyxrc.write(support::makeAbsPath("preferences",
1896 package().user_support().absFileName()), false);
1899 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1900 string const fname = addName(addPath(package().user_support().absFileName(),
1901 "templates/"), "defaults.lyx");
1902 Buffer defaults(fname);
1904 istringstream ss(argument);
1909 // We need to make sure that, after we recreat the DocumentClass,
1910 // which we do in readHeader, we apply it to the document itself.
1911 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1912 int const unknown_tokens = defaults.readHeader(lex);
1913 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1915 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1916 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1918 if (unknown_tokens != 0) {
1919 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1920 << unknown_tokens << " unknown token"
1921 << (unknown_tokens == 1 ? "" : "s")
1925 if (defaults.writeFile(FileName(defaults.absFileName())))
1926 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1927 makeDisplayPath(fname)));
1930 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1935 case LFUN_BOOKMARK_GOTO:
1936 // go to bookmark, open unopened file and switch to buffer if necessary
1937 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1938 dr.screenUpdate(Update::Force | Update::FitCursor);
1941 case LFUN_BOOKMARK_CLEAR:
1942 theSession().bookmarks().clear();
1945 case LFUN_DEBUG_LEVEL_SET:
1946 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1949 case LFUN_DIALOG_SHOW: {
1950 string const name = cmd.getArg(0);
1952 if ( name == "aboutlyx"
1954 || name == "texinfo"
1955 || name == "progress"
1956 || name == "compare")
1958 // work around: on Mac OS the application
1959 // is not terminated when closing the last view.
1960 // Create a new one to be able to dispatch the
1961 // LFUN_DIALOG_SHOW to this view.
1962 if (current_view_ == 0)
1968 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1971 current_view_->dispatch(cmd, dr);
1975 if (cmd.origin() == FuncRequest::LYXSERVER)
1976 updateCurrentView(cmd, dr);
1980 docstring GuiApplication::viewStatusMessage()
1982 // When meta-fake key is pressed, show the key sequence so far + "M-".
1983 if (d->meta_fake_bit != NoModifier)
1984 return d->keyseq.print(KeySequence::ForGui) + "M-";
1986 // Else, when a non-complete key sequence is pressed,
1987 // show the available options.
1988 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1989 return d->keyseq.printOptions(true);
1995 void GuiApplication::handleKeyFunc(FuncCode action)
1999 if (d->keyseq.length())
2001 GuiView * gv = currentView();
2002 LASSERT(gv && gv->currentBufferView(), return);
2003 BufferView * bv = gv->currentBufferView();
2004 bv->getIntl().getTransManager().deadkey(
2005 c, get_accent(action).accent, bv->cursor().innerText(),
2007 // Need to clear, in case the minibuffer calls these
2010 // copied verbatim from do_accent_char
2011 bv->cursor().resetAnchor();
2015 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2017 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2019 // Do nothing if we have nothing (JMarc)
2020 if (!keysym.isOK()) {
2021 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2023 current_view_->restartCursor();
2027 if (keysym.isModifier()) {
2029 current_view_->restartCursor();
2033 char_type encoded_last_key = keysym.getUCSEncoded();
2035 // Do a one-deep top-level lookup for
2036 // cancel and meta-fake keys. RVDK_PATCH_5
2037 d->cancel_meta_seq.reset();
2039 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2040 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2042 // When not cancel or meta-fake, do the normal lookup.
2043 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2044 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2045 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2046 // remove Caps Lock and Mod2 as a modifiers
2047 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2048 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2051 // Dont remove this unless you know what you are doing.
2052 d->meta_fake_bit = NoModifier;
2054 // Can this happen now ?
2055 if (func.action() == LFUN_NOACTION)
2056 func = FuncRequest(LFUN_COMMAND_PREFIX);
2058 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2059 << d->keyseq.print(KeySequence::Portable) << ']');
2061 // already here we know if it any point in going further
2062 // why not return already here if action == -1 and
2063 // num_bytes == 0? (Lgb)
2065 if (d->keyseq.length() > 1 && current_view_)
2066 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2069 // Maybe user can only reach the key via holding down shift.
2070 // Let's see. But only if shift is the only modifier
2071 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2072 LYXERR(Debug::KEY, "Trying without shift");
2073 func = d->keyseq.addkey(keysym, NoModifier);
2074 LYXERR(Debug::KEY, "Action now " << func.action());
2077 if (func.action() == LFUN_UNKNOWN_ACTION) {
2078 // Hmm, we didn't match any of the keysequences. See
2079 // if it's normal insertable text not already covered
2081 if (keysym.isText() && d->keyseq.length() == 1) {
2082 LYXERR(Debug::KEY, "isText() is true, inserting.");
2083 func = FuncRequest(LFUN_SELF_INSERT,
2084 FuncRequest::KEYBOARD);
2086 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2087 if (current_view_) {
2088 current_view_->message(_("Unknown function."));
2089 current_view_->restartCursor();
2095 if (func.action() == LFUN_SELF_INSERT) {
2096 if (encoded_last_key != 0) {
2097 docstring const arg(1, encoded_last_key);
2098 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2099 FuncRequest::KEYBOARD));
2100 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2103 processFuncRequest(func);
2107 void GuiApplication::processFuncRequest(FuncRequest const & func)
2109 lyx::dispatch(func);
2113 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2115 addToFuncRequestQueue(func);
2116 processFuncRequestQueueAsync();
2120 void GuiApplication::processFuncRequestQueue()
2122 while (!d->func_request_queue_.empty()) {
2123 processFuncRequest(d->func_request_queue_.front());
2124 d->func_request_queue_.pop();
2129 void GuiApplication::processFuncRequestQueueAsync()
2131 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2135 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2137 d->func_request_queue_.push(func);
2141 void GuiApplication::resetGui()
2143 // Set the language defined by the user.
2147 if (!readUIFile(toqstr(lyxrc.ui_file)))
2148 // Gives some error box here.
2151 if (d->global_menubar_)
2152 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2154 QHash<int, GuiView *>::iterator it;
2155 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2158 gv->setLayoutDirection(layoutDirection());
2162 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2166 void GuiApplication::createView(int view_id)
2168 createView(QString(), true, view_id);
2172 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2175 // release the keyboard which might have been grabed by the global
2176 // menubar on Mac to catch shortcuts even without any GuiView.
2177 if (d->global_menubar_)
2178 d->global_menubar_->releaseKeyboard();
2182 while (d->views_.find(id) != d->views_.end())
2185 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2186 GuiView * view = new GuiView(id);
2188 d->views_[id] = view;
2192 setActiveWindow(view);
2195 if (!geometry_arg.isEmpty()) {
2199 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2200 re.indexIn(geometry_arg);
2201 w = re.cap(1).toInt();
2202 h = re.cap(2).toInt();
2203 x = re.cap(3).toInt();
2204 y = re.cap(4).toInt();
2205 view->setGeometry(x, y, w, h);
2212 Clipboard & GuiApplication::clipboard()
2214 return d->clipboard_;
2218 Selection & GuiApplication::selection()
2220 return d->selection_;
2224 FontLoader & GuiApplication::fontLoader()
2226 return d->font_loader_;
2230 Toolbars const & GuiApplication::toolbars() const
2232 return d->toolbars_;
2236 Toolbars & GuiApplication::toolbars()
2238 return d->toolbars_;
2242 Menus const & GuiApplication::menus() const
2248 Menus & GuiApplication::menus()
2254 QList<int> GuiApplication::viewIds() const
2256 return d->views_.keys();
2260 ColorCache & GuiApplication::colorCache()
2262 return d->color_cache_;
2266 int GuiApplication::exec()
2268 // asynchronously handle batch commands. This event will be in
2269 // the event queue in front of other asynchronous events. Hence,
2270 // we can assume in the latter that the gui is setup already.
2271 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2273 return QApplication::exec();
2277 void GuiApplication::exit(int status)
2279 QApplication::exit(status);
2283 void GuiApplication::setGuiLanguage()
2287 // install translation file for Qt built-in dialogs
2288 QString const language_name = QString("qt_") + theLocale.name();
2289 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2290 // Short-named translator can be loaded from a long name, but not the
2291 // opposite. Therefore, long name should be used without truncation.
2292 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2293 if (!d->qt_trans_.load(language_name,
2294 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2295 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2298 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2302 switch (theLocale.language()) {
2303 case QLocale::Arabic :
2304 case QLocale::Hebrew :
2305 case QLocale::Persian :
2306 case QLocale::Urdu :
2307 setLayoutDirection(Qt::RightToLeft);
2310 setLayoutDirection(Qt::LeftToRight);
2315 void GuiApplication::execBatchCommands()
2320 if (!readUIFile(toqstr(lyxrc.ui_file)))
2321 // Gives some error box here.
2325 #if QT_VERSION > 0x040600
2326 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2328 // Create the global default menubar which is shown for the dialogs
2329 // and if no GuiView is visible.
2330 // This must be done after the session was recovered to know the "last files".
2331 d->global_menubar_ = new QMenuBar(0);
2332 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2335 lyx::execBatchCommands();
2339 QAbstractItemModel * GuiApplication::languageModel()
2341 if (d->language_model_)
2342 return d->language_model_;
2344 QStandardItemModel * lang_model = new QStandardItemModel(this);
2345 lang_model->insertColumns(0, 3);
2347 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2348 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2349 Languages::const_iterator it = lyx::languages.begin();
2350 Languages::const_iterator end = lyx::languages.end();
2351 for (; it != end; ++it) {
2352 current_row = lang_model->rowCount();
2353 lang_model->insertRows(current_row, 1);
2354 QModelIndex pl_item = lang_model->index(current_row, 0);
2355 QModelIndex sp_item = lang_model->index(current_row, 1);
2356 QModelIndex th_item = lang_model->index(current_row, 2);
2357 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2358 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2359 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2360 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2361 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2362 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2363 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2364 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2365 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2366 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2368 d->language_model_ = new QSortFilterProxyModel(this);
2369 d->language_model_->setSourceModel(lang_model);
2370 d->language_model_->setSortLocaleAware(true);
2371 return d->language_model_;
2375 void GuiApplication::restoreGuiSession()
2377 if (!lyxrc.load_session)
2380 Session & session = theSession();
2381 LastOpenedSection::LastOpened const & lastopened =
2382 session.lastOpened().getfiles();
2384 validateCurrentView();
2386 FileName active_file;
2387 // do not add to the lastfile list since these files are restored from
2388 // last session, and should be already there (regular files), or should
2389 // not be added at all (help files).
2390 for (size_t i = 0; i < lastopened.size(); ++i) {
2391 FileName const & file_name = lastopened[i].file_name;
2392 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2393 && current_view_->documentBufferView() != 0)) {
2394 boost::crc_32_type crc;
2395 string const & fname = file_name.absFileName();
2396 crc = for_each(fname.begin(), fname.end(), crc);
2397 createView(crc.checksum());
2399 current_view_->loadDocument(file_name, false);
2401 if (lastopened[i].active)
2402 active_file = file_name;
2405 // Restore last active buffer
2406 Buffer * buffer = theBufferList().getBuffer(active_file);
2407 if (buffer && current_view_)
2408 current_view_->setBuffer(buffer);
2410 // clear this list to save a few bytes of RAM
2411 session.lastOpened().clear();
2415 QString const GuiApplication::romanFontName()
2418 font.setStyleHint(QFont::Serif);
2419 font.setFamily("serif");
2421 return QFontInfo(font).family();
2425 QString const GuiApplication::sansFontName()
2428 font.setStyleHint(QFont::SansSerif);
2429 font.setFamily("sans");
2431 return QFontInfo(font).family();
2435 QString const GuiApplication::typewriterFontName()
2438 font.setStyleHint(QFont::TypeWriter);
2439 font.setFamily("monospace");
2441 return QFontInfo(font).family();
2445 void GuiApplication::handleRegularEvents()
2447 ForkedCallsController::handleCompletedProcesses();
2451 bool GuiApplication::event(QEvent * e)
2454 case QEvent::FileOpen: {
2455 // Open a file; this happens only on Mac OS X for now.
2457 // We do this asynchronously because on startup the batch
2458 // commands are not executed here yet and the gui is not ready
2460 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2461 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2462 processFuncRequestAsync(fr);
2467 return QApplication::event(e);
2472 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2475 return QApplication::notify(receiver, event);
2477 catch (ExceptionMessage const & e) {
2479 case ErrorException:
2481 setQuitOnLastWindowClosed(false);
2483 Alert::error(e.title_, e.details_);
2485 // Properly crash in debug mode in order to get a useful backtrace.
2488 // In release mode, try to exit gracefully.
2491 case BufferException: {
2492 if (!current_view_ || !current_view_->documentBufferView())
2494 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2495 docstring details = e.details_ + '\n';
2496 details += buf->emergencyWrite();
2497 theBufferList().release(buf);
2498 details += "\n" + _("The current document was closed.");
2499 Alert::error(e.title_, details);
2502 case WarningException:
2503 Alert::warning(e.title_, e.details_);
2507 catch (exception const & e) {
2508 docstring s = _("LyX has caught an exception, it will now "
2509 "attempt to save all unsaved documents and exit."
2511 s += from_ascii(e.what());
2512 Alert::error(_("Software exception Detected"), s);
2516 docstring s = _("LyX has caught some really weird exception, it will "
2517 "now attempt to save all unsaved documents and exit.");
2518 Alert::error(_("Software exception Detected"), s);
2526 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2528 QColor const & qcol = d->color_cache_.get(col);
2529 if (!qcol.isValid()) {
2535 rgbcol.r = qcol.red();
2536 rgbcol.g = qcol.green();
2537 rgbcol.b = qcol.blue();
2542 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2544 QColor const qcol(lcolor.getX11Name(col).c_str());
2545 if (!qcol.isValid()) {
2551 rgbcol.r = qcol.red();
2552 rgbcol.g = qcol.green();
2553 rgbcol.b = qcol.blue();
2558 string const GuiApplication::hexName(ColorCode col)
2560 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2564 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2566 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2567 d->socket_notifiers_[fd] = sn;
2568 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2572 void GuiApplication::socketDataReceived(int fd)
2574 d->socket_notifiers_[fd]->func_();
2578 void GuiApplication::unregisterSocketCallback(int fd)
2580 d->socket_notifiers_.take(fd)->setEnabled(false);
2584 void GuiApplication::commitData(QSessionManager & sm)
2586 /// The implementation is required to avoid an application exit
2587 /// when session state save is triggered by session manager.
2588 /// The default implementation sends a close event to all
2589 /// visible top level widgets when session managment allows
2591 /// We are changing that to close all wiew one by one.
2592 /// FIXME: verify if the default implementation is enough now.
2593 #ifdef QT_NO_SESSIONMANAGER
2595 #warning Qt is compiled without session manager
2597 #pragma message("warning: Qt is compiled without session manager")
2601 if (sm.allowsInteraction() && !closeAllViews())
2607 void GuiApplication::unregisterView(GuiView * gv)
2609 LAPPERR(d->views_[gv->id()] == gv);
2610 d->views_.remove(gv->id());
2611 if (current_view_ == gv)
2616 bool GuiApplication::closeAllViews()
2618 if (d->views_.empty())
2621 // When a view/window was closed before without quitting LyX, there
2622 // are already entries in the lastOpened list.
2623 theSession().lastOpened().clear();
2625 QList<GuiView *> const views = d->views_.values();
2626 foreach (GuiView * view, views) {
2627 if (!view->closeScheduled())
2636 GuiView & GuiApplication::view(int id) const
2638 LAPPERR(d->views_.contains(id));
2639 return *d->views_.value(id);
2643 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2645 QList<GuiView *> const views = d->views_.values();
2646 foreach (GuiView * view, views)
2647 view->hideDialog(name, inset);
2651 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2653 Buffer const * buffer_ = 0;
2654 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2655 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2656 if (Buffer const * ptr = (*it)->updateInset(inset))
2663 bool GuiApplication::searchMenu(FuncRequest const & func,
2664 docstring_list & names) const
2666 return d->menus_.searchMenu(func, names);
2670 // Ensure that a file is read only once (prevents include loops)
2671 static QStringList uifiles;
2672 // store which ui files define Toolbars
2673 static QStringList toolbar_uifiles;
2676 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2687 LexerKeyword uitags[] = {
2688 { "format", ui_format },
2689 { "include", ui_include },
2690 { "menuset", ui_menuset },
2691 { "toolbars", ui_toolbars },
2692 { "toolbarset", ui_toolbarset }
2696 lex.setFile(ui_path);
2698 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2702 if (lyxerr.debugging(Debug::PARSER))
2703 lex.printTable(lyxerr);
2706 // format before introduction of format tag
2707 unsigned int format = 0;
2708 while (lex.isOK()) {
2709 int const status = lex.lex();
2711 // we have to do this check here, outside the switch,
2712 // because otherwise we would start reading include files,
2713 // e.g., if the first tag we hit was an include tag.
2714 if (status == ui_format)
2716 format = lex.getInteger();
2720 // this will trigger unless the first tag we hit is a format
2721 // tag, with the right format.
2722 if (format != LFUN_FORMAT)
2723 return FormatMismatch;
2726 case Lexer::LEX_FEOF:
2731 QString const file = toqstr(lex.getString());
2732 bool const success = readUIFile(file, true);
2734 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2741 d->menus_.read(lex);
2745 d->toolbars_.readToolbars(lex);
2749 d->toolbars_.readToolbarSettings(lex);
2750 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2754 if (!rtrim(lex.getString()).empty())
2755 lex.printError("LyX::ReadUIFile: "
2756 "Unknown menu tag: `$$Token'");
2758 LYXERR0("Error with status: " << status);
2764 return (error ? ReadError : ReadOK);
2768 bool GuiApplication::readUIFile(QString const & name, bool include)
2770 LYXERR(Debug::INIT, "About to read " << name << "...");
2774 ui_path = libFileSearch("ui", name, "inc");
2775 if (ui_path.empty())
2776 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2778 ui_path = libFileSearch("ui", name, "ui");
2781 if (ui_path.empty()) {
2782 static const QString defaultUIFile = "default";
2783 LYXERR(Debug::INIT, "Could not find " << name);
2785 Alert::warning(_("Could not find UI definition file"),
2786 bformat(_("Error while reading the included file\n%1$s\n"
2787 "Please check your installation."), qstring_to_ucs4(name)));
2790 if (name == defaultUIFile) {
2791 LYXERR(Debug::INIT, "Could not find default UI file!!");
2792 Alert::warning(_("Could not find default UI file"),
2793 _("LyX could not find the default UI file!\n"
2794 "Please check your installation."));
2797 Alert::warning(_("Could not find UI definition file"),
2798 bformat(_("Error while reading the configuration file\n%1$s\n"
2799 "Falling back to default.\n"
2800 "Please look under Tools>Preferences>User Interface and\n"
2801 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2802 return readUIFile(defaultUIFile, false);
2805 QString const uifile = toqstr(ui_path.absFileName());
2806 if (uifiles.contains(uifile)) {
2808 // We are reading again the top uifile so reset the safeguard:
2811 d->toolbars_.reset();
2813 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2814 << "Is this an include loop?");
2818 uifiles.push_back(uifile);
2820 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2822 ReturnValues retval = readUIFile(ui_path);
2824 if (retval == FormatMismatch) {
2825 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2826 TempFile tmp("convertXXXXXX.ui");
2827 FileName const tempfile = tmp.name();
2828 bool const success = prefs2prefs(ui_path, tempfile, true);
2830 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2831 " to format " << LFUN_FORMAT << ".");
2833 retval = readUIFile(tempfile);
2837 if (retval != ReadOK) {
2838 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2846 settings.beginGroup("ui_files");
2847 bool touched = false;
2848 for (int i = 0; i != uifiles.size(); ++i) {
2849 QFileInfo fi(uifiles[i]);
2850 QDateTime const date_value = fi.lastModified();
2851 QString const name_key = QString::number(i);
2852 // if an ui file which defines Toolbars has changed,
2853 // we have to reset the settings
2854 if (toolbar_uifiles.contains(uifiles[i])
2855 && (!settings.contains(name_key)
2856 || settings.value(name_key).toString() != uifiles[i]
2857 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2859 settings.setValue(name_key, uifiles[i]);
2860 settings.setValue(name_key + "/date", date_value);
2863 settings.endGroup();
2865 settings.remove("views");
2871 void GuiApplication::onLastWindowClosed()
2873 if (d->global_menubar_)
2874 d->global_menubar_->grabKeyboard();
2878 void GuiApplication::startLongOperation() {
2879 d->key_checker_.start();
2883 bool GuiApplication::longOperationCancelled() {
2884 return d->key_checker_.pressed();
2888 void GuiApplication::stopLongOperation() {
2889 d->key_checker_.stop();
2893 bool GuiApplication::longOperationStarted() {
2894 return d->key_checker_.started();
2898 ////////////////////////////////////////////////////////////////////////
2900 // X11 specific stuff goes here...
2903 bool GuiApplication::x11EventFilter(XEvent * xev)
2908 switch (xev->type) {
2909 case SelectionRequest: {
2910 if (xev->xselectionrequest.selection != XA_PRIMARY)
2912 LYXERR(Debug::SELECTION, "X requested selection.");
2913 BufferView * bv = current_view_->currentBufferView();
2915 docstring const sel = bv->requestSelection();
2917 d->selection_.put(sel);
2921 case SelectionClear: {
2922 if (xev->xselectionclear.selection != XA_PRIMARY)
2924 LYXERR(Debug::SELECTION, "Lost selection.");
2925 BufferView * bv = current_view_->currentBufferView();
2927 bv->clearSelection();
2935 } // namespace frontend
2938 void hideDialogs(std::string const & name, Inset * inset)
2941 frontend::guiApp->hideDialogs(name, inset);
2945 ////////////////////////////////////////////////////////////////////
2949 ////////////////////////////////////////////////////////////////////
2951 frontend::FontLoader & theFontLoader()
2953 LAPPERR(frontend::guiApp);
2954 return frontend::guiApp->fontLoader();
2958 frontend::FontMetrics const & theFontMetrics(Font const & f)
2960 return theFontMetrics(f.fontInfo());
2964 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2966 LAPPERR(frontend::guiApp);
2967 return frontend::guiApp->fontLoader().metrics(f);
2971 ////////////////////////////////////////////////////////////////////
2975 ////////////////////////////////////////////////////////////////////
2977 frontend::Clipboard & theClipboard()
2979 LAPPERR(frontend::guiApp);
2980 return frontend::guiApp->clipboard();
2984 frontend::Selection & theSelection()
2986 LAPPERR(frontend::guiApp);
2987 return frontend::guiApp->selection();
2993 #include "moc_GuiApplication.cpp"