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 search_mode mode = theGuiApp()->imageSearchMode();
509 for (int i = 0; i < imagedirs.size(); ++i) {
510 QString imagedir = imagedirs.at(i) + path;
511 FileName fname = imageLibFileSearch(imagedir, name1, "png", mode);
513 return toqstr(fname.absFileName());
515 fname = imageLibFileSearch(imagedir, name2, "png", mode);
517 return toqstr(fname.absFileName());
520 path = ":/images/" + path;
523 LYXERR0("Directory " << path << " not found in resource!");
527 if (res.exists(name1))
531 if (res.exists(name2))
534 LYXERR(Debug::GUI, "Cannot find icon with filename "
535 << "\"" << name1 << "\""
537 << "\"" << name2 << "\""
539 << lyxaction.getActionName(f.action())
540 << '(' << to_utf8(f.argument()) << ")\"");
543 QString imagedir = "images/";
544 FileName fname = imageLibFileSearch(imagedir, "unknown", "png", mode);
546 return toqstr(fname.absFileName());
547 return QString(":/images/unknown.png");
553 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
556 QString imagedir = path;
557 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
558 QString path1 = toqstr(fname.absFileName());
559 QString path2 = ":/" + path + name + "." + ext;
561 if (pixmap.load(path1)) {
564 else if (pixmap.load(path2)) {
568 LYXERR0("Cannot load pixmap \""
569 << path << name << '.' << ext
570 << "\", please verify resource system!");
575 QIcon getIcon(FuncRequest const & f, bool unknown)
577 #if (QT_VERSION >= 0x040600)
578 if (lyxrc.use_system_theme_icons) {
579 QString action = toqstr(lyxaction.getActionName(f.action()));
580 if (!f.argument().empty())
581 action += " " + toqstr(f.argument());
582 QString const theme_icon = themeIconName(action);
583 if (QIcon::hasThemeIcon(theme_icon))
584 return QIcon::fromTheme(theme_icon);
588 QString icon = iconName(f, unknown);
592 //LYXERR(Debug::GUI, "Found icon: " << icon);
594 if (!pm.load(icon)) {
595 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
603 ////////////////////////////////////////////////////////////////////////
605 // LyX server support code.
607 ////////////////////////////////////////////////////////////////////////
609 class SocketNotifier : public QSocketNotifier
612 /// connect a connection notification from the LyXServerSocket
613 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
614 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
618 /// The callback function
619 Application::SocketCallback func_;
623 ////////////////////////////////////////////////////////////////////////
625 // Mac specific stuff goes here...
627 ////////////////////////////////////////////////////////////////////////
629 class MenuTranslator : public QTranslator
632 MenuTranslator(QObject * parent)
633 : QTranslator(parent)
636 #if QT_VERSION >= 0x050000
637 virtual QString translate(const char * /* context */,
638 const char *sourceText,
639 const char * /* disambiguation */ = 0, int /* n */ = -1) const
641 QString translate(const char * /*context*/,
642 const char * sourceText,
643 const char * /*comment*/ = 0) const
646 string const s = sourceText;
647 if (s == N_("About %1") || s == N_("Preferences")
648 || s == N_("Reconfigure") || s == N_("Quit %1"))
656 // QMacPasteboardMimeGraphics can only be compiled on Mac.
658 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
661 QMacPasteboardMimeGraphics()
662 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
665 QString convertorName() { return "Graphics"; }
667 QString flavorFor(QString const & mime)
669 LYXERR(Debug::ACTION, "flavorFor " << mime);
670 if (mime == pdfMimeType())
671 return QLatin1String("com.adobe.pdf");
675 QString mimeFor(QString flav)
677 LYXERR(Debug::ACTION, "mimeFor " << flav);
678 if (flav == QLatin1String("com.adobe.pdf"))
679 return pdfMimeType();
683 bool canConvert(QString const & mime, QString flav)
685 return mimeFor(flav) == mime;
688 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
692 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
696 QList<QByteArray> convertFromMime(QString const & /*mime*/,
697 QVariant data, QString /*flav*/)
699 QList<QByteArray> ret;
700 ret.append(data.toByteArray());
706 ///////////////////////////////////////////////////////////////
708 // You can find more platform specific stuff at the end of this file...
710 ///////////////////////////////////////////////////////////////
712 ////////////////////////////////////////////////////////////////////////
713 // Windows specific stuff goes here...
716 // QWindowsMimeMetafile can only be compiled on Windows.
718 static FORMATETC cfFromMime(QString const & mimetype)
721 if (mimetype == emfMimeType()) {
722 formatetc.cfFormat = CF_ENHMETAFILE;
723 formatetc.tymed = TYMED_ENHMF;
724 } else if (mimetype == wmfMimeType()) {
725 formatetc.cfFormat = CF_METAFILEPICT;
726 formatetc.tymed = TYMED_MFPICT;
729 formatetc.dwAspect = DVASPECT_CONTENT;
730 formatetc.lindex = -1;
735 class QWindowsMimeMetafile : public QWindowsMime {
737 QWindowsMimeMetafile() {}
739 bool canConvertFromMime(FORMATETC const & formatetc,
740 QMimeData const * mimedata) const
745 bool canConvertToMime(QString const & mimetype,
746 IDataObject * pDataObj) const
748 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
750 FORMATETC formatetc = cfFromMime(mimetype);
751 return pDataObj->QueryGetData(&formatetc) == S_OK;
754 bool convertFromMime(FORMATETC const & formatetc,
755 const QMimeData * mimedata, STGMEDIUM * pmedium) const
760 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
761 QVariant::Type preferredType) const
764 if (!canConvertToMime(mimetype, pDataObj))
767 FORMATETC formatetc = cfFromMime(mimetype);
769 if (pDataObj->GetData(&formatetc, &s) != S_OK)
773 if (s.tymed == TYMED_ENHMF) {
774 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
775 data.resize(dataSize);
776 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
777 (LPBYTE)data.data());
778 } else if (s.tymed == TYMED_MFPICT) {
779 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
780 data.resize(dataSize);
781 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
782 (LPBYTE)data.data());
785 ReleaseStgMedium(&s);
791 QVector<FORMATETC> formatsForMime(QString const & mimetype,
792 QMimeData const * mimedata) const
794 QVector<FORMATETC> formats;
795 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
796 formats += cfFromMime(mimetype);
800 QString mimeForFormat(FORMATETC const & formatetc) const
802 switch (formatetc.cfFormat) {
804 return emfMimeType();
805 case CF_METAFILEPICT:
806 return wmfMimeType();
815 /// Allows to check whether ESC was pressed during a long operation
816 class KeyChecker : public QObject {
821 KeyChecker() : pressed_(false), started_(false) {}
824 QCoreApplication::instance()->installEventFilter(this);
829 QCoreApplication::instance()->removeEventFilter(this);
833 QCoreApplication::processEvents();
836 bool started() const {
839 bool eventFilter(QObject *obj, QEvent *event) {
840 LYXERR(Debug::ACTION, "Event Type: " << event->type());
841 switch (event->type()) {
845 case QEvent::UpdateRequest:
846 case QEvent::CursorChange:
847 case QEvent::ActionChanged:
848 case QEvent::EnabledChange:
849 case QEvent::SockAct:
852 case QEvent::ToolTipChange:
853 case QEvent::LayoutRequest:
854 case QEvent::MetaCall:
855 return QObject::eventFilter(obj, event);
857 // FIXME Blocking all these events is a bad idea.
858 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
859 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
867 ////////////////////////////////////////////////////////////////////////
868 // GuiApplication::Private definition and implementation.
869 ////////////////////////////////////////////////////////////////////////
871 struct GuiApplication::Private
873 Private(): language_model_(0), meta_fake_bit(NoModifier),
877 /// WMF Mime handler for Windows clipboard.
878 wmf_mime_ = new QWindowsMimeMetafile;
880 initKeySequences(&theTopLevelKeymap());
883 void initKeySequences(KeyMap * kb)
885 keyseq = KeySequence(kb, kb);
886 cancel_meta_seq = KeySequence(kb, kb);
890 QSortFilterProxyModel * language_model_;
892 GuiClipboard clipboard_;
894 GuiSelection selection_;
896 FontLoader font_loader_;
898 ColorCache color_cache_;
900 QTranslator qt_trans_;
902 QHash<int, SocketNotifier *> socket_notifiers_;
906 /// The global instance
909 /// this timer is used for any regular events one wants to
910 /// perform. at present it is used to check if forked processes
912 QTimer general_timer_;
914 /// delayed FuncRequests
915 std::queue<FuncRequest> func_request_queue_;
920 KeySequence cancel_meta_seq;
922 KeyModifier meta_fake_bit;
924 /// Multiple views container.
926 * Warning: This must not be a smart pointer as the destruction of the
927 * object is handled by Qt when the view is closed
928 * \sa Qt::WA_DeleteOnClose attribute.
930 QHash<int, GuiView *> views_;
932 /// Only used on mac.
933 QMenuBar * global_menubar_;
936 /// Linkback mime handler for MacOSX.
937 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
941 /// WMF Mime handler for Windows clipboard.
942 QWindowsMimeMetafile * wmf_mime_;
945 /// Allows to check whether ESC was pressed during a long operation
946 KeyChecker key_checker_;
950 GuiApplication * guiApp;
952 GuiApplication::~GuiApplication()
955 closeAllLinkBackLinks();
961 GuiApplication::GuiApplication(int & argc, char ** argv)
962 : QApplication(argc, argv), current_view_(0),
963 d(new GuiApplication::Private)
965 QString app_name = "LyX";
966 QCoreApplication::setOrganizationName(app_name);
967 QCoreApplication::setOrganizationDomain("lyx.org");
968 QCoreApplication::setApplicationName(lyx_package);
970 qsrand(QDateTime::currentDateTime().toTime_t());
972 // Install translator for GUI elements.
973 installTranslator(&d->qt_trans_);
975 // FIXME: quitOnLastWindowClosed is true by default. We should have a
976 // lyxrc setting for this in order to let the application stay resident.
977 // But then we need some kind of dock icon, at least on Windows.
979 if (lyxrc.quit_on_last_window_closed)
980 setQuitOnLastWindowClosed(false);
983 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
984 // seems to be the default case for applications like LyX.
985 setQuitOnLastWindowClosed(false);
986 // This allows to translate the strings that appear in the LyX menu.
987 /// A translator suitable for the entries in the LyX menu.
988 /// Only needed with Qt/Mac.
989 installTranslator(new MenuTranslator(this));
995 // doubleClickInterval() is 400 ms on X11 which is just too long.
996 // On Windows and Mac OS X, the operating system's value is used.
997 // On Microsoft Windows, calling this function sets the double
998 // click interval for all applications. So we don't!
999 QApplication::setDoubleClickInterval(300);
1002 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1004 // needs to be done before reading lyxrc
1006 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1010 // Set the cache to 5120 kilobytes which corresponds to screen size of
1011 // 1280 by 1024 pixels with a color depth of 32 bits.
1012 QPixmapCache::setCacheLimit(5120);
1014 // Initialize RC Fonts
1015 if (lyxrc.roman_font_name.empty())
1016 lyxrc.roman_font_name = fromqstr(romanFontName());
1018 if (lyxrc.sans_font_name.empty())
1019 lyxrc.sans_font_name = fromqstr(sansFontName());
1021 if (lyxrc.typewriter_font_name.empty())
1022 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1024 d->general_timer_.setInterval(500);
1025 connect(&d->general_timer_, SIGNAL(timeout()),
1026 this, SLOT(handleRegularEvents()));
1027 d->general_timer_.start();
1029 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1030 // This is clearly not enough in a time where we use threads for
1031 // document preview and/or export. 20 should be OK.
1032 QThreadPool::globalInstance()->setMaxThreadCount(20);
1036 GuiApplication * theGuiApp()
1038 return dynamic_cast<GuiApplication *>(theApp());
1042 double GuiApplication::pixelRatio() const
1044 #if QT_VERSION >= 0x050000
1045 return devicePixelRatio();
1052 void GuiApplication::clearSession()
1059 docstring Application::iconName(FuncRequest const & f, bool unknown)
1061 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1065 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1069 BufferView * bv = 0;
1070 BufferView * doc_bv = 0;
1072 if (cmd.action() == LFUN_NOACTION) {
1073 status.message(from_utf8(N_("Nothing to do")));
1074 status.setEnabled(false);
1077 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1078 status.setUnknown(true);
1079 status.message(from_utf8(N_("Unknown action")));
1080 status.setEnabled(false);
1083 // Does the GuiApplication know something?
1084 else if (getStatus(cmd, status)) { }
1086 // If we do not have a GuiView, then other functions are disabled
1087 else if (!current_view_)
1088 status.setEnabled(false);
1090 // Does the GuiView know something?
1091 else if (current_view_->getStatus(cmd, status)) { }
1093 // In LyX/Mac, when a dialog is open, the menus of the
1094 // application can still be accessed without giving focus to
1095 // the main window. In this case, we want to disable the menu
1096 // entries that are buffer or view-related.
1097 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1099 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1100 status.setEnabled(false);
1103 // If we do not have a BufferView, then other functions are disabled
1104 else if (!(bv = current_view_->currentBufferView()))
1105 status.setEnabled(false);
1107 // Does the current BufferView know something?
1108 else if (bv->getStatus(cmd, status)) { }
1110 // Does the current Buffer know something?
1111 else if (bv->buffer().getStatus(cmd, status)) { }
1113 // If we do not have a document BufferView, different from the
1114 // current BufferView, then other functions are disabled
1115 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1116 status.setEnabled(false);
1118 // Does the document Buffer know something?
1119 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1122 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1123 status.message(from_utf8(N_("Command not handled")));
1124 status.setEnabled(false);
1127 // the default error message if we disable the command
1128 if (!status.enabled() && status.message().empty())
1129 status.message(from_utf8(N_("Command disabled")));
1135 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1137 // I would really like to avoid having this switch and rather try to
1138 // encode this in the function itself.
1139 // -- And I'd rather let an inset decide which LFUNs it is willing
1140 // to handle (Andre')
1142 switch (cmd.action()) {
1144 // This could be used for the no-GUI version. The GUI version is handled in
1145 // GuiView::getStatus(). See above.
1147 case LFUN_BUFFER_WRITE:
1148 case LFUN_BUFFER_WRITE_AS: {
1149 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1150 enable = b && (b->isUnnamed() || !b->isClean());
1155 case LFUN_BOOKMARK_GOTO: {
1156 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1157 enable = theSession().bookmarks().isValid(num);
1161 case LFUN_BOOKMARK_CLEAR:
1162 enable = theSession().bookmarks().hasValid();
1165 // this one is difficult to get right. As a half-baked
1166 // solution, we consider only the first action of the sequence
1167 case LFUN_COMMAND_SEQUENCE: {
1168 // argument contains ';'-terminated commands
1169 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1170 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1171 func.setOrigin(cmd.origin());
1172 flag = getStatus(func);
1176 // we want to check if at least one of these is enabled
1177 case LFUN_COMMAND_ALTERNATIVES: {
1178 // argument contains ';'-terminated commands
1179 string arg = to_utf8(cmd.argument());
1180 while (!arg.empty()) {
1182 arg = split(arg, first, ';');
1183 FuncRequest func(lyxaction.lookupFunc(first));
1184 func.setOrigin(cmd.origin());
1185 flag = getStatus(func);
1186 // if this one is enabled, the whole thing is
1195 string name = to_utf8(cmd.argument());
1196 if (theTopLevelCmdDef().lock(name, func)) {
1197 func.setOrigin(cmd.origin());
1198 flag = getStatus(func);
1199 theTopLevelCmdDef().release(name);
1201 // catch recursion or unknown command
1202 // definition. all operations until the
1203 // recursion or unknown command definition
1204 // occurs are performed, so set the state to
1211 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1213 case LFUN_PREFERENCES_SAVE:
1214 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1215 case LFUN_DEBUG_LEVEL_SET:
1216 // these are handled in our dispatch()
1219 case LFUN_WINDOW_CLOSE:
1220 enable = d->views_.size() > 0;
1223 case LFUN_BUFFER_NEW:
1224 case LFUN_BUFFER_NEW_TEMPLATE:
1225 case LFUN_FILE_OPEN:
1226 case LFUN_HELP_OPEN:
1227 case LFUN_SCREEN_FONT_UPDATE:
1228 case LFUN_SET_COLOR:
1229 case LFUN_WINDOW_NEW:
1231 case LFUN_LYXRC_APPLY:
1232 case LFUN_COMMAND_PREFIX:
1234 case LFUN_META_PREFIX:
1235 case LFUN_RECONFIGURE:
1236 case LFUN_SERVER_GET_FILENAME:
1237 case LFUN_SERVER_NOTIFY:
1241 case LFUN_BUFFER_FORALL: {
1242 if (theBufferList().empty()) {
1243 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1244 flag.setEnabled(false);
1248 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1249 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1250 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1251 flag.setEnabled(false);
1256 case LFUN_DIALOG_SHOW: {
1257 string const name = cmd.getArg(0);
1258 return name == "aboutlyx"
1260 || name == "texinfo"
1261 || name == "progress"
1262 || name == "compare";
1270 flag.setEnabled(false);
1274 /// make a post-dispatch status message
1275 static docstring makeDispatchMessage(docstring const & msg,
1276 FuncRequest const & cmd)
1278 const bool verbose = (cmd.origin() == FuncRequest::MENU
1279 || cmd.origin() == FuncRequest::TOOLBAR
1280 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1282 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1283 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1287 docstring dispatch_msg = msg;
1288 if (!dispatch_msg.empty())
1289 dispatch_msg += ' ';
1291 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1293 bool argsadded = false;
1295 if (!cmd.argument().empty()) {
1296 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1297 comname += ' ' + cmd.argument();
1301 docstring const shortcuts = theTopLevelKeymap().
1302 printBindings(cmd, KeySequence::ForGui);
1304 if (!shortcuts.empty())
1305 comname += ": " + shortcuts;
1306 else if (!argsadded && !cmd.argument().empty())
1307 comname += ' ' + cmd.argument();
1309 if (!comname.empty()) {
1310 comname = rtrim(comname);
1311 dispatch_msg += '(' + rtrim(comname) + ')';
1313 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1314 return dispatch_msg;
1318 void GuiApplication::dispatch(FuncRequest const & cmd)
1320 Buffer * buffer = 0;
1321 if (current_view_ && current_view_->currentBufferView()) {
1322 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1323 buffer = ¤t_view_->currentBufferView()->buffer();
1325 buffer->undo().beginUndoGroup();
1329 // redraw the screen at the end (first of the two drawing steps).
1330 // This is done unless explicitly requested otherwise
1331 dr.screenUpdate(Update::FitCursor);
1333 updateCurrentView(cmd, dr);
1335 // the buffer may have been closed by one action
1336 if (theBufferList().isLoaded(buffer))
1337 buffer->undo().endUndoGroup();
1341 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1346 BufferView * bv = current_view_->currentBufferView();
1348 if (dr.needBufferUpdate()) {
1349 bv->cursor().clearBufferUpdate();
1350 bv->buffer().updateBuffer();
1352 // BufferView::update() updates the ViewMetricsInfo and
1353 // also initializes the position cache for all insets in
1354 // (at least partially) visible top-level paragraphs.
1355 // We will redraw the screen only if needed.
1356 bv->processUpdateFlags(dr.screenUpdate());
1358 // Do we have a selection?
1359 theSelection().haveSelection(bv->cursor().selection());
1362 current_view_->restartCursor();
1364 if (dr.needMessageUpdate()) {
1365 // Some messages may already be translated, so we cannot use _()
1366 current_view_->message(makeDispatchMessage(
1367 translateIfPossible(dr.message()), cmd));
1372 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1373 bool switchToBuffer)
1375 if (!theSession().bookmarks().isValid(idx))
1377 BookmarksSection::Bookmark const & bm =
1378 theSession().bookmarks().bookmark(idx);
1379 LASSERT(!bm.filename.empty(), return);
1380 string const file = bm.filename.absFileName();
1381 // if the file is not opened, open it.
1382 if (!theBufferList().exists(bm.filename)) {
1384 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1388 // open may fail, so we need to test it again
1389 if (!theBufferList().exists(bm.filename))
1392 // bm can be changed when saving
1393 BookmarksSection::Bookmark tmp = bm;
1395 // Special case idx == 0 used for back-from-back jump navigation
1397 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1399 // if the current buffer is not that one, switch to it.
1400 BufferView * doc_bv = current_view_ ?
1401 current_view_->documentBufferView() : 0;
1402 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1403 if (switchToBuffer) {
1404 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1407 doc_bv = current_view_->documentBufferView();
1412 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1413 if (!doc_bv->moveToPosition(
1414 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1421 // Cursor jump succeeded!
1422 Cursor const & cur = doc_bv->cursor();
1423 pit_type new_pit = cur.pit();
1424 pos_type new_pos = cur.pos();
1425 int new_id = cur.paragraph().id();
1427 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1428 // see http://www.lyx.org/trac/ticket/3092
1429 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1430 || bm.top_id != new_id) {
1431 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1432 new_pit, new_pos, new_id);
1436 // This function runs "configure" and then rereads lyx.defaults to
1437 // reconfigure the automatic settings.
1438 void GuiApplication::reconfigure(string const & option)
1440 // emit message signal.
1442 current_view_->message(_("Running configure..."));
1444 // Run configure in user lyx directory
1445 PathChanger p(package().user_support());
1446 string configure_command = package().configure_command();
1447 configure_command += option;
1449 int const ret = one.startscript(Systemcall::Wait, configure_command);
1451 // emit message signal.
1453 current_view_->message(_("Reloading configuration..."));
1454 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1455 // Re-read packages.lst
1456 LaTeXPackages::getAvailable();
1459 Alert::information(_("System reconfiguration failed"),
1460 _("The system reconfiguration has failed.\n"
1461 "Default textclass is used but LyX may\n"
1462 "not be able to work properly.\n"
1463 "Please reconfigure again if needed."));
1465 Alert::information(_("System reconfigured"),
1466 _("The system has been reconfigured.\n"
1467 "You need to restart LyX to make use of any\n"
1468 "updated document class specifications."));
1471 void GuiApplication::validateCurrentView()
1473 if (!d->views_.empty() && !current_view_) {
1474 // currently at least one view exists but no view has the focus.
1475 // choose the last view to make it current.
1476 // a view without any open document is preferred.
1477 GuiView * candidate = 0;
1478 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1479 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1480 for (; it != end; ++it) {
1482 if (!candidate->documentBufferView())
1485 setCurrentView(candidate);
1489 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1491 string const argument = to_utf8(cmd.argument());
1492 FuncCode const action = cmd.action();
1494 LYXERR(Debug::ACTION, "cmd: " << cmd);
1496 // we have not done anything wrong yet.
1499 FuncStatus const flag = getStatus(cmd);
1500 if (!flag.enabled()) {
1501 // We cannot use this function here
1502 LYXERR(Debug::ACTION, "action "
1503 << lyxaction.getActionName(action)
1504 << " [" << action << "] is disabled at this location");
1505 dr.setMessage(flag.message());
1507 dr.dispatched(false);
1508 dr.screenUpdate(Update::None);
1509 dr.clearBufferUpdate();
1513 if (cmd.origin() == FuncRequest::LYXSERVER) {
1514 if (current_view_ && current_view_->currentBufferView())
1515 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1516 // we will also need to redraw the screen at the end
1517 dr.screenUpdate(Update::FitCursor);
1520 // Assumes that the action will be dispatched.
1521 dr.dispatched(true);
1523 switch (cmd.action()) {
1525 case LFUN_WINDOW_NEW:
1526 createView(toqstr(cmd.argument()));
1529 case LFUN_WINDOW_CLOSE:
1530 // update bookmark pit of the current buffer before window close
1531 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1532 gotoBookmark(i+1, false, false);
1533 // clear the last opened list, because
1534 // maybe this will end the session
1535 theSession().lastOpened().clear();
1536 // check for valid current_view_
1537 validateCurrentView();
1539 current_view_->closeScheduled();
1543 // quitting is triggered by the gui code
1544 // (leaving the event loop).
1546 current_view_->message(from_utf8(N_("Exiting.")));
1547 if (closeAllViews())
1551 case LFUN_SCREEN_FONT_UPDATE: {
1552 // handle the screen font changes.
1553 d->font_loader_.update();
1554 // Backup current_view_
1555 GuiView * view = current_view_;
1556 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1557 // to skip the refresh.
1559 theBufferList().changed(false);
1560 // Restore current_view_
1561 current_view_ = view;
1565 case LFUN_BUFFER_NEW:
1566 validateCurrentView();
1567 if (d->views_.empty()
1568 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1569 createView(QString(), false); // keep hidden
1570 current_view_->newDocument(to_utf8(cmd.argument()), false);
1571 current_view_->show();
1572 setActiveWindow(current_view_);
1574 current_view_->newDocument(to_utf8(cmd.argument()), false);
1578 case LFUN_BUFFER_NEW_TEMPLATE:
1579 validateCurrentView();
1580 if (d->views_.empty()
1581 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1583 current_view_->newDocument(to_utf8(cmd.argument()), true);
1584 if (!current_view_->documentBufferView())
1585 current_view_->close();
1587 current_view_->newDocument(to_utf8(cmd.argument()), true);
1591 case LFUN_FILE_OPEN: {
1592 validateCurrentView();
1593 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1594 string const fname = to_utf8(cmd.argument());
1595 bool const is_open = FileName::isAbsolute(fname)
1596 && theBufferList().getBuffer(FileName(fname));
1597 if (d->views_.empty()
1598 || (!lyxrc.open_buffers_in_tabs
1599 && current_view_->documentBufferView() != 0
1601 // We want the ui session to be saved per document and not per
1602 // window number. The filename crc is a good enough identifier.
1603 boost::crc_32_type crc;
1604 crc = for_each(fname.begin(), fname.end(), crc);
1605 createView(crc.checksum());
1606 current_view_->openDocument(fname);
1607 if (current_view_ && !current_view_->documentBufferView())
1608 current_view_->close();
1610 current_view_->openDocument(fname);
1614 case LFUN_HELP_OPEN: {
1615 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1616 if (current_view_ == 0)
1618 string const arg = to_utf8(cmd.argument());
1620 current_view_->message(_("Missing argument"));
1623 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1625 fname = i18nLibFileSearch("examples", arg, "lyx");
1627 if (fname.empty()) {
1628 lyxerr << "LyX: unable to find documentation file `"
1629 << arg << "'. Bad installation?" << endl;
1632 current_view_->message(bformat(_("Opening help file %1$s..."),
1633 makeDisplayPath(fname.absFileName())));
1634 Buffer * buf = current_view_->loadDocument(fname, false);
1636 #ifndef DEVEL_VERSION
1638 buf->setReadonly(true);
1645 case LFUN_SET_COLOR: {
1647 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1648 if (lyx_name.empty() || x11_name.empty()) {
1650 current_view_->message(
1651 _("Syntax: set-color <lyx_name> <x11_name>"));
1656 // FIXME: The graphics cache no longer has a changeDisplay method.
1657 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1658 bool const graphicsbg_changed =
1659 lyx_name == graphicsbg && x11_name != graphicsbg;
1660 if (graphicsbg_changed)
1661 graphics::GCache::get().changeDisplay(true);
1664 if (!lcolor.setColor(lyx_name, x11_name)) {
1666 current_view_->message(
1667 bformat(_("Set-color \"%1$s\" failed "
1668 "- color is undefined or "
1669 "may not be redefined"),
1670 from_utf8(lyx_name)));
1673 // Make sure we don't keep old colors in cache.
1674 d->color_cache_.clear();
1678 case LFUN_LYXRC_APPLY: {
1679 // reset active key sequences, since the bindings
1680 // are updated (bug 6064)
1682 LyXRC const lyxrc_orig = lyxrc;
1684 istringstream ss(to_utf8(cmd.argument()));
1685 bool const success = lyxrc.read(ss);
1688 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1689 << "Unable to read lyxrc data"
1694 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1696 // If the request comes from the minibuffer, then we can't reset
1697 // the GUI, since that would destory the minibuffer itself and
1698 // cause a crash, since we are currently in one of the methods of
1699 // GuiCommandBuffer. See bug #8540.
1700 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1703 // FIXME Unfortunately, that leaves a bug here, since we cannot
1704 // reset the GUI in this case. If the changes to lyxrc affected the
1705 // UI, then, nothing would happen. This seems fairly unlikely, but
1706 // it definitely is a bug.
1711 case LFUN_COMMAND_PREFIX:
1712 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1717 d->meta_fake_bit = NoModifier;
1718 GuiView * gv = currentView();
1719 if (gv && gv->currentBufferView())
1720 // cancel any selection
1721 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1722 dr.setMessage(from_ascii(N_("Cancel")));
1725 case LFUN_META_PREFIX:
1726 d->meta_fake_bit = AltModifier;
1727 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1730 // --- Menus -----------------------------------------------
1731 case LFUN_RECONFIGURE:
1732 // argument is any additional parameter to the configure.py command
1733 reconfigure(to_utf8(cmd.argument()));
1736 // --- lyxserver commands ----------------------------
1737 case LFUN_SERVER_GET_FILENAME: {
1738 if (current_view_ && current_view_->documentBufferView()) {
1739 docstring const fname = from_utf8(
1740 current_view_->documentBufferView()->buffer().absFileName());
1741 dr.setMessage(fname);
1742 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1744 dr.setMessage(docstring());
1745 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1750 case LFUN_SERVER_NOTIFY: {
1751 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1752 dr.setMessage(dispatch_buffer);
1753 theServer().notifyClient(to_utf8(dispatch_buffer));
1757 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1758 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1764 string rest = split(argument, countstr, ' ');
1765 istringstream is(countstr);
1768 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1769 for (int i = 0; i < count; ++i)
1770 dispatch(lyxaction.lookupFunc(rest));
1774 case LFUN_COMMAND_SEQUENCE: {
1775 // argument contains ';'-terminated commands
1776 string arg = argument;
1777 // FIXME: this LFUN should also work without any view.
1778 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1779 ? &(current_view_->documentBufferView()->buffer()) : 0;
1781 buffer->undo().beginUndoGroup();
1782 while (!arg.empty()) {
1784 arg = split(arg, first, ';');
1785 FuncRequest func(lyxaction.lookupFunc(first));
1786 func.setOrigin(cmd.origin());
1789 // the buffer may have been closed by one action
1790 if (theBufferList().isLoaded(buffer))
1791 buffer->undo().endUndoGroup();
1795 case LFUN_BUFFER_FORALL: {
1796 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1798 map<Buffer *, GuiView *> views_lVisible;
1799 map<GuiView *, Buffer *> activeBuffers;
1801 QList<GuiView *> allViews = d->views_.values();
1803 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1804 // and on which buffer is active in each view.
1805 Buffer * const last = theBufferList().last();
1806 foreach (GuiView * view, allViews) {
1807 // all of the buffers might be locally hidden. That is, there is no active buffer.
1808 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1809 activeBuffers[view] = 0;
1811 activeBuffers[view] = &view->currentBufferView()->buffer();
1813 // find out if each is locally visible or locally hidden.
1814 // we don't use a for loop as the buffer list cycles.
1815 Buffer * b = theBufferList().first();
1817 bool const locallyVisible = view && view->workArea(*b);
1818 if (locallyVisible) {
1819 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1820 // only need to overwrite/add if we don't already know a buffer is globally
1821 // visible or we do know but we would prefer to dispatch LFUN from the
1822 // current view because of cursor position issues.
1823 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1824 views_lVisible[b] = view;
1828 b = theBufferList().next(b);
1832 GuiView * const homeView = currentView();
1833 Buffer * b = theBufferList().first();
1834 Buffer * nextBuf = 0;
1835 int numProcessed = 0;
1838 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1840 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1842 // first change to a view where b is locally visible, preferably current_view_.
1843 GuiView * const vLv = views_lVisible[b];
1845 lyx::dispatch(funcToRun);
1853 // put things back to how they were (if possible).
1854 foreach (GuiView * view, allViews) {
1855 Buffer * originalBuf = activeBuffers[view];
1856 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1857 if (theBufferList().isLoaded(originalBuf))
1858 view->setBuffer(originalBuf);
1860 homeView->setFocus();
1862 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1866 case LFUN_COMMAND_ALTERNATIVES: {
1867 // argument contains ';'-terminated commands
1868 string arg = argument;
1869 while (!arg.empty()) {
1871 arg = split(arg, first, ';');
1872 FuncRequest func(lyxaction.lookupFunc(first));
1873 func.setOrigin(cmd.origin());
1874 FuncStatus const stat = getStatus(func);
1875 if (stat.enabled()) {
1885 if (theTopLevelCmdDef().lock(argument, func)) {
1886 func.setOrigin(cmd.origin());
1888 theTopLevelCmdDef().release(argument);
1890 if (func.action() == LFUN_UNKNOWN_ACTION) {
1891 // unknown command definition
1892 lyxerr << "Warning: unknown command definition `"
1896 // recursion detected
1897 lyxerr << "Warning: Recursion in the command definition `"
1898 << argument << "' detected"
1905 case LFUN_PREFERENCES_SAVE:
1906 lyxrc.write(support::makeAbsPath("preferences",
1907 package().user_support().absFileName()), false);
1910 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1911 string const fname = addName(addPath(package().user_support().absFileName(),
1912 "templates/"), "defaults.lyx");
1913 Buffer defaults(fname);
1915 istringstream ss(argument);
1920 // We need to make sure that, after we recreat the DocumentClass,
1921 // which we do in readHeader, we apply it to the document itself.
1922 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1923 int const unknown_tokens = defaults.readHeader(lex);
1924 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1926 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1927 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1929 if (unknown_tokens != 0) {
1930 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1931 << unknown_tokens << " unknown token"
1932 << (unknown_tokens == 1 ? "" : "s")
1936 if (defaults.writeFile(FileName(defaults.absFileName())))
1937 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1938 makeDisplayPath(fname)));
1941 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1946 case LFUN_BOOKMARK_GOTO:
1947 // go to bookmark, open unopened file and switch to buffer if necessary
1948 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1949 dr.screenUpdate(Update::Force | Update::FitCursor);
1952 case LFUN_BOOKMARK_CLEAR:
1953 theSession().bookmarks().clear();
1956 case LFUN_DEBUG_LEVEL_SET:
1957 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1960 case LFUN_DIALOG_SHOW: {
1961 string const name = cmd.getArg(0);
1963 if ( name == "aboutlyx"
1965 || name == "texinfo"
1966 || name == "progress"
1967 || name == "compare")
1969 // work around: on Mac OS the application
1970 // is not terminated when closing the last view.
1971 // Create a new one to be able to dispatch the
1972 // LFUN_DIALOG_SHOW to this view.
1973 if (current_view_ == 0)
1979 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1982 current_view_->dispatch(cmd, dr);
1986 if (cmd.origin() == FuncRequest::LYXSERVER)
1987 updateCurrentView(cmd, dr);
1991 docstring GuiApplication::viewStatusMessage()
1993 // When meta-fake key is pressed, show the key sequence so far + "M-".
1994 if (d->meta_fake_bit != NoModifier)
1995 return d->keyseq.print(KeySequence::ForGui) + "M-";
1997 // Else, when a non-complete key sequence is pressed,
1998 // show the available options.
1999 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2000 return d->keyseq.printOptions(true);
2006 void GuiApplication::handleKeyFunc(FuncCode action)
2010 if (d->keyseq.length())
2012 GuiView * gv = currentView();
2013 LASSERT(gv && gv->currentBufferView(), return);
2014 BufferView * bv = gv->currentBufferView();
2015 bv->getIntl().getTransManager().deadkey(
2016 c, get_accent(action).accent, bv->cursor().innerText(),
2018 // Need to clear, in case the minibuffer calls these
2021 // copied verbatim from do_accent_char
2022 bv->cursor().resetAnchor();
2026 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2028 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2030 // Do nothing if we have nothing (JMarc)
2031 if (!keysym.isOK()) {
2032 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2034 current_view_->restartCursor();
2038 if (keysym.isModifier()) {
2040 current_view_->restartCursor();
2044 char_type encoded_last_key = keysym.getUCSEncoded();
2046 // Do a one-deep top-level lookup for
2047 // cancel and meta-fake keys. RVDK_PATCH_5
2048 d->cancel_meta_seq.reset();
2050 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2051 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2053 // When not cancel or meta-fake, do the normal lookup.
2054 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2055 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2056 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2057 // remove Caps Lock and Mod2 as a modifiers
2058 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2059 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2062 // Dont remove this unless you know what you are doing.
2063 d->meta_fake_bit = NoModifier;
2065 // Can this happen now ?
2066 if (func.action() == LFUN_NOACTION)
2067 func = FuncRequest(LFUN_COMMAND_PREFIX);
2069 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2070 << d->keyseq.print(KeySequence::Portable) << ']');
2072 // already here we know if it any point in going further
2073 // why not return already here if action == -1 and
2074 // num_bytes == 0? (Lgb)
2076 if (d->keyseq.length() > 1 && current_view_)
2077 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2080 // Maybe user can only reach the key via holding down shift.
2081 // Let's see. But only if shift is the only modifier
2082 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2083 LYXERR(Debug::KEY, "Trying without shift");
2084 func = d->keyseq.addkey(keysym, NoModifier);
2085 LYXERR(Debug::KEY, "Action now " << func.action());
2088 if (func.action() == LFUN_UNKNOWN_ACTION) {
2089 // Hmm, we didn't match any of the keysequences. See
2090 // if it's normal insertable text not already covered
2092 if (keysym.isText() && d->keyseq.length() == 1) {
2093 LYXERR(Debug::KEY, "isText() is true, inserting.");
2094 func = FuncRequest(LFUN_SELF_INSERT,
2095 FuncRequest::KEYBOARD);
2097 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2098 if (current_view_) {
2099 current_view_->message(_("Unknown function."));
2100 current_view_->restartCursor();
2106 if (func.action() == LFUN_SELF_INSERT) {
2107 if (encoded_last_key != 0) {
2108 docstring const arg(1, encoded_last_key);
2109 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2110 FuncRequest::KEYBOARD));
2111 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2114 processFuncRequest(func);
2118 void GuiApplication::processFuncRequest(FuncRequest const & func)
2120 lyx::dispatch(func);
2124 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2126 addToFuncRequestQueue(func);
2127 processFuncRequestQueueAsync();
2131 void GuiApplication::processFuncRequestQueue()
2133 while (!d->func_request_queue_.empty()) {
2134 processFuncRequest(d->func_request_queue_.front());
2135 d->func_request_queue_.pop();
2140 void GuiApplication::processFuncRequestQueueAsync()
2142 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2146 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2148 d->func_request_queue_.push(func);
2152 void GuiApplication::resetGui()
2154 // Set the language defined by the user.
2158 if (!readUIFile(toqstr(lyxrc.ui_file)))
2159 // Gives some error box here.
2162 if (d->global_menubar_)
2163 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2165 QHash<int, GuiView *>::iterator it;
2166 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2169 gv->setLayoutDirection(layoutDirection());
2173 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2177 void GuiApplication::createView(int view_id)
2179 createView(QString(), true, view_id);
2183 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2186 // release the keyboard which might have been grabed by the global
2187 // menubar on Mac to catch shortcuts even without any GuiView.
2188 if (d->global_menubar_)
2189 d->global_menubar_->releaseKeyboard();
2193 while (d->views_.find(id) != d->views_.end())
2196 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2197 GuiView * view = new GuiView(id);
2199 d->views_[id] = view;
2203 setActiveWindow(view);
2206 if (!geometry_arg.isEmpty()) {
2207 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2211 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2212 re.indexIn(geometry_arg);
2213 w = re.cap(1).toInt();
2214 h = re.cap(2).toInt();
2215 x = re.cap(3).toInt();
2216 y = re.cap(4).toInt();
2217 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2218 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2219 // Set initial geometry such that we can get the frame size.
2220 view->setGeometry(x, y, w, h);
2221 int framewidth = view->geometry().x() - view->x();
2222 int titleheight = view->geometry().y() - view->y();
2223 // Negative displacements must be interpreted as distances
2224 // from the right or bottom screen borders.
2225 if (sx == '-' || sy == '-') {
2226 QRect rec = QApplication::desktop()->screenGeometry();
2228 x += rec.width() - w - framewidth;
2230 y += rec.height() - h - titleheight;
2231 view->setGeometry(x, y, w, h);
2233 // Make sure that the left and top frame borders are visible.
2234 if (view->x() < 0 || view->y() < 0) {
2239 view->setGeometry(x, y, w, h);
2247 Clipboard & GuiApplication::clipboard()
2249 return d->clipboard_;
2253 Selection & GuiApplication::selection()
2255 return d->selection_;
2259 FontLoader & GuiApplication::fontLoader()
2261 return d->font_loader_;
2265 Toolbars const & GuiApplication::toolbars() const
2267 return d->toolbars_;
2271 Toolbars & GuiApplication::toolbars()
2273 return d->toolbars_;
2277 Menus const & GuiApplication::menus() const
2283 Menus & GuiApplication::menus()
2289 QList<int> GuiApplication::viewIds() const
2291 return d->views_.keys();
2295 ColorCache & GuiApplication::colorCache()
2297 return d->color_cache_;
2301 int GuiApplication::exec()
2303 // asynchronously handle batch commands. This event will be in
2304 // the event queue in front of other asynchronous events. Hence,
2305 // we can assume in the latter that the gui is setup already.
2306 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2308 return QApplication::exec();
2312 void GuiApplication::exit(int status)
2314 QApplication::exit(status);
2318 void GuiApplication::setGuiLanguage()
2322 // install translation file for Qt built-in dialogs
2323 QString const language_name = QString("qt_") + theLocale.name();
2324 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2325 // Short-named translator can be loaded from a long name, but not the
2326 // opposite. Therefore, long name should be used without truncation.
2327 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2328 if (!d->qt_trans_.load(language_name,
2329 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2330 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2333 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2337 switch (theLocale.language()) {
2338 case QLocale::Arabic :
2339 case QLocale::Hebrew :
2340 case QLocale::Persian :
2341 case QLocale::Urdu :
2342 setLayoutDirection(Qt::RightToLeft);
2345 setLayoutDirection(Qt::LeftToRight);
2350 void GuiApplication::execBatchCommands()
2355 if (!readUIFile(toqstr(lyxrc.ui_file)))
2356 // Gives some error box here.
2360 #if QT_VERSION > 0x040600
2361 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2363 // Create the global default menubar which is shown for the dialogs
2364 // and if no GuiView is visible.
2365 // This must be done after the session was recovered to know the "last files".
2366 d->global_menubar_ = new QMenuBar(0);
2367 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2370 lyx::execBatchCommands();
2374 QAbstractItemModel * GuiApplication::languageModel()
2376 if (d->language_model_)
2377 return d->language_model_;
2379 QStandardItemModel * lang_model = new QStandardItemModel(this);
2380 lang_model->insertColumns(0, 3);
2382 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2383 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2384 Languages::const_iterator it = lyx::languages.begin();
2385 Languages::const_iterator end = lyx::languages.end();
2386 for (; it != end; ++it) {
2387 current_row = lang_model->rowCount();
2388 lang_model->insertRows(current_row, 1);
2389 QModelIndex pl_item = lang_model->index(current_row, 0);
2390 QModelIndex sp_item = lang_model->index(current_row, 1);
2391 QModelIndex th_item = lang_model->index(current_row, 2);
2392 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2393 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2394 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2395 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2396 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2397 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2398 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2399 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2400 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2401 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2403 d->language_model_ = new QSortFilterProxyModel(this);
2404 d->language_model_->setSourceModel(lang_model);
2405 d->language_model_->setSortLocaleAware(true);
2406 return d->language_model_;
2410 void GuiApplication::restoreGuiSession()
2412 if (!lyxrc.load_session)
2415 Session & session = theSession();
2416 LastOpenedSection::LastOpened const & lastopened =
2417 session.lastOpened().getfiles();
2419 validateCurrentView();
2421 FileName active_file;
2422 // do not add to the lastfile list since these files are restored from
2423 // last session, and should be already there (regular files), or should
2424 // not be added at all (help files).
2425 for (size_t i = 0; i < lastopened.size(); ++i) {
2426 FileName const & file_name = lastopened[i].file_name;
2427 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2428 && current_view_->documentBufferView() != 0)) {
2429 boost::crc_32_type crc;
2430 string const & fname = file_name.absFileName();
2431 crc = for_each(fname.begin(), fname.end(), crc);
2432 createView(crc.checksum());
2434 current_view_->loadDocument(file_name, false);
2436 if (lastopened[i].active)
2437 active_file = file_name;
2440 // Restore last active buffer
2441 Buffer * buffer = theBufferList().getBuffer(active_file);
2442 if (buffer && current_view_)
2443 current_view_->setBuffer(buffer);
2445 // clear this list to save a few bytes of RAM
2446 session.lastOpened().clear();
2450 QString const GuiApplication::romanFontName()
2453 font.setStyleHint(QFont::Serif);
2454 font.setFamily("serif");
2456 return QFontInfo(font).family();
2460 QString const GuiApplication::sansFontName()
2463 font.setStyleHint(QFont::SansSerif);
2464 font.setFamily("sans");
2466 return QFontInfo(font).family();
2470 QString const GuiApplication::typewriterFontName()
2473 font.setStyleHint(QFont::TypeWriter);
2474 font.setFamily("monospace");
2476 return QFontInfo(font).family();
2480 void GuiApplication::handleRegularEvents()
2482 ForkedCallsController::handleCompletedProcesses();
2486 bool GuiApplication::event(QEvent * e)
2489 case QEvent::FileOpen: {
2490 // Open a file; this happens only on Mac OS X for now.
2492 // We do this asynchronously because on startup the batch
2493 // commands are not executed here yet and the gui is not ready
2495 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2496 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2497 processFuncRequestAsync(fr);
2502 return QApplication::event(e);
2507 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2510 return QApplication::notify(receiver, event);
2512 catch (ExceptionMessage const & e) {
2514 case ErrorException:
2516 setQuitOnLastWindowClosed(false);
2518 Alert::error(e.title_, e.details_);
2520 // Properly crash in debug mode in order to get a useful backtrace.
2523 // In release mode, try to exit gracefully.
2526 case BufferException: {
2527 if (!current_view_ || !current_view_->documentBufferView())
2529 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2530 docstring details = e.details_ + '\n';
2531 details += buf->emergencyWrite();
2532 theBufferList().release(buf);
2533 details += "\n" + _("The current document was closed.");
2534 Alert::error(e.title_, details);
2537 case WarningException:
2538 Alert::warning(e.title_, e.details_);
2542 catch (exception const & e) {
2543 docstring s = _("LyX has caught an exception, it will now "
2544 "attempt to save all unsaved documents and exit."
2546 s += from_ascii(e.what());
2547 Alert::error(_("Software exception Detected"), s);
2551 docstring s = _("LyX has caught some really weird exception, it will "
2552 "now attempt to save all unsaved documents and exit.");
2553 Alert::error(_("Software exception Detected"), s);
2561 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2563 QColor const & qcol = d->color_cache_.get(col);
2564 if (!qcol.isValid()) {
2570 rgbcol.r = qcol.red();
2571 rgbcol.g = qcol.green();
2572 rgbcol.b = qcol.blue();
2577 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2579 QColor const qcol(lcolor.getX11Name(col).c_str());
2580 if (!qcol.isValid()) {
2586 rgbcol.r = qcol.red();
2587 rgbcol.g = qcol.green();
2588 rgbcol.b = qcol.blue();
2593 string const GuiApplication::hexName(ColorCode col)
2595 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2599 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2601 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2602 d->socket_notifiers_[fd] = sn;
2603 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2607 void GuiApplication::socketDataReceived(int fd)
2609 d->socket_notifiers_[fd]->func_();
2613 void GuiApplication::unregisterSocketCallback(int fd)
2615 d->socket_notifiers_.take(fd)->setEnabled(false);
2619 void GuiApplication::commitData(QSessionManager & sm)
2621 /// The implementation is required to avoid an application exit
2622 /// when session state save is triggered by session manager.
2623 /// The default implementation sends a close event to all
2624 /// visible top level widgets when session managment allows
2626 /// We are changing that to close all wiew one by one.
2627 /// FIXME: verify if the default implementation is enough now.
2628 #ifdef QT_NO_SESSIONMANAGER
2630 #warning Qt is compiled without session manager
2632 #pragma message("warning: Qt is compiled without session manager")
2636 if (sm.allowsInteraction() && !closeAllViews())
2642 void GuiApplication::unregisterView(GuiView * gv)
2644 LAPPERR(d->views_[gv->id()] == gv);
2645 d->views_.remove(gv->id());
2646 if (current_view_ == gv)
2651 bool GuiApplication::closeAllViews()
2653 if (d->views_.empty())
2656 // When a view/window was closed before without quitting LyX, there
2657 // are already entries in the lastOpened list.
2658 theSession().lastOpened().clear();
2660 QList<GuiView *> const views = d->views_.values();
2661 foreach (GuiView * view, views) {
2662 if (!view->closeScheduled())
2671 GuiView & GuiApplication::view(int id) const
2673 LAPPERR(d->views_.contains(id));
2674 return *d->views_.value(id);
2678 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2680 QList<GuiView *> const views = d->views_.values();
2681 foreach (GuiView * view, views)
2682 view->hideDialog(name, inset);
2686 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2688 Buffer const * buffer_ = 0;
2689 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2690 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2691 if (Buffer const * ptr = (*it)->updateInset(inset))
2698 bool GuiApplication::searchMenu(FuncRequest const & func,
2699 docstring_list & names) const
2701 return d->menus_.searchMenu(func, names);
2705 // Ensure that a file is read only once (prevents include loops)
2706 static QStringList uifiles;
2707 // store which ui files define Toolbars
2708 static QStringList toolbar_uifiles;
2711 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2722 LexerKeyword uitags[] = {
2723 { "format", ui_format },
2724 { "include", ui_include },
2725 { "menuset", ui_menuset },
2726 { "toolbars", ui_toolbars },
2727 { "toolbarset", ui_toolbarset }
2731 lex.setFile(ui_path);
2733 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2737 if (lyxerr.debugging(Debug::PARSER))
2738 lex.printTable(lyxerr);
2741 // format before introduction of format tag
2742 unsigned int format = 0;
2743 while (lex.isOK()) {
2744 int const status = lex.lex();
2746 // we have to do this check here, outside the switch,
2747 // because otherwise we would start reading include files,
2748 // e.g., if the first tag we hit was an include tag.
2749 if (status == ui_format)
2751 format = lex.getInteger();
2755 // this will trigger unless the first tag we hit is a format
2756 // tag, with the right format.
2757 if (format != LFUN_FORMAT)
2758 return FormatMismatch;
2761 case Lexer::LEX_FEOF:
2766 QString const file = toqstr(lex.getString());
2767 bool const success = readUIFile(file, true);
2769 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2776 d->menus_.read(lex);
2780 d->toolbars_.readToolbars(lex);
2784 d->toolbars_.readToolbarSettings(lex);
2785 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2789 if (!rtrim(lex.getString()).empty())
2790 lex.printError("LyX::ReadUIFile: "
2791 "Unknown menu tag: `$$Token'");
2793 LYXERR0("Error with status: " << status);
2799 return (error ? ReadError : ReadOK);
2803 bool GuiApplication::readUIFile(QString const & name, bool include)
2805 LYXERR(Debug::INIT, "About to read " << name << "...");
2809 ui_path = libFileSearch("ui", name, "inc");
2810 if (ui_path.empty())
2811 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2813 ui_path = libFileSearch("ui", name, "ui");
2816 if (ui_path.empty()) {
2817 static const QString defaultUIFile = "default";
2818 LYXERR(Debug::INIT, "Could not find " << name);
2820 Alert::warning(_("Could not find UI definition file"),
2821 bformat(_("Error while reading the included file\n%1$s\n"
2822 "Please check your installation."), qstring_to_ucs4(name)));
2825 if (name == defaultUIFile) {
2826 LYXERR(Debug::INIT, "Could not find default UI file!!");
2827 Alert::warning(_("Could not find default UI file"),
2828 _("LyX could not find the default UI file!\n"
2829 "Please check your installation."));
2832 Alert::warning(_("Could not find UI definition file"),
2833 bformat(_("Error while reading the configuration file\n%1$s\n"
2834 "Falling back to default.\n"
2835 "Please look under Tools>Preferences>User Interface and\n"
2836 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2837 return readUIFile(defaultUIFile, false);
2840 QString const uifile = toqstr(ui_path.absFileName());
2841 if (uifiles.contains(uifile)) {
2843 // We are reading again the top uifile so reset the safeguard:
2846 d->toolbars_.reset();
2848 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2849 << "Is this an include loop?");
2853 uifiles.push_back(uifile);
2855 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2857 ReturnValues retval = readUIFile(ui_path);
2859 if (retval == FormatMismatch) {
2860 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2861 TempFile tmp("convertXXXXXX.ui");
2862 FileName const tempfile = tmp.name();
2863 bool const success = prefs2prefs(ui_path, tempfile, true);
2865 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2866 " to format " << LFUN_FORMAT << ".");
2868 retval = readUIFile(tempfile);
2872 if (retval != ReadOK) {
2873 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2881 settings.beginGroup("ui_files");
2882 bool touched = false;
2883 for (int i = 0; i != uifiles.size(); ++i) {
2884 QFileInfo fi(uifiles[i]);
2885 QDateTime const date_value = fi.lastModified();
2886 QString const name_key = QString::number(i);
2887 // if an ui file which defines Toolbars has changed,
2888 // we have to reset the settings
2889 if (toolbar_uifiles.contains(uifiles[i])
2890 && (!settings.contains(name_key)
2891 || settings.value(name_key).toString() != uifiles[i]
2892 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2894 settings.setValue(name_key, uifiles[i]);
2895 settings.setValue(name_key + "/date", date_value);
2898 settings.endGroup();
2900 settings.remove("views");
2906 void GuiApplication::onLastWindowClosed()
2908 if (d->global_menubar_)
2909 d->global_menubar_->grabKeyboard();
2913 void GuiApplication::startLongOperation() {
2914 d->key_checker_.start();
2918 bool GuiApplication::longOperationCancelled() {
2919 return d->key_checker_.pressed();
2923 void GuiApplication::stopLongOperation() {
2924 d->key_checker_.stop();
2928 bool GuiApplication::longOperationStarted() {
2929 return d->key_checker_.started();
2933 ////////////////////////////////////////////////////////////////////////
2935 // X11 specific stuff goes here...
2938 bool GuiApplication::x11EventFilter(XEvent * xev)
2943 switch (xev->type) {
2944 case SelectionRequest: {
2945 if (xev->xselectionrequest.selection != XA_PRIMARY)
2947 LYXERR(Debug::SELECTION, "X requested selection.");
2948 BufferView * bv = current_view_->currentBufferView();
2950 docstring const sel = bv->requestSelection();
2952 d->selection_.put(sel);
2956 case SelectionClear: {
2957 if (xev->xselectionclear.selection != XA_PRIMARY)
2959 LYXERR(Debug::SELECTION, "Lost selection.");
2960 BufferView * bv = current_view_->currentBufferView();
2962 bv->clearSelection();
2970 } // namespace frontend
2973 void hideDialogs(std::string const & name, Inset * inset)
2976 frontend::guiApp->hideDialogs(name, inset);
2980 ////////////////////////////////////////////////////////////////////
2984 ////////////////////////////////////////////////////////////////////
2986 frontend::FontLoader & theFontLoader()
2988 LAPPERR(frontend::guiApp);
2989 return frontend::guiApp->fontLoader();
2993 frontend::FontMetrics const & theFontMetrics(Font const & f)
2995 return theFontMetrics(f.fontInfo());
2999 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3001 LAPPERR(frontend::guiApp);
3002 return frontend::guiApp->fontLoader().metrics(f);
3006 ////////////////////////////////////////////////////////////////////
3010 ////////////////////////////////////////////////////////////////////
3012 frontend::Clipboard & theClipboard()
3014 LAPPERR(frontend::guiApp);
3015 return frontend::guiApp->clipboard();
3019 frontend::Selection & theSelection()
3021 LAPPERR(frontend::guiApp);
3022 return frontend::guiApp->selection();
3028 #include "moc_GuiApplication.cpp"