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"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
24 #include "qt_helpers.h"
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
33 #include "BufferList.h"
34 #include "BufferParams.h"
35 #include "BufferView.h"
38 #include "CutAndPaste.h"
39 #include "ErrorList.h"
41 #include "FuncRequest.h"
42 #include "FuncStatus.h"
43 #include "GuiWorkArea.h"
47 #include "LaTeXPackages.h"
50 #include "LyXAction.h"
52 #include "Paragraph.h"
55 #include "SpellChecker.h"
56 #include "Thesaurus.h"
59 #include "insets/InsetText.h"
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/ExceptionMessage.h"
64 #include "support/FileName.h"
65 #include "support/filetools.h"
66 #include "support/foreach.h"
67 #include "support/ForkedCalls.h"
68 #include "support/gettext.h"
69 #include "support/lassert.h"
70 #include "support/lstrings.h"
71 #include "support/lyxalgo.h" // sorted
72 #include "support/Messages.h"
73 #include "support/os.h"
74 #include "support/Package.h"
75 #include "support/PathChanger.h"
76 #include "support/Systemcall.h"
77 #include "support/TempFile.h"
80 #include "support/AppleScript.h"
81 #include "support/linkback/LinkBackProxy.h"
89 #include <QDesktopWidget>
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 double GuiApplication::pixelRatio() const
1043 #if QT_VERSION > 0x050000
1044 return devicePixelRatio();
1051 void GuiApplication::clearSession()
1058 docstring Application::iconName(FuncRequest const & f, bool unknown)
1060 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1064 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1068 BufferView * bv = 0;
1069 BufferView * doc_bv = 0;
1071 if (cmd.action() == LFUN_NOACTION) {
1072 status.message(from_utf8(N_("Nothing to do")));
1073 status.setEnabled(false);
1076 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1077 status.setUnknown(true);
1078 status.message(from_utf8(N_("Unknown action")));
1079 status.setEnabled(false);
1082 // Does the GuiApplication know something?
1083 else if (getStatus(cmd, status)) { }
1085 // If we do not have a GuiView, then other functions are disabled
1086 else if (!current_view_)
1087 status.setEnabled(false);
1089 // Does the GuiView know something?
1090 else if (current_view_->getStatus(cmd, status)) { }
1092 // In LyX/Mac, when a dialog is open, the menus of the
1093 // application can still be accessed without giving focus to
1094 // the main window. In this case, we want to disable the menu
1095 // entries that are buffer or view-related.
1096 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1098 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1099 status.setEnabled(false);
1102 // If we do not have a BufferView, then other functions are disabled
1103 else if (!(bv = current_view_->currentBufferView()))
1104 status.setEnabled(false);
1106 // Does the current BufferView know something?
1107 else if (bv->getStatus(cmd, status)) { }
1109 // Does the current Buffer know something?
1110 else if (bv->buffer().getStatus(cmd, status)) { }
1112 // If we do not have a document BufferView, different from the
1113 // current BufferView, then other functions are disabled
1114 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1115 status.setEnabled(false);
1117 // Does the document Buffer know something?
1118 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1121 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1122 status.message(from_utf8(N_("Command not handled")));
1123 status.setEnabled(false);
1126 // the default error message if we disable the command
1127 if (!status.enabled() && status.message().empty())
1128 status.message(from_utf8(N_("Command disabled")));
1134 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1136 // I would really like to avoid having this switch and rather try to
1137 // encode this in the function itself.
1138 // -- And I'd rather let an inset decide which LFUNs it is willing
1139 // to handle (Andre')
1141 switch (cmd.action()) {
1143 // This could be used for the no-GUI version. The GUI version is handled in
1144 // GuiView::getStatus(). See above.
1146 case LFUN_BUFFER_WRITE:
1147 case LFUN_BUFFER_WRITE_AS: {
1148 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1149 enable = b && (b->isUnnamed() || !b->isClean());
1154 case LFUN_BOOKMARK_GOTO: {
1155 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1156 enable = theSession().bookmarks().isValid(num);
1160 case LFUN_BOOKMARK_CLEAR:
1161 enable = theSession().bookmarks().hasValid();
1164 // this one is difficult to get right. As a half-baked
1165 // solution, we consider only the first action of the sequence
1166 case LFUN_COMMAND_SEQUENCE: {
1167 // argument contains ';'-terminated commands
1168 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1169 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1170 func.setOrigin(cmd.origin());
1171 flag = getStatus(func);
1175 // we want to check if at least one of these is enabled
1176 case LFUN_COMMAND_ALTERNATIVES: {
1177 // argument contains ';'-terminated commands
1178 string arg = to_utf8(cmd.argument());
1179 while (!arg.empty()) {
1181 arg = split(arg, first, ';');
1182 FuncRequest func(lyxaction.lookupFunc(first));
1183 func.setOrigin(cmd.origin());
1184 flag = getStatus(func);
1185 // if this one is enabled, the whole thing is
1194 string name = to_utf8(cmd.argument());
1195 if (theTopLevelCmdDef().lock(name, func)) {
1196 func.setOrigin(cmd.origin());
1197 flag = getStatus(func);
1198 theTopLevelCmdDef().release(name);
1200 // catch recursion or unknown command
1201 // definition. all operations until the
1202 // recursion or unknown command definition
1203 // occurs are performed, so set the state to
1210 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1212 case LFUN_PREFERENCES_SAVE:
1213 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1214 case LFUN_DEBUG_LEVEL_SET:
1215 // these are handled in our dispatch()
1218 case LFUN_WINDOW_CLOSE:
1219 enable = d->views_.size() > 0;
1222 case LFUN_BUFFER_NEW:
1223 case LFUN_BUFFER_NEW_TEMPLATE:
1224 case LFUN_FILE_OPEN:
1225 case LFUN_HELP_OPEN:
1226 case LFUN_SCREEN_FONT_UPDATE:
1227 case LFUN_SET_COLOR:
1228 case LFUN_WINDOW_NEW:
1230 case LFUN_LYXRC_APPLY:
1231 case LFUN_COMMAND_PREFIX:
1233 case LFUN_META_PREFIX:
1234 case LFUN_RECONFIGURE:
1235 case LFUN_SERVER_GET_FILENAME:
1236 case LFUN_SERVER_NOTIFY:
1240 case LFUN_BUFFER_FORALL: {
1241 if (theBufferList().empty()) {
1242 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1243 flag.setEnabled(false);
1247 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1248 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1249 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1250 flag.setEnabled(false);
1255 case LFUN_DIALOG_SHOW: {
1256 string const name = cmd.getArg(0);
1257 return name == "aboutlyx"
1259 || name == "texinfo"
1260 || name == "progress"
1261 || name == "compare";
1269 flag.setEnabled(false);
1273 /// make a post-dispatch status message
1274 static docstring makeDispatchMessage(docstring const & msg,
1275 FuncRequest const & cmd)
1277 const bool verbose = (cmd.origin() == FuncRequest::MENU
1278 || cmd.origin() == FuncRequest::TOOLBAR
1279 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1281 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1282 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1286 docstring dispatch_msg = msg;
1287 if (!dispatch_msg.empty())
1288 dispatch_msg += ' ';
1290 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1292 bool argsadded = false;
1294 if (!cmd.argument().empty()) {
1295 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1296 comname += ' ' + cmd.argument();
1300 docstring const shortcuts = theTopLevelKeymap().
1301 printBindings(cmd, KeySequence::ForGui);
1303 if (!shortcuts.empty())
1304 comname += ": " + shortcuts;
1305 else if (!argsadded && !cmd.argument().empty())
1306 comname += ' ' + cmd.argument();
1308 if (!comname.empty()) {
1309 comname = rtrim(comname);
1310 dispatch_msg += '(' + rtrim(comname) + ')';
1312 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1313 return dispatch_msg;
1317 void GuiApplication::dispatch(FuncRequest const & cmd)
1319 Buffer * buffer = 0;
1320 if (current_view_ && current_view_->currentBufferView()) {
1321 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1322 buffer = ¤t_view_->currentBufferView()->buffer();
1324 buffer->undo().beginUndoGroup();
1328 // redraw the screen at the end (first of the two drawing steps).
1329 // This is done unless explicitly requested otherwise
1330 dr.screenUpdate(Update::FitCursor);
1332 updateCurrentView(cmd, dr);
1334 // the buffer may have been closed by one action
1335 if (theBufferList().isLoaded(buffer))
1336 buffer->undo().endUndoGroup();
1340 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1345 BufferView * bv = current_view_->currentBufferView();
1347 if (dr.needBufferUpdate()) {
1348 bv->cursor().clearBufferUpdate();
1349 bv->buffer().updateBuffer();
1351 // BufferView::update() updates the ViewMetricsInfo and
1352 // also initializes the position cache for all insets in
1353 // (at least partially) visible top-level paragraphs.
1354 // We will redraw the screen only if needed.
1355 bv->processUpdateFlags(dr.screenUpdate());
1357 // Do we have a selection?
1358 theSelection().haveSelection(bv->cursor().selection());
1361 current_view_->restartCursor();
1363 if (dr.needMessageUpdate()) {
1364 // Some messages may already be translated, so we cannot use _()
1365 current_view_->message(makeDispatchMessage(
1366 translateIfPossible(dr.message()), cmd));
1371 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1372 bool switchToBuffer)
1374 if (!theSession().bookmarks().isValid(idx))
1376 BookmarksSection::Bookmark const & bm =
1377 theSession().bookmarks().bookmark(idx);
1378 LASSERT(!bm.filename.empty(), return);
1379 string const file = bm.filename.absFileName();
1380 // if the file is not opened, open it.
1381 if (!theBufferList().exists(bm.filename)) {
1383 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1387 // open may fail, so we need to test it again
1388 if (!theBufferList().exists(bm.filename))
1391 // bm can be changed when saving
1392 BookmarksSection::Bookmark tmp = bm;
1394 // Special case idx == 0 used for back-from-back jump navigation
1396 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1398 // if the current buffer is not that one, switch to it.
1399 BufferView * doc_bv = current_view_ ?
1400 current_view_->documentBufferView() : 0;
1401 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1402 if (switchToBuffer) {
1403 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1406 doc_bv = current_view_->documentBufferView();
1411 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1412 if (!doc_bv->moveToPosition(
1413 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1420 // Cursor jump succeeded!
1421 Cursor const & cur = doc_bv->cursor();
1422 pit_type new_pit = cur.pit();
1423 pos_type new_pos = cur.pos();
1424 int new_id = cur.paragraph().id();
1426 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1427 // see http://www.lyx.org/trac/ticket/3092
1428 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1429 || bm.top_id != new_id) {
1430 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1431 new_pit, new_pos, new_id);
1435 // This function runs "configure" and then rereads lyx.defaults to
1436 // reconfigure the automatic settings.
1437 void GuiApplication::reconfigure(string const & option)
1439 // emit message signal.
1441 current_view_->message(_("Running configure..."));
1443 // Run configure in user lyx directory
1444 PathChanger p(package().user_support());
1445 string configure_command = package().configure_command();
1446 configure_command += option;
1448 int const ret = one.startscript(Systemcall::Wait, configure_command);
1450 // emit message signal.
1452 current_view_->message(_("Reloading configuration..."));
1453 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1454 // Re-read packages.lst
1455 LaTeXPackages::getAvailable();
1458 Alert::information(_("System reconfiguration failed"),
1459 _("The system reconfiguration has failed.\n"
1460 "Default textclass is used but LyX may\n"
1461 "not be able to work properly.\n"
1462 "Please reconfigure again if needed."));
1464 Alert::information(_("System reconfigured"),
1465 _("The system has been reconfigured.\n"
1466 "You need to restart LyX to make use of any\n"
1467 "updated document class specifications."));
1470 void GuiApplication::validateCurrentView()
1472 if (!d->views_.empty() && !current_view_) {
1473 // currently at least one view exists but no view has the focus.
1474 // choose the last view to make it current.
1475 // a view without any open document is preferred.
1476 GuiView * candidate = 0;
1477 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1478 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1479 for (; it != end; ++it) {
1481 if (!candidate->documentBufferView())
1484 setCurrentView(candidate);
1488 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1490 string const argument = to_utf8(cmd.argument());
1491 FuncCode const action = cmd.action();
1493 LYXERR(Debug::ACTION, "cmd: " << cmd);
1495 // we have not done anything wrong yet.
1498 FuncStatus const flag = getStatus(cmd);
1499 if (!flag.enabled()) {
1500 // We cannot use this function here
1501 LYXERR(Debug::ACTION, "action "
1502 << lyxaction.getActionName(action)
1503 << " [" << action << "] is disabled at this location");
1504 dr.setMessage(flag.message());
1506 dr.dispatched(false);
1507 dr.screenUpdate(Update::None);
1508 dr.clearBufferUpdate();
1512 if (cmd.origin() == FuncRequest::LYXSERVER) {
1513 if (current_view_ && current_view_->currentBufferView())
1514 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1515 // we will also need to redraw the screen at the end
1516 dr.screenUpdate(Update::FitCursor);
1519 // Assumes that the action will be dispatched.
1520 dr.dispatched(true);
1522 switch (cmd.action()) {
1524 case LFUN_WINDOW_NEW:
1525 createView(toqstr(cmd.argument()));
1528 case LFUN_WINDOW_CLOSE:
1529 // update bookmark pit of the current buffer before window close
1530 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1531 gotoBookmark(i+1, false, false);
1532 // clear the last opened list, because
1533 // maybe this will end the session
1534 theSession().lastOpened().clear();
1535 // check for valid current_view_
1536 validateCurrentView();
1538 current_view_->closeScheduled();
1542 // quitting is triggered by the gui code
1543 // (leaving the event loop).
1545 current_view_->message(from_utf8(N_("Exiting.")));
1546 if (closeAllViews())
1550 case LFUN_SCREEN_FONT_UPDATE: {
1551 // handle the screen font changes.
1552 d->font_loader_.update();
1553 // Backup current_view_
1554 GuiView * view = current_view_;
1555 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1556 // to skip the refresh.
1558 theBufferList().changed(false);
1559 // Restore current_view_
1560 current_view_ = view;
1564 case LFUN_BUFFER_NEW:
1565 validateCurrentView();
1566 if (d->views_.empty()
1567 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1568 createView(QString(), false); // keep hidden
1569 current_view_->newDocument(to_utf8(cmd.argument()), false);
1570 current_view_->show();
1571 setActiveWindow(current_view_);
1573 current_view_->newDocument(to_utf8(cmd.argument()), false);
1577 case LFUN_BUFFER_NEW_TEMPLATE:
1578 validateCurrentView();
1579 if (d->views_.empty()
1580 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1582 current_view_->newDocument(to_utf8(cmd.argument()), true);
1583 if (!current_view_->documentBufferView())
1584 current_view_->close();
1586 current_view_->newDocument(to_utf8(cmd.argument()), true);
1590 case LFUN_FILE_OPEN: {
1591 validateCurrentView();
1592 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1593 string const fname = to_utf8(cmd.argument());
1594 bool const is_open = FileName::isAbsolute(fname)
1595 && theBufferList().getBuffer(FileName(fname));
1596 if (d->views_.empty()
1597 || (!lyxrc.open_buffers_in_tabs
1598 && current_view_->documentBufferView() != 0
1600 // We want the ui session to be saved per document and not per
1601 // window number. The filename crc is a good enough identifier.
1602 boost::crc_32_type crc;
1603 crc = for_each(fname.begin(), fname.end(), crc);
1604 createView(crc.checksum());
1605 current_view_->openDocument(fname);
1606 if (current_view_ && !current_view_->documentBufferView())
1607 current_view_->close();
1609 current_view_->openDocument(fname);
1613 case LFUN_HELP_OPEN: {
1614 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1615 if (current_view_ == 0)
1617 string const arg = to_utf8(cmd.argument());
1619 current_view_->message(_("Missing argument"));
1622 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1624 fname = i18nLibFileSearch("examples", arg, "lyx");
1626 if (fname.empty()) {
1627 lyxerr << "LyX: unable to find documentation file `"
1628 << arg << "'. Bad installation?" << endl;
1631 current_view_->message(bformat(_("Opening help file %1$s..."),
1632 makeDisplayPath(fname.absFileName())));
1633 Buffer * buf = current_view_->loadDocument(fname, false);
1635 #ifndef DEVEL_VERSION
1637 buf->setReadonly(true);
1644 case LFUN_SET_COLOR: {
1646 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1647 if (lyx_name.empty() || x11_name.empty()) {
1649 current_view_->message(
1650 _("Syntax: set-color <lyx_name> <x11_name>"));
1655 // FIXME: The graphics cache no longer has a changeDisplay method.
1656 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1657 bool const graphicsbg_changed =
1658 lyx_name == graphicsbg && x11_name != graphicsbg;
1659 if (graphicsbg_changed)
1660 graphics::GCache::get().changeDisplay(true);
1663 if (!lcolor.setColor(lyx_name, x11_name)) {
1665 current_view_->message(
1666 bformat(_("Set-color \"%1$s\" failed "
1667 "- color is undefined or "
1668 "may not be redefined"),
1669 from_utf8(lyx_name)));
1672 // Make sure we don't keep old colors in cache.
1673 d->color_cache_.clear();
1677 case LFUN_LYXRC_APPLY: {
1678 // reset active key sequences, since the bindings
1679 // are updated (bug 6064)
1681 LyXRC const lyxrc_orig = lyxrc;
1683 istringstream ss(to_utf8(cmd.argument()));
1684 bool const success = lyxrc.read(ss);
1687 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1688 << "Unable to read lyxrc data"
1693 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1695 // If the request comes from the minibuffer, then we can't reset
1696 // the GUI, since that would destory the minibuffer itself and
1697 // cause a crash, since we are currently in one of the methods of
1698 // GuiCommandBuffer. See bug #8540.
1699 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1702 // FIXME Unfortunately, that leaves a bug here, since we cannot
1703 // reset the GUI in this case. If the changes to lyxrc affected the
1704 // UI, then, nothing would happen. This seems fairly unlikely, but
1705 // it definitely is a bug.
1710 case LFUN_COMMAND_PREFIX:
1711 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1716 d->meta_fake_bit = NoModifier;
1717 GuiView * gv = currentView();
1718 if (gv && gv->currentBufferView())
1719 // cancel any selection
1720 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1721 dr.setMessage(from_ascii(N_("Cancel")));
1724 case LFUN_META_PREFIX:
1725 d->meta_fake_bit = AltModifier;
1726 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1729 // --- Menus -----------------------------------------------
1730 case LFUN_RECONFIGURE:
1731 // argument is any additional parameter to the configure.py command
1732 reconfigure(to_utf8(cmd.argument()));
1735 // --- lyxserver commands ----------------------------
1736 case LFUN_SERVER_GET_FILENAME: {
1737 if (current_view_ && current_view_->documentBufferView()) {
1738 docstring const fname = from_utf8(
1739 current_view_->documentBufferView()->buffer().absFileName());
1740 dr.setMessage(fname);
1741 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1743 dr.setMessage(docstring());
1744 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1749 case LFUN_SERVER_NOTIFY: {
1750 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1751 dr.setMessage(dispatch_buffer);
1752 theServer().notifyClient(to_utf8(dispatch_buffer));
1756 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1757 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1763 string rest = split(argument, countstr, ' ');
1764 istringstream is(countstr);
1767 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1768 for (int i = 0; i < count; ++i)
1769 dispatch(lyxaction.lookupFunc(rest));
1773 case LFUN_COMMAND_SEQUENCE: {
1774 // argument contains ';'-terminated commands
1775 string arg = argument;
1776 // FIXME: this LFUN should also work without any view.
1777 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1778 ? &(current_view_->documentBufferView()->buffer()) : 0;
1780 buffer->undo().beginUndoGroup();
1781 while (!arg.empty()) {
1783 arg = split(arg, first, ';');
1784 FuncRequest func(lyxaction.lookupFunc(first));
1785 func.setOrigin(cmd.origin());
1788 // the buffer may have been closed by one action
1789 if (theBufferList().isLoaded(buffer))
1790 buffer->undo().endUndoGroup();
1794 case LFUN_BUFFER_FORALL: {
1795 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1797 map<Buffer *, GuiView *> views_lVisible;
1798 map<GuiView *, Buffer *> activeBuffers;
1800 QList<GuiView *> allViews = d->views_.values();
1802 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1803 // and on which buffer is active in each view.
1804 Buffer * const last = theBufferList().last();
1805 foreach (GuiView * view, allViews) {
1806 // all of the buffers might be locally hidden. That is, there is no active buffer.
1807 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1808 activeBuffers[view] = 0;
1810 activeBuffers[view] = &view->currentBufferView()->buffer();
1812 // find out if each is locally visible or locally hidden.
1813 // we don't use a for loop as the buffer list cycles.
1814 Buffer * b = theBufferList().first();
1816 bool const locallyVisible = view && view->workArea(*b);
1817 if (locallyVisible) {
1818 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1819 // only need to overwrite/add if we don't already know a buffer is globally
1820 // visible or we do know but we would prefer to dispatch LFUN from the
1821 // current view because of cursor position issues.
1822 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1823 views_lVisible[b] = view;
1827 b = theBufferList().next(b);
1831 GuiView * const homeView = currentView();
1832 Buffer * b = theBufferList().first();
1833 Buffer * nextBuf = 0;
1834 int numProcessed = 0;
1837 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1839 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1841 // first change to a view where b is locally visible, preferably current_view_.
1842 GuiView * const vLv = views_lVisible[b];
1844 lyx::dispatch(funcToRun);
1852 // put things back to how they were (if possible).
1853 foreach (GuiView * view, allViews) {
1854 Buffer * originalBuf = activeBuffers[view];
1855 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1856 if (theBufferList().isLoaded(originalBuf))
1857 view->setBuffer(originalBuf);
1859 homeView->setFocus();
1861 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1865 case LFUN_COMMAND_ALTERNATIVES: {
1866 // argument contains ';'-terminated commands
1867 string arg = argument;
1868 while (!arg.empty()) {
1870 arg = split(arg, first, ';');
1871 FuncRequest func(lyxaction.lookupFunc(first));
1872 func.setOrigin(cmd.origin());
1873 FuncStatus const stat = getStatus(func);
1874 if (stat.enabled()) {
1884 if (theTopLevelCmdDef().lock(argument, func)) {
1885 func.setOrigin(cmd.origin());
1887 theTopLevelCmdDef().release(argument);
1889 if (func.action() == LFUN_UNKNOWN_ACTION) {
1890 // unknown command definition
1891 lyxerr << "Warning: unknown command definition `"
1895 // recursion detected
1896 lyxerr << "Warning: Recursion in the command definition `"
1897 << argument << "' detected"
1904 case LFUN_PREFERENCES_SAVE:
1905 lyxrc.write(support::makeAbsPath("preferences",
1906 package().user_support().absFileName()), false);
1909 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1910 string const fname = addName(addPath(package().user_support().absFileName(),
1911 "templates/"), "defaults.lyx");
1912 Buffer defaults(fname);
1914 istringstream ss(argument);
1919 // We need to make sure that, after we recreat the DocumentClass,
1920 // which we do in readHeader, we apply it to the document itself.
1921 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1922 int const unknown_tokens = defaults.readHeader(lex);
1923 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1925 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1926 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1928 if (unknown_tokens != 0) {
1929 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1930 << unknown_tokens << " unknown token"
1931 << (unknown_tokens == 1 ? "" : "s")
1935 if (defaults.writeFile(FileName(defaults.absFileName())))
1936 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1937 makeDisplayPath(fname)));
1940 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1945 case LFUN_BOOKMARK_GOTO:
1946 // go to bookmark, open unopened file and switch to buffer if necessary
1947 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1948 dr.screenUpdate(Update::Force | Update::FitCursor);
1951 case LFUN_BOOKMARK_CLEAR:
1952 theSession().bookmarks().clear();
1955 case LFUN_DEBUG_LEVEL_SET:
1956 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1959 case LFUN_DIALOG_SHOW: {
1960 string const name = cmd.getArg(0);
1962 if ( name == "aboutlyx"
1964 || name == "texinfo"
1965 || name == "progress"
1966 || name == "compare")
1968 // work around: on Mac OS the application
1969 // is not terminated when closing the last view.
1970 // Create a new one to be able to dispatch the
1971 // LFUN_DIALOG_SHOW to this view.
1972 if (current_view_ == 0)
1978 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1981 current_view_->dispatch(cmd, dr);
1985 if (cmd.origin() == FuncRequest::LYXSERVER)
1986 updateCurrentView(cmd, dr);
1990 docstring GuiApplication::viewStatusMessage()
1992 // When meta-fake key is pressed, show the key sequence so far + "M-".
1993 if (d->meta_fake_bit != NoModifier)
1994 return d->keyseq.print(KeySequence::ForGui) + "M-";
1996 // Else, when a non-complete key sequence is pressed,
1997 // show the available options.
1998 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1999 return d->keyseq.printOptions(true);
2005 void GuiApplication::handleKeyFunc(FuncCode action)
2009 if (d->keyseq.length())
2011 GuiView * gv = currentView();
2012 LASSERT(gv && gv->currentBufferView(), return);
2013 BufferView * bv = gv->currentBufferView();
2014 bv->getIntl().getTransManager().deadkey(
2015 c, get_accent(action).accent, bv->cursor().innerText(),
2017 // Need to clear, in case the minibuffer calls these
2020 // copied verbatim from do_accent_char
2021 bv->cursor().resetAnchor();
2025 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2027 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2029 // Do nothing if we have nothing (JMarc)
2030 if (!keysym.isOK()) {
2031 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2033 current_view_->restartCursor();
2037 if (keysym.isModifier()) {
2039 current_view_->restartCursor();
2043 char_type encoded_last_key = keysym.getUCSEncoded();
2045 // Do a one-deep top-level lookup for
2046 // cancel and meta-fake keys. RVDK_PATCH_5
2047 d->cancel_meta_seq.reset();
2049 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2050 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2052 // When not cancel or meta-fake, do the normal lookup.
2053 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2054 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2055 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2056 // remove Caps Lock and Mod2 as a modifiers
2057 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2058 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2061 // Dont remove this unless you know what you are doing.
2062 d->meta_fake_bit = NoModifier;
2064 // Can this happen now ?
2065 if (func.action() == LFUN_NOACTION)
2066 func = FuncRequest(LFUN_COMMAND_PREFIX);
2068 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2069 << d->keyseq.print(KeySequence::Portable) << ']');
2071 // already here we know if it any point in going further
2072 // why not return already here if action == -1 and
2073 // num_bytes == 0? (Lgb)
2075 if (d->keyseq.length() > 1 && current_view_)
2076 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2079 // Maybe user can only reach the key via holding down shift.
2080 // Let's see. But only if shift is the only modifier
2081 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2082 LYXERR(Debug::KEY, "Trying without shift");
2083 func = d->keyseq.addkey(keysym, NoModifier);
2084 LYXERR(Debug::KEY, "Action now " << func.action());
2087 if (func.action() == LFUN_UNKNOWN_ACTION) {
2088 // Hmm, we didn't match any of the keysequences. See
2089 // if it's normal insertable text not already covered
2091 if (keysym.isText() && d->keyseq.length() == 1) {
2092 LYXERR(Debug::KEY, "isText() is true, inserting.");
2093 func = FuncRequest(LFUN_SELF_INSERT,
2094 FuncRequest::KEYBOARD);
2096 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2097 if (current_view_) {
2098 current_view_->message(_("Unknown function."));
2099 current_view_->restartCursor();
2105 if (func.action() == LFUN_SELF_INSERT) {
2106 if (encoded_last_key != 0) {
2107 docstring const arg(1, encoded_last_key);
2108 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2109 FuncRequest::KEYBOARD));
2110 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2113 processFuncRequest(func);
2117 void GuiApplication::processFuncRequest(FuncRequest const & func)
2119 lyx::dispatch(func);
2123 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2125 addToFuncRequestQueue(func);
2126 processFuncRequestQueueAsync();
2130 void GuiApplication::processFuncRequestQueue()
2132 while (!d->func_request_queue_.empty()) {
2133 processFuncRequest(d->func_request_queue_.front());
2134 d->func_request_queue_.pop();
2139 void GuiApplication::processFuncRequestQueueAsync()
2141 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2145 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2147 d->func_request_queue_.push(func);
2151 void GuiApplication::resetGui()
2153 // Set the language defined by the user.
2157 if (!readUIFile(toqstr(lyxrc.ui_file)))
2158 // Gives some error box here.
2161 if (d->global_menubar_)
2162 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2164 QHash<int, GuiView *>::iterator it;
2165 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2168 gv->setLayoutDirection(layoutDirection());
2172 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2176 void GuiApplication::createView(int view_id)
2178 createView(QString(), true, view_id);
2182 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2185 // release the keyboard which might have been grabed by the global
2186 // menubar on Mac to catch shortcuts even without any GuiView.
2187 if (d->global_menubar_)
2188 d->global_menubar_->releaseKeyboard();
2192 while (d->views_.find(id) != d->views_.end())
2195 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2196 GuiView * view = new GuiView(id);
2198 d->views_[id] = view;
2202 setActiveWindow(view);
2205 if (!geometry_arg.isEmpty()) {
2206 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2210 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2211 re.indexIn(geometry_arg);
2212 w = re.cap(1).toInt();
2213 h = re.cap(2).toInt();
2214 x = re.cap(3).toInt();
2215 y = re.cap(4).toInt();
2216 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2217 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2218 // Set initial geometry such that we can get the frame size.
2219 view->setGeometry(x, y, w, h);
2220 int framewidth = view->geometry().x() - view->x();
2221 int titleheight = view->geometry().y() - view->y();
2222 // Negative displacements must be interpreted as distances
2223 // from the right or bottom screen borders.
2224 if (sx == '-' || sy == '-') {
2225 QRect rec = QApplication::desktop()->screenGeometry();
2227 x += rec.width() - w - framewidth;
2229 y += rec.height() - h - titleheight;
2230 view->setGeometry(x, y, w, h);
2232 // Make sure that the left and top frame borders are visible.
2233 if (view->x() < 0 || view->y() < 0) {
2238 view->setGeometry(x, y, w, h);
2246 Clipboard & GuiApplication::clipboard()
2248 return d->clipboard_;
2252 Selection & GuiApplication::selection()
2254 return d->selection_;
2258 FontLoader & GuiApplication::fontLoader()
2260 return d->font_loader_;
2264 Toolbars const & GuiApplication::toolbars() const
2266 return d->toolbars_;
2270 Toolbars & GuiApplication::toolbars()
2272 return d->toolbars_;
2276 Menus const & GuiApplication::menus() const
2282 Menus & GuiApplication::menus()
2288 QList<int> GuiApplication::viewIds() const
2290 return d->views_.keys();
2294 ColorCache & GuiApplication::colorCache()
2296 return d->color_cache_;
2300 int GuiApplication::exec()
2302 // asynchronously handle batch commands. This event will be in
2303 // the event queue in front of other asynchronous events. Hence,
2304 // we can assume in the latter that the gui is setup already.
2305 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2307 return QApplication::exec();
2311 void GuiApplication::exit(int status)
2313 QApplication::exit(status);
2317 void GuiApplication::setGuiLanguage()
2321 // install translation file for Qt built-in dialogs
2322 QString const language_name = QString("qt_") + theLocale.name();
2323 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2324 // Short-named translator can be loaded from a long name, but not the
2325 // opposite. Therefore, long name should be used without truncation.
2326 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2327 if (!d->qt_trans_.load(language_name,
2328 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2329 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2332 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2336 switch (theLocale.language()) {
2337 case QLocale::Arabic :
2338 case QLocale::Hebrew :
2339 case QLocale::Persian :
2340 case QLocale::Urdu :
2341 setLayoutDirection(Qt::RightToLeft);
2344 setLayoutDirection(Qt::LeftToRight);
2349 void GuiApplication::execBatchCommands()
2354 if (!readUIFile(toqstr(lyxrc.ui_file)))
2355 // Gives some error box here.
2359 #if QT_VERSION > 0x040600
2360 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2362 // Create the global default menubar which is shown for the dialogs
2363 // and if no GuiView is visible.
2364 // This must be done after the session was recovered to know the "last files".
2365 d->global_menubar_ = new QMenuBar(0);
2366 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2369 lyx::execBatchCommands();
2373 QAbstractItemModel * GuiApplication::languageModel()
2375 if (d->language_model_)
2376 return d->language_model_;
2378 QStandardItemModel * lang_model = new QStandardItemModel(this);
2379 lang_model->insertColumns(0, 3);
2381 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2382 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2383 Languages::const_iterator it = lyx::languages.begin();
2384 Languages::const_iterator end = lyx::languages.end();
2385 for (; it != end; ++it) {
2386 current_row = lang_model->rowCount();
2387 lang_model->insertRows(current_row, 1);
2388 QModelIndex pl_item = lang_model->index(current_row, 0);
2389 QModelIndex sp_item = lang_model->index(current_row, 1);
2390 QModelIndex th_item = lang_model->index(current_row, 2);
2391 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2392 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2393 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2394 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2395 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2396 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2397 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2398 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2399 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2400 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2402 d->language_model_ = new QSortFilterProxyModel(this);
2403 d->language_model_->setSourceModel(lang_model);
2404 d->language_model_->setSortLocaleAware(true);
2405 return d->language_model_;
2409 void GuiApplication::restoreGuiSession()
2411 if (!lyxrc.load_session)
2414 Session & session = theSession();
2415 LastOpenedSection::LastOpened const & lastopened =
2416 session.lastOpened().getfiles();
2418 validateCurrentView();
2420 FileName active_file;
2421 // do not add to the lastfile list since these files are restored from
2422 // last session, and should be already there (regular files), or should
2423 // not be added at all (help files).
2424 for (size_t i = 0; i < lastopened.size(); ++i) {
2425 FileName const & file_name = lastopened[i].file_name;
2426 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2427 && current_view_->documentBufferView() != 0)) {
2428 boost::crc_32_type crc;
2429 string const & fname = file_name.absFileName();
2430 crc = for_each(fname.begin(), fname.end(), crc);
2431 createView(crc.checksum());
2433 current_view_->loadDocument(file_name, false);
2435 if (lastopened[i].active)
2436 active_file = file_name;
2439 // Restore last active buffer
2440 Buffer * buffer = theBufferList().getBuffer(active_file);
2441 if (buffer && current_view_)
2442 current_view_->setBuffer(buffer);
2444 // clear this list to save a few bytes of RAM
2445 session.lastOpened().clear();
2449 QString const GuiApplication::romanFontName()
2452 font.setStyleHint(QFont::Serif);
2453 font.setFamily("serif");
2455 return QFontInfo(font).family();
2459 QString const GuiApplication::sansFontName()
2462 font.setStyleHint(QFont::SansSerif);
2463 font.setFamily("sans");
2465 return QFontInfo(font).family();
2469 QString const GuiApplication::typewriterFontName()
2472 font.setStyleHint(QFont::TypeWriter);
2473 font.setFamily("monospace");
2475 return QFontInfo(font).family();
2479 void GuiApplication::handleRegularEvents()
2481 ForkedCallsController::handleCompletedProcesses();
2485 bool GuiApplication::event(QEvent * e)
2488 case QEvent::FileOpen: {
2489 // Open a file; this happens only on Mac OS X for now.
2491 // We do this asynchronously because on startup the batch
2492 // commands are not executed here yet and the gui is not ready
2494 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2495 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2496 processFuncRequestAsync(fr);
2501 return QApplication::event(e);
2506 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2509 return QApplication::notify(receiver, event);
2511 catch (ExceptionMessage const & e) {
2513 case ErrorException:
2515 setQuitOnLastWindowClosed(false);
2517 Alert::error(e.title_, e.details_);
2519 // Properly crash in debug mode in order to get a useful backtrace.
2522 // In release mode, try to exit gracefully.
2525 case BufferException: {
2526 if (!current_view_ || !current_view_->documentBufferView())
2528 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2529 docstring details = e.details_ + '\n';
2530 details += buf->emergencyWrite();
2531 theBufferList().release(buf);
2532 details += "\n" + _("The current document was closed.");
2533 Alert::error(e.title_, details);
2536 case WarningException:
2537 Alert::warning(e.title_, e.details_);
2541 catch (exception const & e) {
2542 docstring s = _("LyX has caught an exception, it will now "
2543 "attempt to save all unsaved documents and exit."
2545 s += from_ascii(e.what());
2546 Alert::error(_("Software exception Detected"), s);
2550 docstring s = _("LyX has caught some really weird exception, it will "
2551 "now attempt to save all unsaved documents and exit.");
2552 Alert::error(_("Software exception Detected"), s);
2560 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2562 QColor const & qcol = d->color_cache_.get(col);
2563 if (!qcol.isValid()) {
2569 rgbcol.r = qcol.red();
2570 rgbcol.g = qcol.green();
2571 rgbcol.b = qcol.blue();
2576 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2578 QColor const qcol(lcolor.getX11Name(col).c_str());
2579 if (!qcol.isValid()) {
2585 rgbcol.r = qcol.red();
2586 rgbcol.g = qcol.green();
2587 rgbcol.b = qcol.blue();
2592 string const GuiApplication::hexName(ColorCode col)
2594 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2598 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2600 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2601 d->socket_notifiers_[fd] = sn;
2602 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2606 void GuiApplication::socketDataReceived(int fd)
2608 d->socket_notifiers_[fd]->func_();
2612 void GuiApplication::unregisterSocketCallback(int fd)
2614 d->socket_notifiers_.take(fd)->setEnabled(false);
2618 void GuiApplication::commitData(QSessionManager & sm)
2620 /// The implementation is required to avoid an application exit
2621 /// when session state save is triggered by session manager.
2622 /// The default implementation sends a close event to all
2623 /// visible top level widgets when session managment allows
2625 /// We are changing that to close all wiew one by one.
2626 /// FIXME: verify if the default implementation is enough now.
2627 #ifdef QT_NO_SESSIONMANAGER
2629 #warning Qt is compiled without session manager
2631 #pragma message("warning: Qt is compiled without session manager")
2635 if (sm.allowsInteraction() && !closeAllViews())
2641 void GuiApplication::unregisterView(GuiView * gv)
2643 LAPPERR(d->views_[gv->id()] == gv);
2644 d->views_.remove(gv->id());
2645 if (current_view_ == gv)
2650 bool GuiApplication::closeAllViews()
2652 if (d->views_.empty())
2655 // When a view/window was closed before without quitting LyX, there
2656 // are already entries in the lastOpened list.
2657 theSession().lastOpened().clear();
2659 QList<GuiView *> const views = d->views_.values();
2660 foreach (GuiView * view, views) {
2661 if (!view->closeScheduled())
2670 GuiView & GuiApplication::view(int id) const
2672 LAPPERR(d->views_.contains(id));
2673 return *d->views_.value(id);
2677 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2679 QList<GuiView *> const views = d->views_.values();
2680 foreach (GuiView * view, views)
2681 view->hideDialog(name, inset);
2685 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2687 Buffer const * buffer_ = 0;
2688 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2689 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2690 if (Buffer const * ptr = (*it)->updateInset(inset))
2697 bool GuiApplication::searchMenu(FuncRequest const & func,
2698 docstring_list & names) const
2700 return d->menus_.searchMenu(func, names);
2704 // Ensure that a file is read only once (prevents include loops)
2705 static QStringList uifiles;
2706 // store which ui files define Toolbars
2707 static QStringList toolbar_uifiles;
2710 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2721 LexerKeyword uitags[] = {
2722 { "format", ui_format },
2723 { "include", ui_include },
2724 { "menuset", ui_menuset },
2725 { "toolbars", ui_toolbars },
2726 { "toolbarset", ui_toolbarset }
2730 lex.setFile(ui_path);
2732 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2736 if (lyxerr.debugging(Debug::PARSER))
2737 lex.printTable(lyxerr);
2740 // format before introduction of format tag
2741 unsigned int format = 0;
2742 while (lex.isOK()) {
2743 int const status = lex.lex();
2745 // we have to do this check here, outside the switch,
2746 // because otherwise we would start reading include files,
2747 // e.g., if the first tag we hit was an include tag.
2748 if (status == ui_format)
2750 format = lex.getInteger();
2754 // this will trigger unless the first tag we hit is a format
2755 // tag, with the right format.
2756 if (format != LFUN_FORMAT)
2757 return FormatMismatch;
2760 case Lexer::LEX_FEOF:
2765 QString const file = toqstr(lex.getString());
2766 bool const success = readUIFile(file, true);
2768 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2775 d->menus_.read(lex);
2779 d->toolbars_.readToolbars(lex);
2783 d->toolbars_.readToolbarSettings(lex);
2784 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2788 if (!rtrim(lex.getString()).empty())
2789 lex.printError("LyX::ReadUIFile: "
2790 "Unknown menu tag: `$$Token'");
2792 LYXERR0("Error with status: " << status);
2798 return (error ? ReadError : ReadOK);
2802 bool GuiApplication::readUIFile(QString const & name, bool include)
2804 LYXERR(Debug::INIT, "About to read " << name << "...");
2808 ui_path = libFileSearch("ui", name, "inc");
2809 if (ui_path.empty())
2810 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2812 ui_path = libFileSearch("ui", name, "ui");
2815 if (ui_path.empty()) {
2816 static const QString defaultUIFile = "default";
2817 LYXERR(Debug::INIT, "Could not find " << name);
2819 Alert::warning(_("Could not find UI definition file"),
2820 bformat(_("Error while reading the included file\n%1$s\n"
2821 "Please check your installation."), qstring_to_ucs4(name)));
2824 if (name == defaultUIFile) {
2825 LYXERR(Debug::INIT, "Could not find default UI file!!");
2826 Alert::warning(_("Could not find default UI file"),
2827 _("LyX could not find the default UI file!\n"
2828 "Please check your installation."));
2831 Alert::warning(_("Could not find UI definition file"),
2832 bformat(_("Error while reading the configuration file\n%1$s\n"
2833 "Falling back to default.\n"
2834 "Please look under Tools>Preferences>User Interface and\n"
2835 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2836 return readUIFile(defaultUIFile, false);
2839 QString const uifile = toqstr(ui_path.absFileName());
2840 if (uifiles.contains(uifile)) {
2842 // We are reading again the top uifile so reset the safeguard:
2845 d->toolbars_.reset();
2847 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2848 << "Is this an include loop?");
2852 uifiles.push_back(uifile);
2854 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2856 ReturnValues retval = readUIFile(ui_path);
2858 if (retval == FormatMismatch) {
2859 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2860 TempFile tmp("convertXXXXXX.ui");
2861 FileName const tempfile = tmp.name();
2862 bool const success = prefs2prefs(ui_path, tempfile, true);
2864 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2865 " to format " << LFUN_FORMAT << ".");
2867 retval = readUIFile(tempfile);
2871 if (retval != ReadOK) {
2872 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2880 settings.beginGroup("ui_files");
2881 bool touched = false;
2882 for (int i = 0; i != uifiles.size(); ++i) {
2883 QFileInfo fi(uifiles[i]);
2884 QDateTime const date_value = fi.lastModified();
2885 QString const name_key = QString::number(i);
2886 // if an ui file which defines Toolbars has changed,
2887 // we have to reset the settings
2888 if (toolbar_uifiles.contains(uifiles[i])
2889 && (!settings.contains(name_key)
2890 || settings.value(name_key).toString() != uifiles[i]
2891 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2893 settings.setValue(name_key, uifiles[i]);
2894 settings.setValue(name_key + "/date", date_value);
2897 settings.endGroup();
2899 settings.remove("views");
2905 void GuiApplication::onLastWindowClosed()
2907 if (d->global_menubar_)
2908 d->global_menubar_->grabKeyboard();
2912 void GuiApplication::startLongOperation() {
2913 d->key_checker_.start();
2917 bool GuiApplication::longOperationCancelled() {
2918 return d->key_checker_.pressed();
2922 void GuiApplication::stopLongOperation() {
2923 d->key_checker_.stop();
2927 bool GuiApplication::longOperationStarted() {
2928 return d->key_checker_.started();
2932 ////////////////////////////////////////////////////////////////////////
2934 // X11 specific stuff goes here...
2937 bool GuiApplication::x11EventFilter(XEvent * xev)
2942 switch (xev->type) {
2943 case SelectionRequest: {
2944 if (xev->xselectionrequest.selection != XA_PRIMARY)
2946 LYXERR(Debug::SELECTION, "X requested selection.");
2947 BufferView * bv = current_view_->currentBufferView();
2949 docstring const sel = bv->requestSelection();
2951 d->selection_.put(sel);
2955 case SelectionClear: {
2956 if (xev->xselectionclear.selection != XA_PRIMARY)
2958 LYXERR(Debug::SELECTION, "Lost selection.");
2959 BufferView * bv = current_view_->currentBufferView();
2961 bv->clearSelection();
2969 } // namespace frontend
2972 void hideDialogs(std::string const & name, Inset * inset)
2975 frontend::guiApp->hideDialogs(name, inset);
2979 ////////////////////////////////////////////////////////////////////
2983 ////////////////////////////////////////////////////////////////////
2985 frontend::FontLoader & theFontLoader()
2987 LAPPERR(frontend::guiApp);
2988 return frontend::guiApp->fontLoader();
2992 frontend::FontMetrics const & theFontMetrics(Font const & f)
2994 return theFontMetrics(f.fontInfo());
2998 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3000 LAPPERR(frontend::guiApp);
3001 return frontend::guiApp->fontLoader().metrics(f);
3005 ////////////////////////////////////////////////////////////////////
3009 ////////////////////////////////////////////////////////////////////
3011 frontend::Clipboard & theClipboard()
3013 LAPPERR(frontend::guiApp);
3014 return frontend::guiApp->clipboard();
3018 frontend::Selection & theSelection()
3020 LAPPERR(frontend::guiApp);
3021 return frontend::guiApp->selection();
3027 #include "moc_GuiApplication.cpp"